1 //===- CodeGenSchedule.cpp - Scheduling MachineModels ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines structures to encapsulate the machine model as described in
11 // the target description.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "CodeGenSchedule.h"
16 #include "CodeGenTarget.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Regex.h"
20 #include "llvm/TableGen/Error.h"
21 
22 using namespace llvm;
23 
24 #define DEBUG_TYPE "subtarget-emitter"
25 
26 #ifndef NDEBUG
27 static void dumpIdxVec(ArrayRef<unsigned> V) {
28   for (unsigned Idx : V)
29     dbgs() << Idx << ", ";
30 }
31 #endif
32 
33 namespace {
34 // (instrs a, b, ...) Evaluate and union all arguments. Identical to AddOp.
35 struct InstrsOp : public SetTheory::Operator {
36   void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
37              ArrayRef<SMLoc> Loc) override {
38     ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts, Loc);
39   }
40 };
41 
42 // (instregex "OpcPat",...) Find all instructions matching an opcode pattern.
43 //
44 // TODO: Since this is a prefix match, perform a binary search over the
45 // instruction names using lower_bound. Note that the predefined instrs must be
46 // scanned linearly first. However, this is only safe if the regex pattern has
47 // no top-level bars. The DAG already has a list of patterns, so there's no
48 // reason to use top-level bars, but we need a way to verify they don't exist
49 // before implementing the optimization.
50 struct InstRegexOp : public SetTheory::Operator {
51   const CodeGenTarget &Target;
52   InstRegexOp(const CodeGenTarget &t): Target(t) {}
53 
54   void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
55              ArrayRef<SMLoc> Loc) override {
56     SmallVector<Regex, 4> RegexList;
57     for (DagInit::const_arg_iterator
58            AI = Expr->arg_begin(), AE = Expr->arg_end(); AI != AE; ++AI) {
59       StringInit *SI = dyn_cast<StringInit>(*AI);
60       if (!SI)
61         PrintFatalError(Loc, "instregex requires pattern string: "
62           + Expr->getAsString());
63       std::string pat = SI->getValue();
64       // Implement a python-style prefix match.
65       if (pat[0] != '^') {
66         pat.insert(0, "^(");
67         pat.insert(pat.end(), ')');
68       }
69       RegexList.push_back(Regex(pat));
70     }
71     for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
72       for (auto &R : RegexList) {
73         if (R.match(Inst->TheDef->getName()))
74           Elts.insert(Inst->TheDef);
75       }
76     }
77   }
78 };
79 } // end anonymous namespace
80 
81 /// CodeGenModels ctor interprets machine model records and populates maps.
82 CodeGenSchedModels::CodeGenSchedModels(RecordKeeper &RK,
83                                        const CodeGenTarget &TGT):
84   Records(RK), Target(TGT) {
85 
86   Sets.addFieldExpander("InstRW", "Instrs");
87 
88   // Allow Set evaluation to recognize the dags used in InstRW records:
89   // (instrs Op1, Op1...)
90   Sets.addOperator("instrs", llvm::make_unique<InstrsOp>());
91   Sets.addOperator("instregex", llvm::make_unique<InstRegexOp>(Target));
92 
93   // Instantiate a CodeGenProcModel for each SchedMachineModel with the values
94   // that are explicitly referenced in tablegen records. Resources associated
95   // with each processor will be derived later. Populate ProcModelMap with the
96   // CodeGenProcModel instances.
97   collectProcModels();
98 
99   // Instantiate a CodeGenSchedRW for each SchedReadWrite record explicitly
100   // defined, and populate SchedReads and SchedWrites vectors. Implicit
101   // SchedReadWrites that represent sequences derived from expanded variant will
102   // be inferred later.
103   collectSchedRW();
104 
105   // Instantiate a CodeGenSchedClass for each unique SchedRW signature directly
106   // required by an instruction definition, and populate SchedClassIdxMap. Set
107   // NumItineraryClasses to the number of explicit itinerary classes referenced
108   // by instructions. Set NumInstrSchedClasses to the number of itinerary
109   // classes plus any classes implied by instructions that derive from class
110   // Sched and provide SchedRW list. This does not infer any new classes from
111   // SchedVariant.
112   collectSchedClasses();
113 
114   // Find instruction itineraries for each processor. Sort and populate
115   // CodeGenProcModel::ItinDefList. (Cycle-to-cycle itineraries). This requires
116   // all itinerary classes to be discovered.
117   collectProcItins();
118 
119   // Find ItinRW records for each processor and itinerary class.
120   // (For per-operand resources mapped to itinerary classes).
121   collectProcItinRW();
122 
123   // Infer new SchedClasses from SchedVariant.
124   inferSchedClasses();
125 
126   // Populate each CodeGenProcModel's WriteResDefs, ReadAdvanceDefs, and
127   // ProcResourceDefs.
128   collectProcResources();
129 
130   checkCompleteness();
131 }
132 
133 /// Gather all processor models.
134 void CodeGenSchedModels::collectProcModels() {
135   RecVec ProcRecords = Records.getAllDerivedDefinitions("Processor");
136   std::sort(ProcRecords.begin(), ProcRecords.end(), LessRecordFieldName());
137 
138   // Reserve space because we can. Reallocation would be ok.
139   ProcModels.reserve(ProcRecords.size()+1);
140 
141   // Use idx=0 for NoModel/NoItineraries.
142   Record *NoModelDef = Records.getDef("NoSchedModel");
143   Record *NoItinsDef = Records.getDef("NoItineraries");
144   ProcModels.emplace_back(0, "NoSchedModel", NoModelDef, NoItinsDef);
145   ProcModelMap[NoModelDef] = 0;
146 
147   // For each processor, find a unique machine model.
148   for (unsigned i = 0, N = ProcRecords.size(); i < N; ++i)
149     addProcModel(ProcRecords[i]);
150 }
151 
152 /// Get a unique processor model based on the defined MachineModel and
153 /// ProcessorItineraries.
154 void CodeGenSchedModels::addProcModel(Record *ProcDef) {
155   Record *ModelKey = getModelOrItinDef(ProcDef);
156   if (!ProcModelMap.insert(std::make_pair(ModelKey, ProcModels.size())).second)
157     return;
158 
159   std::string Name = ModelKey->getName();
160   if (ModelKey->isSubClassOf("SchedMachineModel")) {
161     Record *ItinsDef = ModelKey->getValueAsDef("Itineraries");
162     ProcModels.emplace_back(ProcModels.size(), Name, ModelKey, ItinsDef);
163   }
164   else {
165     // An itinerary is defined without a machine model. Infer a new model.
166     if (!ModelKey->getValueAsListOfDefs("IID").empty())
167       Name = Name + "Model";
168     ProcModels.emplace_back(ProcModels.size(), Name,
169                             ProcDef->getValueAsDef("SchedModel"), ModelKey);
170   }
171   DEBUG(ProcModels.back().dump());
172 }
173 
174 // Recursively find all reachable SchedReadWrite records.
175 static void scanSchedRW(Record *RWDef, RecVec &RWDefs,
176                         SmallPtrSet<Record*, 16> &RWSet) {
177   if (!RWSet.insert(RWDef).second)
178     return;
179   RWDefs.push_back(RWDef);
180   // Reads don't current have sequence records, but it can be added later.
181   if (RWDef->isSubClassOf("WriteSequence")) {
182     RecVec Seq = RWDef->getValueAsListOfDefs("Writes");
183     for (RecIter I = Seq.begin(), E = Seq.end(); I != E; ++I)
184       scanSchedRW(*I, RWDefs, RWSet);
185   }
186   else if (RWDef->isSubClassOf("SchedVariant")) {
187     // Visit each variant (guarded by a different predicate).
188     RecVec Vars = RWDef->getValueAsListOfDefs("Variants");
189     for (RecIter VI = Vars.begin(), VE = Vars.end(); VI != VE; ++VI) {
190       // Visit each RW in the sequence selected by the current variant.
191       RecVec Selected = (*VI)->getValueAsListOfDefs("Selected");
192       for (RecIter I = Selected.begin(), E = Selected.end(); I != E; ++I)
193         scanSchedRW(*I, RWDefs, RWSet);
194     }
195   }
196 }
197 
198 // Collect and sort all SchedReadWrites reachable via tablegen records.
199 // More may be inferred later when inferring new SchedClasses from variants.
200 void CodeGenSchedModels::collectSchedRW() {
201   // Reserve idx=0 for invalid writes/reads.
202   SchedWrites.resize(1);
203   SchedReads.resize(1);
204 
205   SmallPtrSet<Record*, 16> RWSet;
206 
207   // Find all SchedReadWrites referenced by instruction defs.
208   RecVec SWDefs, SRDefs;
209   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
210     Record *SchedDef = Inst->TheDef;
211     if (SchedDef->isValueUnset("SchedRW"))
212       continue;
213     RecVec RWs = SchedDef->getValueAsListOfDefs("SchedRW");
214     for (RecIter RWI = RWs.begin(), RWE = RWs.end(); RWI != RWE; ++RWI) {
215       if ((*RWI)->isSubClassOf("SchedWrite"))
216         scanSchedRW(*RWI, SWDefs, RWSet);
217       else {
218         assert((*RWI)->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
219         scanSchedRW(*RWI, SRDefs, RWSet);
220       }
221     }
222   }
223   // Find all ReadWrites referenced by InstRW.
224   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
225   for (RecIter OI = InstRWDefs.begin(), OE = InstRWDefs.end(); OI != OE; ++OI) {
226     // For all OperandReadWrites.
227     RecVec RWDefs = (*OI)->getValueAsListOfDefs("OperandReadWrites");
228     for (RecIter RWI = RWDefs.begin(), RWE = RWDefs.end();
229          RWI != RWE; ++RWI) {
230       if ((*RWI)->isSubClassOf("SchedWrite"))
231         scanSchedRW(*RWI, SWDefs, RWSet);
232       else {
233         assert((*RWI)->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
234         scanSchedRW(*RWI, SRDefs, RWSet);
235       }
236     }
237   }
238   // Find all ReadWrites referenced by ItinRW.
239   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
240   for (RecIter II = ItinRWDefs.begin(), IE = ItinRWDefs.end(); II != IE; ++II) {
241     // For all OperandReadWrites.
242     RecVec RWDefs = (*II)->getValueAsListOfDefs("OperandReadWrites");
243     for (RecIter RWI = RWDefs.begin(), RWE = RWDefs.end();
244          RWI != RWE; ++RWI) {
245       if ((*RWI)->isSubClassOf("SchedWrite"))
246         scanSchedRW(*RWI, SWDefs, RWSet);
247       else {
248         assert((*RWI)->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
249         scanSchedRW(*RWI, SRDefs, RWSet);
250       }
251     }
252   }
253   // Find all ReadWrites referenced by SchedAlias. AliasDefs needs to be sorted
254   // for the loop below that initializes Alias vectors.
255   RecVec AliasDefs = Records.getAllDerivedDefinitions("SchedAlias");
256   std::sort(AliasDefs.begin(), AliasDefs.end(), LessRecord());
257   for (RecIter AI = AliasDefs.begin(), AE = AliasDefs.end(); AI != AE; ++AI) {
258     Record *MatchDef = (*AI)->getValueAsDef("MatchRW");
259     Record *AliasDef = (*AI)->getValueAsDef("AliasRW");
260     if (MatchDef->isSubClassOf("SchedWrite")) {
261       if (!AliasDef->isSubClassOf("SchedWrite"))
262         PrintFatalError((*AI)->getLoc(), "SchedWrite Alias must be SchedWrite");
263       scanSchedRW(AliasDef, SWDefs, RWSet);
264     }
265     else {
266       assert(MatchDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
267       if (!AliasDef->isSubClassOf("SchedRead"))
268         PrintFatalError((*AI)->getLoc(), "SchedRead Alias must be SchedRead");
269       scanSchedRW(AliasDef, SRDefs, RWSet);
270     }
271   }
272   // Sort and add the SchedReadWrites directly referenced by instructions or
273   // itinerary resources. Index reads and writes in separate domains.
274   std::sort(SWDefs.begin(), SWDefs.end(), LessRecord());
275   for (RecIter SWI = SWDefs.begin(), SWE = SWDefs.end(); SWI != SWE; ++SWI) {
276     assert(!getSchedRWIdx(*SWI, /*IsRead=*/false) && "duplicate SchedWrite");
277     SchedWrites.emplace_back(SchedWrites.size(), *SWI);
278   }
279   std::sort(SRDefs.begin(), SRDefs.end(), LessRecord());
280   for (RecIter SRI = SRDefs.begin(), SRE = SRDefs.end(); SRI != SRE; ++SRI) {
281     assert(!getSchedRWIdx(*SRI, /*IsRead-*/true) && "duplicate SchedWrite");
282     SchedReads.emplace_back(SchedReads.size(), *SRI);
283   }
284   // Initialize WriteSequence vectors.
285   for (std::vector<CodeGenSchedRW>::iterator WI = SchedWrites.begin(),
286          WE = SchedWrites.end(); WI != WE; ++WI) {
287     if (!WI->IsSequence)
288       continue;
289     findRWs(WI->TheDef->getValueAsListOfDefs("Writes"), WI->Sequence,
290             /*IsRead=*/false);
291   }
292   // Initialize Aliases vectors.
293   for (RecIter AI = AliasDefs.begin(), AE = AliasDefs.end(); AI != AE; ++AI) {
294     Record *AliasDef = (*AI)->getValueAsDef("AliasRW");
295     getSchedRW(AliasDef).IsAlias = true;
296     Record *MatchDef = (*AI)->getValueAsDef("MatchRW");
297     CodeGenSchedRW &RW = getSchedRW(MatchDef);
298     if (RW.IsAlias)
299       PrintFatalError((*AI)->getLoc(), "Cannot Alias an Alias");
300     RW.Aliases.push_back(*AI);
301   }
302   DEBUG(
303     for (unsigned WIdx = 0, WEnd = SchedWrites.size(); WIdx != WEnd; ++WIdx) {
304       dbgs() << WIdx << ": ";
305       SchedWrites[WIdx].dump();
306       dbgs() << '\n';
307     }
308     for (unsigned RIdx = 0, REnd = SchedReads.size(); RIdx != REnd; ++RIdx) {
309       dbgs() << RIdx << ": ";
310       SchedReads[RIdx].dump();
311       dbgs() << '\n';
312     }
313     RecVec RWDefs = Records.getAllDerivedDefinitions("SchedReadWrite");
314     for (RecIter RI = RWDefs.begin(), RE = RWDefs.end();
315          RI != RE; ++RI) {
316       if (!getSchedRWIdx(*RI, (*RI)->isSubClassOf("SchedRead"))) {
317         const std::string &Name = (*RI)->getName();
318         if (Name != "NoWrite" && Name != "ReadDefault")
319           dbgs() << "Unused SchedReadWrite " << (*RI)->getName() << '\n';
320       }
321     });
322 }
323 
324 /// Compute a SchedWrite name from a sequence of writes.
325 std::string CodeGenSchedModels::genRWName(ArrayRef<unsigned> Seq, bool IsRead) {
326   std::string Name("(");
327   for (auto I = Seq.begin(), E = Seq.end(); I != E; ++I) {
328     if (I != Seq.begin())
329       Name += '_';
330     Name += getSchedRW(*I, IsRead).Name;
331   }
332   Name += ')';
333   return Name;
334 }
335 
336 unsigned CodeGenSchedModels::getSchedRWIdx(Record *Def, bool IsRead,
337                                            unsigned After) const {
338   const std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
339   assert(After < RWVec.size() && "start position out of bounds");
340   for (std::vector<CodeGenSchedRW>::const_iterator I = RWVec.begin() + After,
341          E = RWVec.end(); I != E; ++I) {
342     if (I->TheDef == Def)
343       return I - RWVec.begin();
344   }
345   return 0;
346 }
347 
348 bool CodeGenSchedModels::hasReadOfWrite(Record *WriteDef) const {
349   for (unsigned i = 0, e = SchedReads.size(); i < e; ++i) {
350     Record *ReadDef = SchedReads[i].TheDef;
351     if (!ReadDef || !ReadDef->isSubClassOf("ProcReadAdvance"))
352       continue;
353 
354     RecVec ValidWrites = ReadDef->getValueAsListOfDefs("ValidWrites");
355     if (std::find(ValidWrites.begin(), ValidWrites.end(), WriteDef)
356         != ValidWrites.end()) {
357       return true;
358     }
359   }
360   return false;
361 }
362 
363 namespace llvm {
364 void splitSchedReadWrites(const RecVec &RWDefs,
365                           RecVec &WriteDefs, RecVec &ReadDefs) {
366   for (RecIter RWI = RWDefs.begin(), RWE = RWDefs.end(); RWI != RWE; ++RWI) {
367     if ((*RWI)->isSubClassOf("SchedWrite"))
368       WriteDefs.push_back(*RWI);
369     else {
370       assert((*RWI)->isSubClassOf("SchedRead") && "unknown SchedReadWrite");
371       ReadDefs.push_back(*RWI);
372     }
373   }
374 }
375 } // namespace llvm
376 
377 // Split the SchedReadWrites defs and call findRWs for each list.
378 void CodeGenSchedModels::findRWs(const RecVec &RWDefs,
379                                  IdxVec &Writes, IdxVec &Reads) const {
380     RecVec WriteDefs;
381     RecVec ReadDefs;
382     splitSchedReadWrites(RWDefs, WriteDefs, ReadDefs);
383     findRWs(WriteDefs, Writes, false);
384     findRWs(ReadDefs, Reads, true);
385 }
386 
387 // Call getSchedRWIdx for all elements in a sequence of SchedRW defs.
388 void CodeGenSchedModels::findRWs(const RecVec &RWDefs, IdxVec &RWs,
389                                  bool IsRead) const {
390   for (RecIter RI = RWDefs.begin(), RE = RWDefs.end(); RI != RE; ++RI) {
391     unsigned Idx = getSchedRWIdx(*RI, IsRead);
392     assert(Idx && "failed to collect SchedReadWrite");
393     RWs.push_back(Idx);
394   }
395 }
396 
397 void CodeGenSchedModels::expandRWSequence(unsigned RWIdx, IdxVec &RWSeq,
398                                           bool IsRead) const {
399   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
400   if (!SchedRW.IsSequence) {
401     RWSeq.push_back(RWIdx);
402     return;
403   }
404   int Repeat =
405     SchedRW.TheDef ? SchedRW.TheDef->getValueAsInt("Repeat") : 1;
406   for (int i = 0; i < Repeat; ++i) {
407     for (IdxIter I = SchedRW.Sequence.begin(), E = SchedRW.Sequence.end();
408          I != E; ++I) {
409       expandRWSequence(*I, RWSeq, IsRead);
410     }
411   }
412 }
413 
414 // Expand a SchedWrite as a sequence following any aliases that coincide with
415 // the given processor model.
416 void CodeGenSchedModels::expandRWSeqForProc(
417   unsigned RWIdx, IdxVec &RWSeq, bool IsRead,
418   const CodeGenProcModel &ProcModel) const {
419 
420   const CodeGenSchedRW &SchedWrite = getSchedRW(RWIdx, IsRead);
421   Record *AliasDef = nullptr;
422   for (RecIter AI = SchedWrite.Aliases.begin(), AE = SchedWrite.Aliases.end();
423        AI != AE; ++AI) {
424     const CodeGenSchedRW &AliasRW = getSchedRW((*AI)->getValueAsDef("AliasRW"));
425     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
426       Record *ModelDef = (*AI)->getValueAsDef("SchedModel");
427       if (&getProcModel(ModelDef) != &ProcModel)
428         continue;
429     }
430     if (AliasDef)
431       PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
432                       "defined for processor " + ProcModel.ModelName +
433                       " Ensure only one SchedAlias exists per RW.");
434     AliasDef = AliasRW.TheDef;
435   }
436   if (AliasDef) {
437     expandRWSeqForProc(getSchedRWIdx(AliasDef, IsRead),
438                        RWSeq, IsRead,ProcModel);
439     return;
440   }
441   if (!SchedWrite.IsSequence) {
442     RWSeq.push_back(RWIdx);
443     return;
444   }
445   int Repeat =
446     SchedWrite.TheDef ? SchedWrite.TheDef->getValueAsInt("Repeat") : 1;
447   for (int i = 0; i < Repeat; ++i) {
448     for (IdxIter I = SchedWrite.Sequence.begin(), E = SchedWrite.Sequence.end();
449          I != E; ++I) {
450       expandRWSeqForProc(*I, RWSeq, IsRead, ProcModel);
451     }
452   }
453 }
454 
455 // Find the existing SchedWrite that models this sequence of writes.
456 unsigned CodeGenSchedModels::findRWForSequence(ArrayRef<unsigned> Seq,
457                                                bool IsRead) {
458   std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
459 
460   for (std::vector<CodeGenSchedRW>::iterator I = RWVec.begin(), E = RWVec.end();
461        I != E; ++I) {
462     if (makeArrayRef(I->Sequence) == Seq)
463       return I - RWVec.begin();
464   }
465   // Index zero reserved for invalid RW.
466   return 0;
467 }
468 
469 /// Add this ReadWrite if it doesn't already exist.
470 unsigned CodeGenSchedModels::findOrInsertRW(ArrayRef<unsigned> Seq,
471                                             bool IsRead) {
472   assert(!Seq.empty() && "cannot insert empty sequence");
473   if (Seq.size() == 1)
474     return Seq.back();
475 
476   unsigned Idx = findRWForSequence(Seq, IsRead);
477   if (Idx)
478     return Idx;
479 
480   unsigned RWIdx = IsRead ? SchedReads.size() : SchedWrites.size();
481   CodeGenSchedRW SchedRW(RWIdx, IsRead, Seq, genRWName(Seq, IsRead));
482   if (IsRead)
483     SchedReads.push_back(SchedRW);
484   else
485     SchedWrites.push_back(SchedRW);
486   return RWIdx;
487 }
488 
489 /// Visit all the instruction definitions for this target to gather and
490 /// enumerate the itinerary classes. These are the explicitly specified
491 /// SchedClasses. More SchedClasses may be inferred.
492 void CodeGenSchedModels::collectSchedClasses() {
493 
494   // NoItinerary is always the first class at Idx=0
495   SchedClasses.resize(1);
496   SchedClasses.back().Index = 0;
497   SchedClasses.back().Name = "NoInstrModel";
498   SchedClasses.back().ItinClassDef = Records.getDef("NoItinerary");
499   SchedClasses.back().ProcIndices.push_back(0);
500 
501   // Create a SchedClass for each unique combination of itinerary class and
502   // SchedRW list.
503   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
504     Record *ItinDef = Inst->TheDef->getValueAsDef("Itinerary");
505     IdxVec Writes, Reads;
506     if (!Inst->TheDef->isValueUnset("SchedRW"))
507       findRWs(Inst->TheDef->getValueAsListOfDefs("SchedRW"), Writes, Reads);
508 
509     // ProcIdx == 0 indicates the class applies to all processors.
510     IdxVec ProcIndices(1, 0);
511 
512     unsigned SCIdx = addSchedClass(ItinDef, Writes, Reads, ProcIndices);
513     InstrClassMap[Inst->TheDef] = SCIdx;
514   }
515   // Create classes for InstRW defs.
516   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
517   std::sort(InstRWDefs.begin(), InstRWDefs.end(), LessRecord());
518   for (RecIter OI = InstRWDefs.begin(), OE = InstRWDefs.end(); OI != OE; ++OI)
519     createInstRWClass(*OI);
520 
521   NumInstrSchedClasses = SchedClasses.size();
522 
523   bool EnableDump = false;
524   DEBUG(EnableDump = true);
525   if (!EnableDump)
526     return;
527 
528   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
529     std::string InstName = Inst->TheDef->getName();
530     unsigned SCIdx = InstrClassMap.lookup(Inst->TheDef);
531     if (!SCIdx) {
532       if (!Inst->hasNoSchedulingInfo)
533         dbgs() << "No machine model for " << Inst->TheDef->getName() << '\n';
534       continue;
535     }
536     CodeGenSchedClass &SC = getSchedClass(SCIdx);
537     if (SC.ProcIndices[0] != 0)
538       PrintFatalError(Inst->TheDef->getLoc(), "Instruction's sched class "
539                       "must not be subtarget specific.");
540 
541     IdxVec ProcIndices;
542     if (SC.ItinClassDef->getName() != "NoItinerary") {
543       ProcIndices.push_back(0);
544       dbgs() << "Itinerary for " << InstName << ": "
545              << SC.ItinClassDef->getName() << '\n';
546     }
547     if (!SC.Writes.empty()) {
548       ProcIndices.push_back(0);
549       dbgs() << "SchedRW machine model for " << InstName;
550       for (IdxIter WI = SC.Writes.begin(), WE = SC.Writes.end(); WI != WE; ++WI)
551         dbgs() << " " << SchedWrites[*WI].Name;
552       for (IdxIter RI = SC.Reads.begin(), RE = SC.Reads.end(); RI != RE; ++RI)
553         dbgs() << " " << SchedReads[*RI].Name;
554       dbgs() << '\n';
555     }
556     const RecVec &RWDefs = SchedClasses[SCIdx].InstRWs;
557     for (RecIter RWI = RWDefs.begin(), RWE = RWDefs.end();
558          RWI != RWE; ++RWI) {
559       const CodeGenProcModel &ProcModel =
560         getProcModel((*RWI)->getValueAsDef("SchedModel"));
561       ProcIndices.push_back(ProcModel.Index);
562       dbgs() << "InstRW on " << ProcModel.ModelName << " for " << InstName;
563       IdxVec Writes;
564       IdxVec Reads;
565       findRWs((*RWI)->getValueAsListOfDefs("OperandReadWrites"),
566               Writes, Reads);
567       for (IdxIter WI = Writes.begin(), WE = Writes.end(); WI != WE; ++WI)
568         dbgs() << " " << SchedWrites[*WI].Name;
569       for (IdxIter RI = Reads.begin(), RE = Reads.end(); RI != RE; ++RI)
570         dbgs() << " " << SchedReads[*RI].Name;
571       dbgs() << '\n';
572     }
573     for (std::vector<CodeGenProcModel>::iterator PI = ProcModels.begin(),
574            PE = ProcModels.end(); PI != PE; ++PI) {
575       if (!std::count(ProcIndices.begin(), ProcIndices.end(), PI->Index))
576         dbgs() << "No machine model for " << Inst->TheDef->getName()
577                << " on processor " << PI->ModelName << '\n';
578     }
579   }
580 }
581 
582 /// Find an SchedClass that has been inferred from a per-operand list of
583 /// SchedWrites and SchedReads.
584 unsigned CodeGenSchedModels::findSchedClassIdx(Record *ItinClassDef,
585                                                ArrayRef<unsigned> Writes,
586                                                ArrayRef<unsigned> Reads) const {
587   for (SchedClassIter I = schedClassBegin(), E = schedClassEnd(); I != E; ++I) {
588     if (I->ItinClassDef == ItinClassDef && makeArrayRef(I->Writes) == Writes &&
589         makeArrayRef(I->Reads) == Reads) {
590       return I - schedClassBegin();
591     }
592   }
593   return 0;
594 }
595 
596 // Get the SchedClass index for an instruction.
597 unsigned CodeGenSchedModels::getSchedClassIdx(
598   const CodeGenInstruction &Inst) const {
599 
600   return InstrClassMap.lookup(Inst.TheDef);
601 }
602 
603 std::string
604 CodeGenSchedModels::createSchedClassName(Record *ItinClassDef,
605                                          ArrayRef<unsigned> OperWrites,
606                                          ArrayRef<unsigned> OperReads) {
607 
608   std::string Name;
609   if (ItinClassDef && ItinClassDef->getName() != "NoItinerary")
610     Name = ItinClassDef->getName();
611   for (unsigned Idx : OperWrites) {
612     if (!Name.empty())
613       Name += '_';
614     Name += SchedWrites[Idx].Name;
615   }
616   for (unsigned Idx : OperReads) {
617     Name += '_';
618     Name += SchedReads[Idx].Name;
619   }
620   return Name;
621 }
622 
623 std::string CodeGenSchedModels::createSchedClassName(const RecVec &InstDefs) {
624 
625   std::string Name;
626   for (RecIter I = InstDefs.begin(), E = InstDefs.end(); I != E; ++I) {
627     if (I != InstDefs.begin())
628       Name += '_';
629     Name += (*I)->getName();
630   }
631   return Name;
632 }
633 
634 /// Add an inferred sched class from an itinerary class and per-operand list of
635 /// SchedWrites and SchedReads. ProcIndices contains the set of IDs of
636 /// processors that may utilize this class.
637 unsigned CodeGenSchedModels::addSchedClass(Record *ItinClassDef,
638                                            ArrayRef<unsigned> OperWrites,
639                                            ArrayRef<unsigned> OperReads,
640                                            ArrayRef<unsigned> ProcIndices) {
641   assert(!ProcIndices.empty() && "expect at least one ProcIdx");
642 
643   unsigned Idx = findSchedClassIdx(ItinClassDef, OperWrites, OperReads);
644   if (Idx || SchedClasses[0].isKeyEqual(ItinClassDef, OperWrites, OperReads)) {
645     IdxVec PI;
646     std::set_union(SchedClasses[Idx].ProcIndices.begin(),
647                    SchedClasses[Idx].ProcIndices.end(),
648                    ProcIndices.begin(), ProcIndices.end(),
649                    std::back_inserter(PI));
650     SchedClasses[Idx].ProcIndices.swap(PI);
651     return Idx;
652   }
653   Idx = SchedClasses.size();
654   SchedClasses.resize(Idx+1);
655   CodeGenSchedClass &SC = SchedClasses.back();
656   SC.Index = Idx;
657   SC.Name = createSchedClassName(ItinClassDef, OperWrites, OperReads);
658   SC.ItinClassDef = ItinClassDef;
659   SC.Writes = OperWrites;
660   SC.Reads = OperReads;
661   SC.ProcIndices = ProcIndices;
662 
663   return Idx;
664 }
665 
666 // Create classes for each set of opcodes that are in the same InstReadWrite
667 // definition across all processors.
668 void CodeGenSchedModels::createInstRWClass(Record *InstRWDef) {
669   // ClassInstrs will hold an entry for each subset of Instrs in InstRWDef that
670   // intersects with an existing class via a previous InstRWDef. Instrs that do
671   // not intersect with an existing class refer back to their former class as
672   // determined from ItinDef or SchedRW.
673   SmallVector<std::pair<unsigned, SmallVector<Record *, 8> >, 4> ClassInstrs;
674   // Sort Instrs into sets.
675   const RecVec *InstDefs = Sets.expand(InstRWDef);
676   if (InstDefs->empty())
677     PrintFatalError(InstRWDef->getLoc(), "No matching instruction opcodes");
678 
679   for (RecIter I = InstDefs->begin(), E = InstDefs->end(); I != E; ++I) {
680     InstClassMapTy::const_iterator Pos = InstrClassMap.find(*I);
681     if (Pos == InstrClassMap.end())
682       PrintFatalError((*I)->getLoc(), "No sched class for instruction.");
683     unsigned SCIdx = Pos->second;
684     unsigned CIdx = 0, CEnd = ClassInstrs.size();
685     for (; CIdx != CEnd; ++CIdx) {
686       if (ClassInstrs[CIdx].first == SCIdx)
687         break;
688     }
689     if (CIdx == CEnd) {
690       ClassInstrs.resize(CEnd + 1);
691       ClassInstrs[CIdx].first = SCIdx;
692     }
693     ClassInstrs[CIdx].second.push_back(*I);
694   }
695   // For each set of Instrs, create a new class if necessary, and map or remap
696   // the Instrs to it.
697   unsigned CIdx = 0, CEnd = ClassInstrs.size();
698   for (; CIdx != CEnd; ++CIdx) {
699     unsigned OldSCIdx = ClassInstrs[CIdx].first;
700     ArrayRef<Record*> InstDefs = ClassInstrs[CIdx].second;
701     // If the all instrs in the current class are accounted for, then leave
702     // them mapped to their old class.
703     if (OldSCIdx) {
704       const RecVec &RWDefs = SchedClasses[OldSCIdx].InstRWs;
705       if (!RWDefs.empty()) {
706         const RecVec *OrigInstDefs = Sets.expand(RWDefs[0]);
707         unsigned OrigNumInstrs = 0;
708         for (RecIter I = OrigInstDefs->begin(), E = OrigInstDefs->end();
709              I != E; ++I) {
710           if (InstrClassMap[*I] == OldSCIdx)
711             ++OrigNumInstrs;
712         }
713         if (OrigNumInstrs == InstDefs.size()) {
714           assert(SchedClasses[OldSCIdx].ProcIndices[0] == 0 &&
715                  "expected a generic SchedClass");
716           DEBUG(dbgs() << "InstRW: Reuse SC " << OldSCIdx << ":"
717                 << SchedClasses[OldSCIdx].Name << " on "
718                 << InstRWDef->getValueAsDef("SchedModel")->getName() << "\n");
719           SchedClasses[OldSCIdx].InstRWs.push_back(InstRWDef);
720           continue;
721         }
722       }
723     }
724     unsigned SCIdx = SchedClasses.size();
725     SchedClasses.resize(SCIdx+1);
726     CodeGenSchedClass &SC = SchedClasses.back();
727     SC.Index = SCIdx;
728     SC.Name = createSchedClassName(InstDefs);
729     DEBUG(dbgs() << "InstRW: New SC " << SCIdx << ":" << SC.Name << " on "
730           << InstRWDef->getValueAsDef("SchedModel")->getName() << "\n");
731 
732     // Preserve ItinDef and Writes/Reads for processors without an InstRW entry.
733     SC.ItinClassDef = SchedClasses[OldSCIdx].ItinClassDef;
734     SC.Writes = SchedClasses[OldSCIdx].Writes;
735     SC.Reads = SchedClasses[OldSCIdx].Reads;
736     SC.ProcIndices.push_back(0);
737     // Map each Instr to this new class.
738     // Note that InstDefs may be a smaller list than InstRWDef's "Instrs".
739     Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
740     SmallSet<unsigned, 4> RemappedClassIDs;
741     for (ArrayRef<Record*>::const_iterator
742            II = InstDefs.begin(), IE = InstDefs.end(); II != IE; ++II) {
743       unsigned OldSCIdx = InstrClassMap[*II];
744       if (OldSCIdx && RemappedClassIDs.insert(OldSCIdx).second) {
745         for (RecIter RI = SchedClasses[OldSCIdx].InstRWs.begin(),
746                RE = SchedClasses[OldSCIdx].InstRWs.end(); RI != RE; ++RI) {
747           if ((*RI)->getValueAsDef("SchedModel") == RWModelDef) {
748             PrintFatalError(InstRWDef->getLoc(), "Overlapping InstRW def " +
749                           (*II)->getName() + " also matches " +
750                           (*RI)->getValue("Instrs")->getValue()->getAsString());
751           }
752           assert(*RI != InstRWDef && "SchedClass has duplicate InstRW def");
753           SC.InstRWs.push_back(*RI);
754         }
755       }
756       InstrClassMap[*II] = SCIdx;
757     }
758     SC.InstRWs.push_back(InstRWDef);
759   }
760 }
761 
762 // True if collectProcItins found anything.
763 bool CodeGenSchedModels::hasItineraries() const {
764   for (CodeGenSchedModels::ProcIter PI = procModelBegin(), PE = procModelEnd();
765        PI != PE; ++PI) {
766     if (PI->hasItineraries())
767       return true;
768   }
769   return false;
770 }
771 
772 // Gather the processor itineraries.
773 void CodeGenSchedModels::collectProcItins() {
774   for (CodeGenProcModel &ProcModel : ProcModels) {
775     if (!ProcModel.hasItineraries())
776       continue;
777 
778     RecVec ItinRecords = ProcModel.ItinsDef->getValueAsListOfDefs("IID");
779     assert(!ItinRecords.empty() && "ProcModel.hasItineraries is incorrect");
780 
781     // Populate ItinDefList with Itinerary records.
782     ProcModel.ItinDefList.resize(NumInstrSchedClasses);
783 
784     // Insert each itinerary data record in the correct position within
785     // the processor model's ItinDefList.
786     for (unsigned i = 0, N = ItinRecords.size(); i < N; i++) {
787       Record *ItinData = ItinRecords[i];
788       Record *ItinDef = ItinData->getValueAsDef("TheClass");
789       bool FoundClass = false;
790       for (SchedClassIter SCI = schedClassBegin(), SCE = schedClassEnd();
791            SCI != SCE; ++SCI) {
792         // Multiple SchedClasses may share an itinerary. Update all of them.
793         if (SCI->ItinClassDef == ItinDef) {
794           ProcModel.ItinDefList[SCI->Index] = ItinData;
795           FoundClass = true;
796         }
797       }
798       if (!FoundClass) {
799         DEBUG(dbgs() << ProcModel.ItinsDef->getName()
800               << " missing class for itinerary " << ItinDef->getName() << '\n');
801       }
802     }
803     // Check for missing itinerary entries.
804     assert(!ProcModel.ItinDefList[0] && "NoItinerary class can't have rec");
805     DEBUG(
806       for (unsigned i = 1, N = ProcModel.ItinDefList.size(); i < N; ++i) {
807         if (!ProcModel.ItinDefList[i])
808           dbgs() << ProcModel.ItinsDef->getName()
809                  << " missing itinerary for class "
810                  << SchedClasses[i].Name << '\n';
811       });
812   }
813 }
814 
815 // Gather the read/write types for each itinerary class.
816 void CodeGenSchedModels::collectProcItinRW() {
817   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
818   std::sort(ItinRWDefs.begin(), ItinRWDefs.end(), LessRecord());
819   for (RecIter II = ItinRWDefs.begin(), IE = ItinRWDefs.end(); II != IE; ++II) {
820     if (!(*II)->getValueInit("SchedModel")->isComplete())
821       PrintFatalError((*II)->getLoc(), "SchedModel is undefined");
822     Record *ModelDef = (*II)->getValueAsDef("SchedModel");
823     ProcModelMapTy::const_iterator I = ProcModelMap.find(ModelDef);
824     if (I == ProcModelMap.end()) {
825       PrintFatalError((*II)->getLoc(), "Undefined SchedMachineModel "
826                     + ModelDef->getName());
827     }
828     ProcModels[I->second].ItinRWDefs.push_back(*II);
829   }
830 }
831 
832 /// Infer new classes from existing classes. In the process, this may create new
833 /// SchedWrites from sequences of existing SchedWrites.
834 void CodeGenSchedModels::inferSchedClasses() {
835   DEBUG(dbgs() << NumInstrSchedClasses << " instr sched classes.\n");
836 
837   // Visit all existing classes and newly created classes.
838   for (unsigned Idx = 0; Idx != SchedClasses.size(); ++Idx) {
839     assert(SchedClasses[Idx].Index == Idx && "bad SCIdx");
840 
841     if (SchedClasses[Idx].ItinClassDef)
842       inferFromItinClass(SchedClasses[Idx].ItinClassDef, Idx);
843     if (!SchedClasses[Idx].InstRWs.empty())
844       inferFromInstRWs(Idx);
845     if (!SchedClasses[Idx].Writes.empty()) {
846       inferFromRW(SchedClasses[Idx].Writes, SchedClasses[Idx].Reads,
847                   Idx, SchedClasses[Idx].ProcIndices);
848     }
849     assert(SchedClasses.size() < (NumInstrSchedClasses*6) &&
850            "too many SchedVariants");
851   }
852 }
853 
854 /// Infer classes from per-processor itinerary resources.
855 void CodeGenSchedModels::inferFromItinClass(Record *ItinClassDef,
856                                             unsigned FromClassIdx) {
857   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
858     const CodeGenProcModel &PM = ProcModels[PIdx];
859     // For all ItinRW entries.
860     bool HasMatch = false;
861     for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
862          II != IE; ++II) {
863       RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
864       if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
865         continue;
866       if (HasMatch)
867         PrintFatalError((*II)->getLoc(), "Duplicate itinerary class "
868                       + ItinClassDef->getName()
869                       + " in ItinResources for " + PM.ModelName);
870       HasMatch = true;
871       IdxVec Writes, Reads;
872       findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
873       IdxVec ProcIndices(1, PIdx);
874       inferFromRW(Writes, Reads, FromClassIdx, ProcIndices);
875     }
876   }
877 }
878 
879 /// Infer classes from per-processor InstReadWrite definitions.
880 void CodeGenSchedModels::inferFromInstRWs(unsigned SCIdx) {
881   for (unsigned I = 0, E = SchedClasses[SCIdx].InstRWs.size(); I != E; ++I) {
882     assert(SchedClasses[SCIdx].InstRWs.size() == E && "InstrRWs was mutated!");
883     Record *Rec = SchedClasses[SCIdx].InstRWs[I];
884     const RecVec *InstDefs = Sets.expand(Rec);
885     RecIter II = InstDefs->begin(), IE = InstDefs->end();
886     for (; II != IE; ++II) {
887       if (InstrClassMap[*II] == SCIdx)
888         break;
889     }
890     // If this class no longer has any instructions mapped to it, it has become
891     // irrelevant.
892     if (II == IE)
893       continue;
894     IdxVec Writes, Reads;
895     findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
896     unsigned PIdx = getProcModel(Rec->getValueAsDef("SchedModel")).Index;
897     IdxVec ProcIndices(1, PIdx);
898     inferFromRW(Writes, Reads, SCIdx, ProcIndices); // May mutate SchedClasses.
899   }
900 }
901 
902 namespace {
903 // Helper for substituteVariantOperand.
904 struct TransVariant {
905   Record *VarOrSeqDef;  // Variant or sequence.
906   unsigned RWIdx;       // Index of this variant or sequence's matched type.
907   unsigned ProcIdx;     // Processor model index or zero for any.
908   unsigned TransVecIdx; // Index into PredTransitions::TransVec.
909 
910   TransVariant(Record *def, unsigned rwi, unsigned pi, unsigned ti):
911     VarOrSeqDef(def), RWIdx(rwi), ProcIdx(pi), TransVecIdx(ti) {}
912 };
913 
914 // Associate a predicate with the SchedReadWrite that it guards.
915 // RWIdx is the index of the read/write variant.
916 struct PredCheck {
917   bool IsRead;
918   unsigned RWIdx;
919   Record *Predicate;
920 
921   PredCheck(bool r, unsigned w, Record *p): IsRead(r), RWIdx(w), Predicate(p) {}
922 };
923 
924 // A Predicate transition is a list of RW sequences guarded by a PredTerm.
925 struct PredTransition {
926   // A predicate term is a conjunction of PredChecks.
927   SmallVector<PredCheck, 4> PredTerm;
928   SmallVector<SmallVector<unsigned,4>, 16> WriteSequences;
929   SmallVector<SmallVector<unsigned,4>, 16> ReadSequences;
930   SmallVector<unsigned, 4> ProcIndices;
931 };
932 
933 // Encapsulate a set of partially constructed transitions.
934 // The results are built by repeated calls to substituteVariants.
935 class PredTransitions {
936   CodeGenSchedModels &SchedModels;
937 
938 public:
939   std::vector<PredTransition> TransVec;
940 
941   PredTransitions(CodeGenSchedModels &sm): SchedModels(sm) {}
942 
943   void substituteVariantOperand(const SmallVectorImpl<unsigned> &RWSeq,
944                                 bool IsRead, unsigned StartIdx);
945 
946   void substituteVariants(const PredTransition &Trans);
947 
948 #ifndef NDEBUG
949   void dump() const;
950 #endif
951 
952 private:
953   bool mutuallyExclusive(Record *PredDef, ArrayRef<PredCheck> Term);
954   void getIntersectingVariants(
955     const CodeGenSchedRW &SchedRW, unsigned TransIdx,
956     std::vector<TransVariant> &IntersectingVariants);
957   void pushVariant(const TransVariant &VInfo, bool IsRead);
958 };
959 } // anonymous
960 
961 // Return true if this predicate is mutually exclusive with a PredTerm. This
962 // degenerates into checking if the predicate is mutually exclusive with any
963 // predicate in the Term's conjunction.
964 //
965 // All predicates associated with a given SchedRW are considered mutually
966 // exclusive. This should work even if the conditions expressed by the
967 // predicates are not exclusive because the predicates for a given SchedWrite
968 // are always checked in the order they are defined in the .td file. Later
969 // conditions implicitly negate any prior condition.
970 bool PredTransitions::mutuallyExclusive(Record *PredDef,
971                                         ArrayRef<PredCheck> Term) {
972 
973   for (ArrayRef<PredCheck>::iterator I = Term.begin(), E = Term.end();
974        I != E; ++I) {
975     if (I->Predicate == PredDef)
976       return false;
977 
978     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(I->RWIdx, I->IsRead);
979     assert(SchedRW.HasVariants && "PredCheck must refer to a SchedVariant");
980     RecVec Variants = SchedRW.TheDef->getValueAsListOfDefs("Variants");
981     for (RecIter VI = Variants.begin(), VE = Variants.end(); VI != VE; ++VI) {
982       if ((*VI)->getValueAsDef("Predicate") == PredDef)
983         return true;
984     }
985   }
986   return false;
987 }
988 
989 static bool hasAliasedVariants(const CodeGenSchedRW &RW,
990                                CodeGenSchedModels &SchedModels) {
991   if (RW.HasVariants)
992     return true;
993 
994   for (RecIter I = RW.Aliases.begin(), E = RW.Aliases.end(); I != E; ++I) {
995     const CodeGenSchedRW &AliasRW =
996       SchedModels.getSchedRW((*I)->getValueAsDef("AliasRW"));
997     if (AliasRW.HasVariants)
998       return true;
999     if (AliasRW.IsSequence) {
1000       IdxVec ExpandedRWs;
1001       SchedModels.expandRWSequence(AliasRW.Index, ExpandedRWs, AliasRW.IsRead);
1002       for (IdxIter SI = ExpandedRWs.begin(), SE = ExpandedRWs.end();
1003            SI != SE; ++SI) {
1004         if (hasAliasedVariants(SchedModels.getSchedRW(*SI, AliasRW.IsRead),
1005                                SchedModels)) {
1006           return true;
1007         }
1008       }
1009     }
1010   }
1011   return false;
1012 }
1013 
1014 static bool hasVariant(ArrayRef<PredTransition> Transitions,
1015                        CodeGenSchedModels &SchedModels) {
1016   for (ArrayRef<PredTransition>::iterator
1017          PTI = Transitions.begin(), PTE = Transitions.end();
1018        PTI != PTE; ++PTI) {
1019     for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
1020            WSI = PTI->WriteSequences.begin(), WSE = PTI->WriteSequences.end();
1021          WSI != WSE; ++WSI) {
1022       for (SmallVectorImpl<unsigned>::const_iterator
1023              WI = WSI->begin(), WE = WSI->end(); WI != WE; ++WI) {
1024         if (hasAliasedVariants(SchedModels.getSchedWrite(*WI), SchedModels))
1025           return true;
1026       }
1027     }
1028     for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
1029            RSI = PTI->ReadSequences.begin(), RSE = PTI->ReadSequences.end();
1030          RSI != RSE; ++RSI) {
1031       for (SmallVectorImpl<unsigned>::const_iterator
1032              RI = RSI->begin(), RE = RSI->end(); RI != RE; ++RI) {
1033         if (hasAliasedVariants(SchedModels.getSchedRead(*RI), SchedModels))
1034           return true;
1035       }
1036     }
1037   }
1038   return false;
1039 }
1040 
1041 // Populate IntersectingVariants with any variants or aliased sequences of the
1042 // given SchedRW whose processor indices and predicates are not mutually
1043 // exclusive with the given transition.
1044 void PredTransitions::getIntersectingVariants(
1045   const CodeGenSchedRW &SchedRW, unsigned TransIdx,
1046   std::vector<TransVariant> &IntersectingVariants) {
1047 
1048   bool GenericRW = false;
1049 
1050   std::vector<TransVariant> Variants;
1051   if (SchedRW.HasVariants) {
1052     unsigned VarProcIdx = 0;
1053     if (SchedRW.TheDef->getValueInit("SchedModel")->isComplete()) {
1054       Record *ModelDef = SchedRW.TheDef->getValueAsDef("SchedModel");
1055       VarProcIdx = SchedModels.getProcModel(ModelDef).Index;
1056     }
1057     // Push each variant. Assign TransVecIdx later.
1058     const RecVec VarDefs = SchedRW.TheDef->getValueAsListOfDefs("Variants");
1059     for (RecIter RI = VarDefs.begin(), RE = VarDefs.end(); RI != RE; ++RI)
1060       Variants.push_back(TransVariant(*RI, SchedRW.Index, VarProcIdx, 0));
1061     if (VarProcIdx == 0)
1062       GenericRW = true;
1063   }
1064   for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
1065        AI != AE; ++AI) {
1066     // If either the SchedAlias itself or the SchedReadWrite that it aliases
1067     // to is defined within a processor model, constrain all variants to
1068     // that processor.
1069     unsigned AliasProcIdx = 0;
1070     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
1071       Record *ModelDef = (*AI)->getValueAsDef("SchedModel");
1072       AliasProcIdx = SchedModels.getProcModel(ModelDef).Index;
1073     }
1074     const CodeGenSchedRW &AliasRW =
1075       SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
1076 
1077     if (AliasRW.HasVariants) {
1078       const RecVec VarDefs = AliasRW.TheDef->getValueAsListOfDefs("Variants");
1079       for (RecIter RI = VarDefs.begin(), RE = VarDefs.end(); RI != RE; ++RI)
1080         Variants.push_back(TransVariant(*RI, AliasRW.Index, AliasProcIdx, 0));
1081     }
1082     if (AliasRW.IsSequence) {
1083       Variants.push_back(
1084         TransVariant(AliasRW.TheDef, SchedRW.Index, AliasProcIdx, 0));
1085     }
1086     if (AliasProcIdx == 0)
1087       GenericRW = true;
1088   }
1089   for (unsigned VIdx = 0, VEnd = Variants.size(); VIdx != VEnd; ++VIdx) {
1090     TransVariant &Variant = Variants[VIdx];
1091     // Don't expand variants if the processor models don't intersect.
1092     // A zero processor index means any processor.
1093     SmallVectorImpl<unsigned> &ProcIndices = TransVec[TransIdx].ProcIndices;
1094     if (ProcIndices[0] && Variants[VIdx].ProcIdx) {
1095       unsigned Cnt = std::count(ProcIndices.begin(), ProcIndices.end(),
1096                                 Variant.ProcIdx);
1097       if (!Cnt)
1098         continue;
1099       if (Cnt > 1) {
1100         const CodeGenProcModel &PM =
1101           *(SchedModels.procModelBegin() + Variant.ProcIdx);
1102         PrintFatalError(Variant.VarOrSeqDef->getLoc(),
1103                         "Multiple variants defined for processor " +
1104                         PM.ModelName +
1105                         " Ensure only one SchedAlias exists per RW.");
1106       }
1107     }
1108     if (Variant.VarOrSeqDef->isSubClassOf("SchedVar")) {
1109       Record *PredDef = Variant.VarOrSeqDef->getValueAsDef("Predicate");
1110       if (mutuallyExclusive(PredDef, TransVec[TransIdx].PredTerm))
1111         continue;
1112     }
1113     if (IntersectingVariants.empty()) {
1114       // The first variant builds on the existing transition.
1115       Variant.TransVecIdx = TransIdx;
1116       IntersectingVariants.push_back(Variant);
1117     }
1118     else {
1119       // Push another copy of the current transition for more variants.
1120       Variant.TransVecIdx = TransVec.size();
1121       IntersectingVariants.push_back(Variant);
1122       TransVec.push_back(TransVec[TransIdx]);
1123     }
1124   }
1125   if (GenericRW && IntersectingVariants.empty()) {
1126     PrintFatalError(SchedRW.TheDef->getLoc(), "No variant of this type has "
1127                     "a matching predicate on any processor");
1128   }
1129 }
1130 
1131 // Push the Reads/Writes selected by this variant onto the PredTransition
1132 // specified by VInfo.
1133 void PredTransitions::
1134 pushVariant(const TransVariant &VInfo, bool IsRead) {
1135 
1136   PredTransition &Trans = TransVec[VInfo.TransVecIdx];
1137 
1138   // If this operand transition is reached through a processor-specific alias,
1139   // then the whole transition is specific to this processor.
1140   if (VInfo.ProcIdx != 0)
1141     Trans.ProcIndices.assign(1, VInfo.ProcIdx);
1142 
1143   IdxVec SelectedRWs;
1144   if (VInfo.VarOrSeqDef->isSubClassOf("SchedVar")) {
1145     Record *PredDef = VInfo.VarOrSeqDef->getValueAsDef("Predicate");
1146     Trans.PredTerm.push_back(PredCheck(IsRead, VInfo.RWIdx,PredDef));
1147     RecVec SelectedDefs = VInfo.VarOrSeqDef->getValueAsListOfDefs("Selected");
1148     SchedModels.findRWs(SelectedDefs, SelectedRWs, IsRead);
1149   }
1150   else {
1151     assert(VInfo.VarOrSeqDef->isSubClassOf("WriteSequence") &&
1152            "variant must be a SchedVariant or aliased WriteSequence");
1153     SelectedRWs.push_back(SchedModels.getSchedRWIdx(VInfo.VarOrSeqDef, IsRead));
1154   }
1155 
1156   const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(VInfo.RWIdx, IsRead);
1157 
1158   SmallVectorImpl<SmallVector<unsigned,4> > &RWSequences = IsRead
1159     ? Trans.ReadSequences : Trans.WriteSequences;
1160   if (SchedRW.IsVariadic) {
1161     unsigned OperIdx = RWSequences.size()-1;
1162     // Make N-1 copies of this transition's last sequence.
1163     for (unsigned i = 1, e = SelectedRWs.size(); i != e; ++i) {
1164       // Create a temporary copy the vector could reallocate.
1165       RWSequences.reserve(RWSequences.size() + 1);
1166       RWSequences.push_back(RWSequences[OperIdx]);
1167     }
1168     // Push each of the N elements of the SelectedRWs onto a copy of the last
1169     // sequence (split the current operand into N operands).
1170     // Note that write sequences should be expanded within this loop--the entire
1171     // sequence belongs to a single operand.
1172     for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
1173          RWI != RWE; ++RWI, ++OperIdx) {
1174       IdxVec ExpandedRWs;
1175       if (IsRead)
1176         ExpandedRWs.push_back(*RWI);
1177       else
1178         SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
1179       RWSequences[OperIdx].insert(RWSequences[OperIdx].end(),
1180                                   ExpandedRWs.begin(), ExpandedRWs.end());
1181     }
1182     assert(OperIdx == RWSequences.size() && "missed a sequence");
1183   }
1184   else {
1185     // Push this transition's expanded sequence onto this transition's last
1186     // sequence (add to the current operand's sequence).
1187     SmallVectorImpl<unsigned> &Seq = RWSequences.back();
1188     IdxVec ExpandedRWs;
1189     for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
1190          RWI != RWE; ++RWI) {
1191       if (IsRead)
1192         ExpandedRWs.push_back(*RWI);
1193       else
1194         SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
1195     }
1196     Seq.insert(Seq.end(), ExpandedRWs.begin(), ExpandedRWs.end());
1197   }
1198 }
1199 
1200 // RWSeq is a sequence of all Reads or all Writes for the next read or write
1201 // operand. StartIdx is an index into TransVec where partial results
1202 // starts. RWSeq must be applied to all transitions between StartIdx and the end
1203 // of TransVec.
1204 void PredTransitions::substituteVariantOperand(
1205   const SmallVectorImpl<unsigned> &RWSeq, bool IsRead, unsigned StartIdx) {
1206 
1207   // Visit each original RW within the current sequence.
1208   for (SmallVectorImpl<unsigned>::const_iterator
1209          RWI = RWSeq.begin(), RWE = RWSeq.end(); RWI != RWE; ++RWI) {
1210     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(*RWI, IsRead);
1211     // Push this RW on all partial PredTransitions or distribute variants.
1212     // New PredTransitions may be pushed within this loop which should not be
1213     // revisited (TransEnd must be loop invariant).
1214     for (unsigned TransIdx = StartIdx, TransEnd = TransVec.size();
1215          TransIdx != TransEnd; ++TransIdx) {
1216       // In the common case, push RW onto the current operand's sequence.
1217       if (!hasAliasedVariants(SchedRW, SchedModels)) {
1218         if (IsRead)
1219           TransVec[TransIdx].ReadSequences.back().push_back(*RWI);
1220         else
1221           TransVec[TransIdx].WriteSequences.back().push_back(*RWI);
1222         continue;
1223       }
1224       // Distribute this partial PredTransition across intersecting variants.
1225       // This will push a copies of TransVec[TransIdx] on the back of TransVec.
1226       std::vector<TransVariant> IntersectingVariants;
1227       getIntersectingVariants(SchedRW, TransIdx, IntersectingVariants);
1228       // Now expand each variant on top of its copy of the transition.
1229       for (std::vector<TransVariant>::const_iterator
1230              IVI = IntersectingVariants.begin(),
1231              IVE = IntersectingVariants.end();
1232            IVI != IVE; ++IVI) {
1233         pushVariant(*IVI, IsRead);
1234       }
1235     }
1236   }
1237 }
1238 
1239 // For each variant of a Read/Write in Trans, substitute the sequence of
1240 // Read/Writes guarded by the variant. This is exponential in the number of
1241 // variant Read/Writes, but in practice detection of mutually exclusive
1242 // predicates should result in linear growth in the total number variants.
1243 //
1244 // This is one step in a breadth-first search of nested variants.
1245 void PredTransitions::substituteVariants(const PredTransition &Trans) {
1246   // Build up a set of partial results starting at the back of
1247   // PredTransitions. Remember the first new transition.
1248   unsigned StartIdx = TransVec.size();
1249   TransVec.resize(TransVec.size() + 1);
1250   TransVec.back().PredTerm = Trans.PredTerm;
1251   TransVec.back().ProcIndices = Trans.ProcIndices;
1252 
1253   // Visit each original write sequence.
1254   for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
1255          WSI = Trans.WriteSequences.begin(), WSE = Trans.WriteSequences.end();
1256        WSI != WSE; ++WSI) {
1257     // Push a new (empty) write sequence onto all partial Transitions.
1258     for (std::vector<PredTransition>::iterator I =
1259            TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
1260       I->WriteSequences.resize(I->WriteSequences.size() + 1);
1261     }
1262     substituteVariantOperand(*WSI, /*IsRead=*/false, StartIdx);
1263   }
1264   // Visit each original read sequence.
1265   for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
1266          RSI = Trans.ReadSequences.begin(), RSE = Trans.ReadSequences.end();
1267        RSI != RSE; ++RSI) {
1268     // Push a new (empty) read sequence onto all partial Transitions.
1269     for (std::vector<PredTransition>::iterator I =
1270            TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
1271       I->ReadSequences.resize(I->ReadSequences.size() + 1);
1272     }
1273     substituteVariantOperand(*RSI, /*IsRead=*/true, StartIdx);
1274   }
1275 }
1276 
1277 // Create a new SchedClass for each variant found by inferFromRW. Pass
1278 static void inferFromTransitions(ArrayRef<PredTransition> LastTransitions,
1279                                  unsigned FromClassIdx,
1280                                  CodeGenSchedModels &SchedModels) {
1281   // For each PredTransition, create a new CodeGenSchedTransition, which usually
1282   // requires creating a new SchedClass.
1283   for (ArrayRef<PredTransition>::iterator
1284          I = LastTransitions.begin(), E = LastTransitions.end(); I != E; ++I) {
1285     IdxVec OperWritesVariant;
1286     for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
1287            WSI = I->WriteSequences.begin(), WSE = I->WriteSequences.end();
1288          WSI != WSE; ++WSI) {
1289       // Create a new write representing the expanded sequence.
1290       OperWritesVariant.push_back(
1291         SchedModels.findOrInsertRW(*WSI, /*IsRead=*/false));
1292     }
1293     IdxVec OperReadsVariant;
1294     for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
1295            RSI = I->ReadSequences.begin(), RSE = I->ReadSequences.end();
1296          RSI != RSE; ++RSI) {
1297       // Create a new read representing the expanded sequence.
1298       OperReadsVariant.push_back(
1299         SchedModels.findOrInsertRW(*RSI, /*IsRead=*/true));
1300     }
1301     IdxVec ProcIndices(I->ProcIndices.begin(), I->ProcIndices.end());
1302     CodeGenSchedTransition SCTrans;
1303     SCTrans.ToClassIdx =
1304       SchedModels.addSchedClass(/*ItinClassDef=*/nullptr, OperWritesVariant,
1305                                 OperReadsVariant, ProcIndices);
1306     SCTrans.ProcIndices = ProcIndices;
1307     // The final PredTerm is unique set of predicates guarding the transition.
1308     RecVec Preds;
1309     for (SmallVectorImpl<PredCheck>::const_iterator
1310            PI = I->PredTerm.begin(), PE = I->PredTerm.end(); PI != PE; ++PI) {
1311       Preds.push_back(PI->Predicate);
1312     }
1313     RecIter PredsEnd = std::unique(Preds.begin(), Preds.end());
1314     Preds.resize(PredsEnd - Preds.begin());
1315     SCTrans.PredTerm = Preds;
1316     SchedModels.getSchedClass(FromClassIdx).Transitions.push_back(SCTrans);
1317   }
1318 }
1319 
1320 // Create new SchedClasses for the given ReadWrite list. If any of the
1321 // ReadWrites refers to a SchedVariant, create a new SchedClass for each variant
1322 // of the ReadWrite list, following Aliases if necessary.
1323 void CodeGenSchedModels::inferFromRW(ArrayRef<unsigned> OperWrites,
1324                                      ArrayRef<unsigned> OperReads,
1325                                      unsigned FromClassIdx,
1326                                      ArrayRef<unsigned> ProcIndices) {
1327   DEBUG(dbgs() << "INFER RW proc("; dumpIdxVec(ProcIndices); dbgs() << ") ");
1328 
1329   // Create a seed transition with an empty PredTerm and the expanded sequences
1330   // of SchedWrites for the current SchedClass.
1331   std::vector<PredTransition> LastTransitions;
1332   LastTransitions.resize(1);
1333   LastTransitions.back().ProcIndices.append(ProcIndices.begin(),
1334                                             ProcIndices.end());
1335 
1336   for (unsigned WriteIdx : OperWrites) {
1337     IdxVec WriteSeq;
1338     expandRWSequence(WriteIdx, WriteSeq, /*IsRead=*/false);
1339     unsigned Idx = LastTransitions[0].WriteSequences.size();
1340     LastTransitions[0].WriteSequences.resize(Idx + 1);
1341     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].WriteSequences[Idx];
1342     for (IdxIter WI = WriteSeq.begin(), WE = WriteSeq.end(); WI != WE; ++WI)
1343       Seq.push_back(*WI);
1344     DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
1345   }
1346   DEBUG(dbgs() << " Reads: ");
1347   for (unsigned ReadIdx : OperReads) {
1348     IdxVec ReadSeq;
1349     expandRWSequence(ReadIdx, ReadSeq, /*IsRead=*/true);
1350     unsigned Idx = LastTransitions[0].ReadSequences.size();
1351     LastTransitions[0].ReadSequences.resize(Idx + 1);
1352     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].ReadSequences[Idx];
1353     for (IdxIter RI = ReadSeq.begin(), RE = ReadSeq.end(); RI != RE; ++RI)
1354       Seq.push_back(*RI);
1355     DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
1356   }
1357   DEBUG(dbgs() << '\n');
1358 
1359   // Collect all PredTransitions for individual operands.
1360   // Iterate until no variant writes remain.
1361   while (hasVariant(LastTransitions, *this)) {
1362     PredTransitions Transitions(*this);
1363     for (std::vector<PredTransition>::const_iterator
1364            I = LastTransitions.begin(), E = LastTransitions.end();
1365          I != E; ++I) {
1366       Transitions.substituteVariants(*I);
1367     }
1368     DEBUG(Transitions.dump());
1369     LastTransitions.swap(Transitions.TransVec);
1370   }
1371   // If the first transition has no variants, nothing to do.
1372   if (LastTransitions[0].PredTerm.empty())
1373     return;
1374 
1375   // WARNING: We are about to mutate the SchedClasses vector. Do not refer to
1376   // OperWrites, OperReads, or ProcIndices after calling inferFromTransitions.
1377   inferFromTransitions(LastTransitions, FromClassIdx, *this);
1378 }
1379 
1380 // Check if any processor resource group contains all resource records in
1381 // SubUnits.
1382 bool CodeGenSchedModels::hasSuperGroup(RecVec &SubUnits, CodeGenProcModel &PM) {
1383   for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
1384     if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
1385       continue;
1386     RecVec SuperUnits =
1387       PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
1388     RecIter RI = SubUnits.begin(), RE = SubUnits.end();
1389     for ( ; RI != RE; ++RI) {
1390       if (std::find(SuperUnits.begin(), SuperUnits.end(), *RI)
1391           == SuperUnits.end()) {
1392         break;
1393       }
1394     }
1395     if (RI == RE)
1396       return true;
1397   }
1398   return false;
1399 }
1400 
1401 // Verify that overlapping groups have a common supergroup.
1402 void CodeGenSchedModels::verifyProcResourceGroups(CodeGenProcModel &PM) {
1403   for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
1404     if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
1405       continue;
1406     RecVec CheckUnits =
1407       PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
1408     for (unsigned j = i+1; j < e; ++j) {
1409       if (!PM.ProcResourceDefs[j]->isSubClassOf("ProcResGroup"))
1410         continue;
1411       RecVec OtherUnits =
1412         PM.ProcResourceDefs[j]->getValueAsListOfDefs("Resources");
1413       if (std::find_first_of(CheckUnits.begin(), CheckUnits.end(),
1414                              OtherUnits.begin(), OtherUnits.end())
1415           != CheckUnits.end()) {
1416         // CheckUnits and OtherUnits overlap
1417         OtherUnits.insert(OtherUnits.end(), CheckUnits.begin(),
1418                           CheckUnits.end());
1419         if (!hasSuperGroup(OtherUnits, PM)) {
1420           PrintFatalError((PM.ProcResourceDefs[i])->getLoc(),
1421                           "proc resource group overlaps with "
1422                           + PM.ProcResourceDefs[j]->getName()
1423                           + " but no supergroup contains both.");
1424         }
1425       }
1426     }
1427   }
1428 }
1429 
1430 // Collect and sort WriteRes, ReadAdvance, and ProcResources.
1431 void CodeGenSchedModels::collectProcResources() {
1432   // Add any subtarget-specific SchedReadWrites that are directly associated
1433   // with processor resources. Refer to the parent SchedClass's ProcIndices to
1434   // determine which processors they apply to.
1435   for (SchedClassIter SCI = schedClassBegin(), SCE = schedClassEnd();
1436        SCI != SCE; ++SCI) {
1437     if (SCI->ItinClassDef)
1438       collectItinProcResources(SCI->ItinClassDef);
1439     else {
1440       // This class may have a default ReadWrite list which can be overriden by
1441       // InstRW definitions.
1442       if (!SCI->InstRWs.empty()) {
1443         for (RecIter RWI = SCI->InstRWs.begin(), RWE = SCI->InstRWs.end();
1444              RWI != RWE; ++RWI) {
1445           Record *RWModelDef = (*RWI)->getValueAsDef("SchedModel");
1446           IdxVec ProcIndices(1, getProcModel(RWModelDef).Index);
1447           IdxVec Writes, Reads;
1448           findRWs((*RWI)->getValueAsListOfDefs("OperandReadWrites"),
1449                   Writes, Reads);
1450           collectRWResources(Writes, Reads, ProcIndices);
1451         }
1452       }
1453       collectRWResources(SCI->Writes, SCI->Reads, SCI->ProcIndices);
1454     }
1455   }
1456   // Add resources separately defined by each subtarget.
1457   RecVec WRDefs = Records.getAllDerivedDefinitions("WriteRes");
1458   for (RecIter WRI = WRDefs.begin(), WRE = WRDefs.end(); WRI != WRE; ++WRI) {
1459     Record *ModelDef = (*WRI)->getValueAsDef("SchedModel");
1460     addWriteRes(*WRI, getProcModel(ModelDef).Index);
1461   }
1462   RecVec SWRDefs = Records.getAllDerivedDefinitions("SchedWriteRes");
1463   for (RecIter WRI = SWRDefs.begin(), WRE = SWRDefs.end(); WRI != WRE; ++WRI) {
1464     Record *ModelDef = (*WRI)->getValueAsDef("SchedModel");
1465     addWriteRes(*WRI, getProcModel(ModelDef).Index);
1466   }
1467   RecVec RADefs = Records.getAllDerivedDefinitions("ReadAdvance");
1468   for (RecIter RAI = RADefs.begin(), RAE = RADefs.end(); RAI != RAE; ++RAI) {
1469     Record *ModelDef = (*RAI)->getValueAsDef("SchedModel");
1470     addReadAdvance(*RAI, getProcModel(ModelDef).Index);
1471   }
1472   RecVec SRADefs = Records.getAllDerivedDefinitions("SchedReadAdvance");
1473   for (RecIter RAI = SRADefs.begin(), RAE = SRADefs.end(); RAI != RAE; ++RAI) {
1474     if ((*RAI)->getValueInit("SchedModel")->isComplete()) {
1475       Record *ModelDef = (*RAI)->getValueAsDef("SchedModel");
1476       addReadAdvance(*RAI, getProcModel(ModelDef).Index);
1477     }
1478   }
1479   // Add ProcResGroups that are defined within this processor model, which may
1480   // not be directly referenced but may directly specify a buffer size.
1481   RecVec ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
1482   for (RecIter RI = ProcResGroups.begin(), RE = ProcResGroups.end();
1483        RI != RE; ++RI) {
1484     if (!(*RI)->getValueInit("SchedModel")->isComplete())
1485       continue;
1486     CodeGenProcModel &PM = getProcModel((*RI)->getValueAsDef("SchedModel"));
1487     RecIter I = std::find(PM.ProcResourceDefs.begin(),
1488                           PM.ProcResourceDefs.end(), *RI);
1489     if (I == PM.ProcResourceDefs.end())
1490       PM.ProcResourceDefs.push_back(*RI);
1491   }
1492   // Finalize each ProcModel by sorting the record arrays.
1493   for (CodeGenProcModel &PM : ProcModels) {
1494     std::sort(PM.WriteResDefs.begin(), PM.WriteResDefs.end(),
1495               LessRecord());
1496     std::sort(PM.ReadAdvanceDefs.begin(), PM.ReadAdvanceDefs.end(),
1497               LessRecord());
1498     std::sort(PM.ProcResourceDefs.begin(), PM.ProcResourceDefs.end(),
1499               LessRecord());
1500     DEBUG(
1501       PM.dump();
1502       dbgs() << "WriteResDefs: ";
1503       for (RecIter RI = PM.WriteResDefs.begin(),
1504              RE = PM.WriteResDefs.end(); RI != RE; ++RI) {
1505         if ((*RI)->isSubClassOf("WriteRes"))
1506           dbgs() << (*RI)->getValueAsDef("WriteType")->getName() << " ";
1507         else
1508           dbgs() << (*RI)->getName() << " ";
1509       }
1510       dbgs() << "\nReadAdvanceDefs: ";
1511       for (RecIter RI = PM.ReadAdvanceDefs.begin(),
1512              RE = PM.ReadAdvanceDefs.end(); RI != RE; ++RI) {
1513         if ((*RI)->isSubClassOf("ReadAdvance"))
1514           dbgs() << (*RI)->getValueAsDef("ReadType")->getName() << " ";
1515         else
1516           dbgs() << (*RI)->getName() << " ";
1517       }
1518       dbgs() << "\nProcResourceDefs: ";
1519       for (RecIter RI = PM.ProcResourceDefs.begin(),
1520              RE = PM.ProcResourceDefs.end(); RI != RE; ++RI) {
1521         dbgs() << (*RI)->getName() << " ";
1522       }
1523       dbgs() << '\n');
1524     verifyProcResourceGroups(PM);
1525   }
1526 }
1527 
1528 void CodeGenSchedModels::checkCompleteness() {
1529   bool Complete = true;
1530   bool HadCompleteModel = false;
1531   for (const CodeGenProcModel &ProcModel : procModels()) {
1532     if (!ProcModel.ModelDef->getValueAsBit("CompleteModel"))
1533       continue;
1534     for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
1535       if (Inst->hasNoSchedulingInfo)
1536         continue;
1537       unsigned SCIdx = getSchedClassIdx(*Inst);
1538       if (!SCIdx) {
1539         if (Inst->TheDef->isValueUnset("SchedRW") && !HadCompleteModel) {
1540           PrintError("No schedule information for instruction '"
1541                      + Inst->TheDef->getName() + "'");
1542           Complete = false;
1543         }
1544         continue;
1545       }
1546 
1547       const CodeGenSchedClass &SC = getSchedClass(SCIdx);
1548       if (!SC.Writes.empty())
1549         continue;
1550       if (SC.ItinClassDef != nullptr)
1551         continue;
1552 
1553       const RecVec &InstRWs = SC.InstRWs;
1554       auto I = std::find_if(InstRWs.begin(), InstRWs.end(),
1555                             [&ProcModel] (const Record *R) {
1556                               return R->getValueAsDef("SchedModel") ==
1557                                      ProcModel.ModelDef;
1558                             });
1559       if (I == InstRWs.end()) {
1560         PrintError("'" + ProcModel.ModelName + "' lacks information for '" +
1561                    Inst->TheDef->getName() + "'");
1562         Complete = false;
1563       }
1564     }
1565     HadCompleteModel = true;
1566   }
1567   if (!Complete) {
1568     errs() << "\n\nIncomplete schedule models found.\n"
1569       << "- Consider setting 'CompleteModel = 0' while developing new models.\n"
1570       << "- Pseudo instructions can be marked with 'hasNoSchedulingInfo = 1'.\n"
1571       << "- Instructions should usually have Sched<[...]> as a superclass, "
1572          "you may temporarily use an empty list.\n\n";
1573     PrintFatalError("Incomplete schedule model");
1574   }
1575 }
1576 
1577 // Collect itinerary class resources for each processor.
1578 void CodeGenSchedModels::collectItinProcResources(Record *ItinClassDef) {
1579   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
1580     const CodeGenProcModel &PM = ProcModels[PIdx];
1581     // For all ItinRW entries.
1582     bool HasMatch = false;
1583     for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
1584          II != IE; ++II) {
1585       RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
1586       if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
1587         continue;
1588       if (HasMatch)
1589         PrintFatalError((*II)->getLoc(), "Duplicate itinerary class "
1590                         + ItinClassDef->getName()
1591                         + " in ItinResources for " + PM.ModelName);
1592       HasMatch = true;
1593       IdxVec Writes, Reads;
1594       findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1595       IdxVec ProcIndices(1, PIdx);
1596       collectRWResources(Writes, Reads, ProcIndices);
1597     }
1598   }
1599 }
1600 
1601 void CodeGenSchedModels::collectRWResources(unsigned RWIdx, bool IsRead,
1602                                             ArrayRef<unsigned> ProcIndices) {
1603   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
1604   if (SchedRW.TheDef) {
1605     if (!IsRead && SchedRW.TheDef->isSubClassOf("SchedWriteRes")) {
1606       for (unsigned Idx : ProcIndices)
1607         addWriteRes(SchedRW.TheDef, Idx);
1608     }
1609     else if (IsRead && SchedRW.TheDef->isSubClassOf("SchedReadAdvance")) {
1610       for (unsigned Idx : ProcIndices)
1611         addReadAdvance(SchedRW.TheDef, Idx);
1612     }
1613   }
1614   for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
1615        AI != AE; ++AI) {
1616     IdxVec AliasProcIndices;
1617     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
1618       AliasProcIndices.push_back(
1619         getProcModel((*AI)->getValueAsDef("SchedModel")).Index);
1620     }
1621     else
1622       AliasProcIndices = ProcIndices;
1623     const CodeGenSchedRW &AliasRW = getSchedRW((*AI)->getValueAsDef("AliasRW"));
1624     assert(AliasRW.IsRead == IsRead && "cannot alias reads to writes");
1625 
1626     IdxVec ExpandedRWs;
1627     expandRWSequence(AliasRW.Index, ExpandedRWs, IsRead);
1628     for (IdxIter SI = ExpandedRWs.begin(), SE = ExpandedRWs.end();
1629          SI != SE; ++SI) {
1630       collectRWResources(*SI, IsRead, AliasProcIndices);
1631     }
1632   }
1633 }
1634 
1635 // Collect resources for a set of read/write types and processor indices.
1636 void CodeGenSchedModels::collectRWResources(ArrayRef<unsigned> Writes,
1637                                             ArrayRef<unsigned> Reads,
1638                                             ArrayRef<unsigned> ProcIndices) {
1639 
1640   for (unsigned Idx : Writes)
1641     collectRWResources(Idx, /*IsRead=*/false, ProcIndices);
1642 
1643   for (unsigned Idx : Reads)
1644     collectRWResources(Idx, /*IsRead=*/true, ProcIndices);
1645 }
1646 
1647 
1648 // Find the processor's resource units for this kind of resource.
1649 Record *CodeGenSchedModels::findProcResUnits(Record *ProcResKind,
1650                                              const CodeGenProcModel &PM) const {
1651   if (ProcResKind->isSubClassOf("ProcResourceUnits"))
1652     return ProcResKind;
1653 
1654   Record *ProcUnitDef = nullptr;
1655   RecVec ProcResourceDefs =
1656     Records.getAllDerivedDefinitions("ProcResourceUnits");
1657 
1658   for (RecIter RI = ProcResourceDefs.begin(), RE = ProcResourceDefs.end();
1659        RI != RE; ++RI) {
1660 
1661     if ((*RI)->getValueAsDef("Kind") == ProcResKind
1662         && (*RI)->getValueAsDef("SchedModel") == PM.ModelDef) {
1663       if (ProcUnitDef) {
1664         PrintFatalError((*RI)->getLoc(),
1665                         "Multiple ProcessorResourceUnits associated with "
1666                         + ProcResKind->getName());
1667       }
1668       ProcUnitDef = *RI;
1669     }
1670   }
1671   RecVec ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
1672   for (RecIter RI = ProcResGroups.begin(), RE = ProcResGroups.end();
1673        RI != RE; ++RI) {
1674 
1675     if (*RI == ProcResKind
1676         && (*RI)->getValueAsDef("SchedModel") == PM.ModelDef) {
1677       if (ProcUnitDef) {
1678         PrintFatalError((*RI)->getLoc(),
1679                         "Multiple ProcessorResourceUnits associated with "
1680                         + ProcResKind->getName());
1681       }
1682       ProcUnitDef = *RI;
1683     }
1684   }
1685   if (!ProcUnitDef) {
1686     PrintFatalError(ProcResKind->getLoc(),
1687                     "No ProcessorResources associated with "
1688                     + ProcResKind->getName());
1689   }
1690   return ProcUnitDef;
1691 }
1692 
1693 // Iteratively add a resource and its super resources.
1694 void CodeGenSchedModels::addProcResource(Record *ProcResKind,
1695                                          CodeGenProcModel &PM) {
1696   for (;;) {
1697     Record *ProcResUnits = findProcResUnits(ProcResKind, PM);
1698 
1699     // See if this ProcResource is already associated with this processor.
1700     RecIter I = std::find(PM.ProcResourceDefs.begin(),
1701                           PM.ProcResourceDefs.end(), ProcResUnits);
1702     if (I != PM.ProcResourceDefs.end())
1703       return;
1704 
1705     PM.ProcResourceDefs.push_back(ProcResUnits);
1706     if (ProcResUnits->isSubClassOf("ProcResGroup"))
1707       return;
1708 
1709     if (!ProcResUnits->getValueInit("Super")->isComplete())
1710       return;
1711 
1712     ProcResKind = ProcResUnits->getValueAsDef("Super");
1713   }
1714 }
1715 
1716 // Add resources for a SchedWrite to this processor if they don't exist.
1717 void CodeGenSchedModels::addWriteRes(Record *ProcWriteResDef, unsigned PIdx) {
1718   assert(PIdx && "don't add resources to an invalid Processor model");
1719 
1720   RecVec &WRDefs = ProcModels[PIdx].WriteResDefs;
1721   RecIter WRI = std::find(WRDefs.begin(), WRDefs.end(), ProcWriteResDef);
1722   if (WRI != WRDefs.end())
1723     return;
1724   WRDefs.push_back(ProcWriteResDef);
1725 
1726   // Visit ProcResourceKinds referenced by the newly discovered WriteRes.
1727   RecVec ProcResDefs = ProcWriteResDef->getValueAsListOfDefs("ProcResources");
1728   for (RecIter WritePRI = ProcResDefs.begin(), WritePRE = ProcResDefs.end();
1729        WritePRI != WritePRE; ++WritePRI) {
1730     addProcResource(*WritePRI, ProcModels[PIdx]);
1731   }
1732 }
1733 
1734 // Add resources for a ReadAdvance to this processor if they don't exist.
1735 void CodeGenSchedModels::addReadAdvance(Record *ProcReadAdvanceDef,
1736                                         unsigned PIdx) {
1737   RecVec &RADefs = ProcModels[PIdx].ReadAdvanceDefs;
1738   RecIter I = std::find(RADefs.begin(), RADefs.end(), ProcReadAdvanceDef);
1739   if (I != RADefs.end())
1740     return;
1741   RADefs.push_back(ProcReadAdvanceDef);
1742 }
1743 
1744 unsigned CodeGenProcModel::getProcResourceIdx(Record *PRDef) const {
1745   RecIter PRPos = std::find(ProcResourceDefs.begin(), ProcResourceDefs.end(),
1746                             PRDef);
1747   if (PRPos == ProcResourceDefs.end())
1748     PrintFatalError(PRDef->getLoc(), "ProcResource def is not included in "
1749                     "the ProcResources list for " + ModelName);
1750   // Idx=0 is reserved for invalid.
1751   return 1 + (PRPos - ProcResourceDefs.begin());
1752 }
1753 
1754 #ifndef NDEBUG
1755 void CodeGenProcModel::dump() const {
1756   dbgs() << Index << ": " << ModelName << " "
1757          << (ModelDef ? ModelDef->getName() : "inferred") << " "
1758          << (ItinsDef ? ItinsDef->getName() : "no itinerary") << '\n';
1759 }
1760 
1761 void CodeGenSchedRW::dump() const {
1762   dbgs() << Name << (IsVariadic ? " (V) " : " ");
1763   if (IsSequence) {
1764     dbgs() << "(";
1765     dumpIdxVec(Sequence);
1766     dbgs() << ")";
1767   }
1768 }
1769 
1770 void CodeGenSchedClass::dump(const CodeGenSchedModels* SchedModels) const {
1771   dbgs() << "SCHEDCLASS " << Index << ":" << Name << '\n'
1772          << "  Writes: ";
1773   for (unsigned i = 0, N = Writes.size(); i < N; ++i) {
1774     SchedModels->getSchedWrite(Writes[i]).dump();
1775     if (i < N-1) {
1776       dbgs() << '\n';
1777       dbgs().indent(10);
1778     }
1779   }
1780   dbgs() << "\n  Reads: ";
1781   for (unsigned i = 0, N = Reads.size(); i < N; ++i) {
1782     SchedModels->getSchedRead(Reads[i]).dump();
1783     if (i < N-1) {
1784       dbgs() << '\n';
1785       dbgs().indent(10);
1786     }
1787   }
1788   dbgs() << "\n  ProcIdx: "; dumpIdxVec(ProcIndices); dbgs() << '\n';
1789   if (!Transitions.empty()) {
1790     dbgs() << "\n Transitions for Proc ";
1791     for (std::vector<CodeGenSchedTransition>::const_iterator
1792            TI = Transitions.begin(), TE = Transitions.end(); TI != TE; ++TI) {
1793       dumpIdxVec(TI->ProcIndices);
1794     }
1795   }
1796 }
1797 
1798 void PredTransitions::dump() const {
1799   dbgs() << "Expanded Variants:\n";
1800   for (std::vector<PredTransition>::const_iterator
1801          TI = TransVec.begin(), TE = TransVec.end(); TI != TE; ++TI) {
1802     dbgs() << "{";
1803     for (SmallVectorImpl<PredCheck>::const_iterator
1804            PCI = TI->PredTerm.begin(), PCE = TI->PredTerm.end();
1805          PCI != PCE; ++PCI) {
1806       if (PCI != TI->PredTerm.begin())
1807         dbgs() << ", ";
1808       dbgs() << SchedModels.getSchedRW(PCI->RWIdx, PCI->IsRead).Name
1809              << ":" << PCI->Predicate->getName();
1810     }
1811     dbgs() << "},\n  => {";
1812     for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
1813            WSI = TI->WriteSequences.begin(), WSE = TI->WriteSequences.end();
1814          WSI != WSE; ++WSI) {
1815       dbgs() << "(";
1816       for (SmallVectorImpl<unsigned>::const_iterator
1817              WI = WSI->begin(), WE = WSI->end(); WI != WE; ++WI) {
1818         if (WI != WSI->begin())
1819           dbgs() << ", ";
1820         dbgs() << SchedModels.getSchedWrite(*WI).Name;
1821       }
1822       dbgs() << "),";
1823     }
1824     dbgs() << "}\n";
1825   }
1826 }
1827 #endif // NDEBUG
1828