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