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