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