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   // Find pfm counter definitions for each processor.
244   collectPfmCounters();
245 
246   checkCompleteness();
247 }
248 
249 /// Gather all processor models.
250 void CodeGenSchedModels::collectProcModels() {
251   RecVec ProcRecords = Records.getAllDerivedDefinitions("Processor");
252   llvm::sort(ProcRecords.begin(), ProcRecords.end(), LessRecordFieldName());
253 
254   // Reserve space because we can. Reallocation would be ok.
255   ProcModels.reserve(ProcRecords.size()+1);
256 
257   // Use idx=0 for NoModel/NoItineraries.
258   Record *NoModelDef = Records.getDef("NoSchedModel");
259   Record *NoItinsDef = Records.getDef("NoItineraries");
260   ProcModels.emplace_back(0, "NoSchedModel", NoModelDef, NoItinsDef);
261   ProcModelMap[NoModelDef] = 0;
262 
263   // For each processor, find a unique machine model.
264   DEBUG(dbgs() << "+++ PROCESSOR MODELs (addProcModel) +++\n");
265   for (Record *ProcRecord : ProcRecords)
266     addProcModel(ProcRecord);
267 }
268 
269 /// Get a unique processor model based on the defined MachineModel and
270 /// ProcessorItineraries.
271 void CodeGenSchedModels::addProcModel(Record *ProcDef) {
272   Record *ModelKey = getModelOrItinDef(ProcDef);
273   if (!ProcModelMap.insert(std::make_pair(ModelKey, ProcModels.size())).second)
274     return;
275 
276   std::string Name = ModelKey->getName();
277   if (ModelKey->isSubClassOf("SchedMachineModel")) {
278     Record *ItinsDef = ModelKey->getValueAsDef("Itineraries");
279     ProcModels.emplace_back(ProcModels.size(), Name, ModelKey, ItinsDef);
280   }
281   else {
282     // An itinerary is defined without a machine model. Infer a new model.
283     if (!ModelKey->getValueAsListOfDefs("IID").empty())
284       Name = Name + "Model";
285     ProcModels.emplace_back(ProcModels.size(), Name,
286                             ProcDef->getValueAsDef("SchedModel"), ModelKey);
287   }
288   DEBUG(ProcModels.back().dump());
289 }
290 
291 // Recursively find all reachable SchedReadWrite records.
292 static void scanSchedRW(Record *RWDef, RecVec &RWDefs,
293                         SmallPtrSet<Record*, 16> &RWSet) {
294   if (!RWSet.insert(RWDef).second)
295     return;
296   RWDefs.push_back(RWDef);
297   // Reads don't currently have sequence records, but it can be added later.
298   if (RWDef->isSubClassOf("WriteSequence")) {
299     RecVec Seq = RWDef->getValueAsListOfDefs("Writes");
300     for (Record *WSRec : Seq)
301       scanSchedRW(WSRec, RWDefs, RWSet);
302   }
303   else if (RWDef->isSubClassOf("SchedVariant")) {
304     // Visit each variant (guarded by a different predicate).
305     RecVec Vars = RWDef->getValueAsListOfDefs("Variants");
306     for (Record *Variant : Vars) {
307       // Visit each RW in the sequence selected by the current variant.
308       RecVec Selected = Variant->getValueAsListOfDefs("Selected");
309       for (Record *SelDef : Selected)
310         scanSchedRW(SelDef, RWDefs, RWSet);
311     }
312   }
313 }
314 
315 // Collect and sort all SchedReadWrites reachable via tablegen records.
316 // More may be inferred later when inferring new SchedClasses from variants.
317 void CodeGenSchedModels::collectSchedRW() {
318   // Reserve idx=0 for invalid writes/reads.
319   SchedWrites.resize(1);
320   SchedReads.resize(1);
321 
322   SmallPtrSet<Record*, 16> RWSet;
323 
324   // Find all SchedReadWrites referenced by instruction defs.
325   RecVec SWDefs, SRDefs;
326   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
327     Record *SchedDef = Inst->TheDef;
328     if (SchedDef->isValueUnset("SchedRW"))
329       continue;
330     RecVec RWs = SchedDef->getValueAsListOfDefs("SchedRW");
331     for (Record *RW : RWs) {
332       if (RW->isSubClassOf("SchedWrite"))
333         scanSchedRW(RW, SWDefs, RWSet);
334       else {
335         assert(RW->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
336         scanSchedRW(RW, SRDefs, RWSet);
337       }
338     }
339   }
340   // Find all ReadWrites referenced by InstRW.
341   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
342   for (Record *InstRWDef : InstRWDefs) {
343     // For all OperandReadWrites.
344     RecVec RWDefs = InstRWDef->getValueAsListOfDefs("OperandReadWrites");
345     for (Record *RWDef : RWDefs) {
346       if (RWDef->isSubClassOf("SchedWrite"))
347         scanSchedRW(RWDef, SWDefs, RWSet);
348       else {
349         assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
350         scanSchedRW(RWDef, SRDefs, RWSet);
351       }
352     }
353   }
354   // Find all ReadWrites referenced by ItinRW.
355   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
356   for (Record *ItinRWDef : ItinRWDefs) {
357     // For all OperandReadWrites.
358     RecVec RWDefs = ItinRWDef->getValueAsListOfDefs("OperandReadWrites");
359     for (Record *RWDef : RWDefs) {
360       if (RWDef->isSubClassOf("SchedWrite"))
361         scanSchedRW(RWDef, SWDefs, RWSet);
362       else {
363         assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
364         scanSchedRW(RWDef, SRDefs, RWSet);
365       }
366     }
367   }
368   // Find all ReadWrites referenced by SchedAlias. AliasDefs needs to be sorted
369   // for the loop below that initializes Alias vectors.
370   RecVec AliasDefs = Records.getAllDerivedDefinitions("SchedAlias");
371   llvm::sort(AliasDefs.begin(), AliasDefs.end(), LessRecord());
372   for (Record *ADef : AliasDefs) {
373     Record *MatchDef = ADef->getValueAsDef("MatchRW");
374     Record *AliasDef = ADef->getValueAsDef("AliasRW");
375     if (MatchDef->isSubClassOf("SchedWrite")) {
376       if (!AliasDef->isSubClassOf("SchedWrite"))
377         PrintFatalError(ADef->getLoc(), "SchedWrite Alias must be SchedWrite");
378       scanSchedRW(AliasDef, SWDefs, RWSet);
379     }
380     else {
381       assert(MatchDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
382       if (!AliasDef->isSubClassOf("SchedRead"))
383         PrintFatalError(ADef->getLoc(), "SchedRead Alias must be SchedRead");
384       scanSchedRW(AliasDef, SRDefs, RWSet);
385     }
386   }
387   // Sort and add the SchedReadWrites directly referenced by instructions or
388   // itinerary resources. Index reads and writes in separate domains.
389   llvm::sort(SWDefs.begin(), SWDefs.end(), LessRecord());
390   for (Record *SWDef : SWDefs) {
391     assert(!getSchedRWIdx(SWDef, /*IsRead=*/false) && "duplicate SchedWrite");
392     SchedWrites.emplace_back(SchedWrites.size(), SWDef);
393   }
394   llvm::sort(SRDefs.begin(), SRDefs.end(), LessRecord());
395   for (Record *SRDef : SRDefs) {
396     assert(!getSchedRWIdx(SRDef, /*IsRead-*/true) && "duplicate SchedWrite");
397     SchedReads.emplace_back(SchedReads.size(), SRDef);
398   }
399   // Initialize WriteSequence vectors.
400   for (CodeGenSchedRW &CGRW : SchedWrites) {
401     if (!CGRW.IsSequence)
402       continue;
403     findRWs(CGRW.TheDef->getValueAsListOfDefs("Writes"), CGRW.Sequence,
404             /*IsRead=*/false);
405   }
406   // Initialize Aliases vectors.
407   for (Record *ADef : AliasDefs) {
408     Record *AliasDef = ADef->getValueAsDef("AliasRW");
409     getSchedRW(AliasDef).IsAlias = true;
410     Record *MatchDef = ADef->getValueAsDef("MatchRW");
411     CodeGenSchedRW &RW = getSchedRW(MatchDef);
412     if (RW.IsAlias)
413       PrintFatalError(ADef->getLoc(), "Cannot Alias an Alias");
414     RW.Aliases.push_back(ADef);
415   }
416   DEBUG(
417     dbgs() << "\n+++ SCHED READS and WRITES (collectSchedRW) +++\n";
418     for (unsigned WIdx = 0, WEnd = SchedWrites.size(); WIdx != WEnd; ++WIdx) {
419       dbgs() << WIdx << ": ";
420       SchedWrites[WIdx].dump();
421       dbgs() << '\n';
422     }
423     for (unsigned RIdx = 0, REnd = SchedReads.size(); RIdx != REnd; ++RIdx) {
424       dbgs() << RIdx << ": ";
425       SchedReads[RIdx].dump();
426       dbgs() << '\n';
427     }
428     RecVec RWDefs = Records.getAllDerivedDefinitions("SchedReadWrite");
429     for (Record *RWDef : RWDefs) {
430       if (!getSchedRWIdx(RWDef, RWDef->isSubClassOf("SchedRead"))) {
431         StringRef Name = RWDef->getName();
432         if (Name != "NoWrite" && Name != "ReadDefault")
433           dbgs() << "Unused SchedReadWrite " << Name << '\n';
434       }
435     });
436 }
437 
438 /// Compute a SchedWrite name from a sequence of writes.
439 std::string CodeGenSchedModels::genRWName(ArrayRef<unsigned> Seq, bool IsRead) {
440   std::string Name("(");
441   for (auto I = Seq.begin(), E = Seq.end(); I != E; ++I) {
442     if (I != Seq.begin())
443       Name += '_';
444     Name += getSchedRW(*I, IsRead).Name;
445   }
446   Name += ')';
447   return Name;
448 }
449 
450 unsigned CodeGenSchedModels::getSchedRWIdx(Record *Def, bool IsRead) const {
451   const std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
452   for (std::vector<CodeGenSchedRW>::const_iterator I = RWVec.begin(),
453          E = RWVec.end(); I != E; ++I) {
454     if (I->TheDef == Def)
455       return I - RWVec.begin();
456   }
457   return 0;
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 (RecIter AI = SchedWrite.Aliases.begin(), AE = SchedWrite.Aliases.end();
531        AI != AE; ++AI) {
532     const CodeGenSchedRW &AliasRW = getSchedRW((*AI)->getValueAsDef("AliasRW"));
533     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
534       Record *ModelDef = (*AI)->getValueAsDef("SchedModel");
535       if (&getProcModel(ModelDef) != &ProcModel)
536         continue;
537     }
538     if (AliasDef)
539       PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
540                       "defined for processor " + ProcModel.ModelName +
541                       " Ensure only one SchedAlias exists per RW.");
542     AliasDef = AliasRW.TheDef;
543   }
544   if (AliasDef) {
545     expandRWSeqForProc(getSchedRWIdx(AliasDef, IsRead),
546                        RWSeq, IsRead,ProcModel);
547     return;
548   }
549   if (!SchedWrite.IsSequence) {
550     RWSeq.push_back(RWIdx);
551     return;
552   }
553   int Repeat =
554     SchedWrite.TheDef ? SchedWrite.TheDef->getValueAsInt("Repeat") : 1;
555   for (int i = 0; i < Repeat; ++i) {
556     for (unsigned I : SchedWrite.Sequence) {
557       expandRWSeqForProc(I, RWSeq, IsRead, ProcModel);
558     }
559   }
560 }
561 
562 // Find the existing SchedWrite that models this sequence of writes.
563 unsigned CodeGenSchedModels::findRWForSequence(ArrayRef<unsigned> Seq,
564                                                bool IsRead) {
565   std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
566 
567   for (std::vector<CodeGenSchedRW>::iterator I = RWVec.begin(), E = RWVec.end();
568        I != E; ++I) {
569     if (makeArrayRef(I->Sequence) == Seq)
570       return I - RWVec.begin();
571   }
572   // Index zero reserved for invalid RW.
573   return 0;
574 }
575 
576 /// Add this ReadWrite if it doesn't already exist.
577 unsigned CodeGenSchedModels::findOrInsertRW(ArrayRef<unsigned> Seq,
578                                             bool IsRead) {
579   assert(!Seq.empty() && "cannot insert empty sequence");
580   if (Seq.size() == 1)
581     return Seq.back();
582 
583   unsigned Idx = findRWForSequence(Seq, IsRead);
584   if (Idx)
585     return Idx;
586 
587   unsigned RWIdx = IsRead ? SchedReads.size() : SchedWrites.size();
588   CodeGenSchedRW SchedRW(RWIdx, IsRead, Seq, genRWName(Seq, IsRead));
589   if (IsRead)
590     SchedReads.push_back(SchedRW);
591   else
592     SchedWrites.push_back(SchedRW);
593   return RWIdx;
594 }
595 
596 /// Visit all the instruction definitions for this target to gather and
597 /// enumerate the itinerary classes. These are the explicitly specified
598 /// SchedClasses. More SchedClasses may be inferred.
599 void CodeGenSchedModels::collectSchedClasses() {
600 
601   // NoItinerary is always the first class at Idx=0
602   assert(SchedClasses.empty() && "Expected empty sched class");
603   SchedClasses.emplace_back(0, "NoInstrModel",
604                             Records.getDef("NoItinerary"));
605   SchedClasses.back().ProcIndices.push_back(0);
606 
607   // Create a SchedClass for each unique combination of itinerary class and
608   // SchedRW list.
609   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
610     Record *ItinDef = Inst->TheDef->getValueAsDef("Itinerary");
611     IdxVec Writes, Reads;
612     if (!Inst->TheDef->isValueUnset("SchedRW"))
613       findRWs(Inst->TheDef->getValueAsListOfDefs("SchedRW"), Writes, Reads);
614 
615     // ProcIdx == 0 indicates the class applies to all processors.
616     unsigned SCIdx = addSchedClass(ItinDef, Writes, Reads, /*ProcIndices*/{0});
617     InstrClassMap[Inst->TheDef] = SCIdx;
618   }
619   // Create classes for InstRW defs.
620   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
621   llvm::sort(InstRWDefs.begin(), InstRWDefs.end(), LessRecord());
622   DEBUG(dbgs() << "\n+++ SCHED CLASSES (createInstRWClass) +++\n");
623   for (Record *RWDef : InstRWDefs)
624     createInstRWClass(RWDef);
625 
626   NumInstrSchedClasses = SchedClasses.size();
627 
628   bool EnableDump = false;
629   DEBUG(EnableDump = true);
630   if (!EnableDump)
631     return;
632 
633   dbgs() << "\n+++ ITINERARIES and/or MACHINE MODELS (collectSchedClasses) +++\n";
634   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
635     StringRef InstName = Inst->TheDef->getName();
636     unsigned SCIdx = getSchedClassIdx(*Inst);
637     if (!SCIdx) {
638       if (!Inst->hasNoSchedulingInfo)
639         dbgs() << "No machine model for " << Inst->TheDef->getName() << '\n';
640       continue;
641     }
642     CodeGenSchedClass &SC = getSchedClass(SCIdx);
643     if (SC.ProcIndices[0] != 0)
644       PrintFatalError(Inst->TheDef->getLoc(), "Instruction's sched class "
645                       "must not be subtarget specific.");
646 
647     IdxVec ProcIndices;
648     if (SC.ItinClassDef->getName() != "NoItinerary") {
649       ProcIndices.push_back(0);
650       dbgs() << "Itinerary for " << InstName << ": "
651              << SC.ItinClassDef->getName() << '\n';
652     }
653     if (!SC.Writes.empty()) {
654       ProcIndices.push_back(0);
655       dbgs() << "SchedRW machine model for " << InstName;
656       for (IdxIter WI = SC.Writes.begin(), WE = SC.Writes.end(); WI != WE; ++WI)
657         dbgs() << " " << SchedWrites[*WI].Name;
658       for (IdxIter RI = SC.Reads.begin(), RE = SC.Reads.end(); RI != RE; ++RI)
659         dbgs() << " " << SchedReads[*RI].Name;
660       dbgs() << '\n';
661     }
662     const RecVec &RWDefs = SchedClasses[SCIdx].InstRWs;
663     for (Record *RWDef : RWDefs) {
664       const CodeGenProcModel &ProcModel =
665         getProcModel(RWDef->getValueAsDef("SchedModel"));
666       ProcIndices.push_back(ProcModel.Index);
667       dbgs() << "InstRW on " << ProcModel.ModelName << " for " << InstName;
668       IdxVec Writes;
669       IdxVec Reads;
670       findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
671               Writes, Reads);
672       for (unsigned WIdx : Writes)
673         dbgs() << " " << SchedWrites[WIdx].Name;
674       for (unsigned RIdx : Reads)
675         dbgs() << " " << SchedReads[RIdx].Name;
676       dbgs() << '\n';
677     }
678     // If ProcIndices contains zero, the class applies to all processors.
679     if (!std::count(ProcIndices.begin(), ProcIndices.end(), 0)) {
680       for (const CodeGenProcModel &PM : ProcModels) {
681         if (!std::count(ProcIndices.begin(), ProcIndices.end(), PM.Index))
682           dbgs() << "No machine model for " << Inst->TheDef->getName()
683                  << " on processor " << PM.ModelName << '\n';
684       }
685     }
686   }
687 }
688 
689 /// Find an SchedClass that has been inferred from a per-operand list of
690 /// SchedWrites and SchedReads.
691 unsigned CodeGenSchedModels::findSchedClassIdx(Record *ItinClassDef,
692                                                ArrayRef<unsigned> Writes,
693                                                ArrayRef<unsigned> Reads) const {
694   for (SchedClassIter I = schedClassBegin(), E = schedClassEnd(); I != E; ++I)
695     if (I->isKeyEqual(ItinClassDef, Writes, Reads))
696       return I - schedClassBegin();
697   return 0;
698 }
699 
700 // Get the SchedClass index for an instruction.
701 unsigned CodeGenSchedModels::getSchedClassIdx(
702   const CodeGenInstruction &Inst) const {
703 
704   return InstrClassMap.lookup(Inst.TheDef);
705 }
706 
707 std::string
708 CodeGenSchedModels::createSchedClassName(Record *ItinClassDef,
709                                          ArrayRef<unsigned> OperWrites,
710                                          ArrayRef<unsigned> OperReads) {
711 
712   std::string Name;
713   if (ItinClassDef && ItinClassDef->getName() != "NoItinerary")
714     Name = ItinClassDef->getName();
715   for (unsigned Idx : OperWrites) {
716     if (!Name.empty())
717       Name += '_';
718     Name += SchedWrites[Idx].Name;
719   }
720   for (unsigned Idx : OperReads) {
721     Name += '_';
722     Name += SchedReads[Idx].Name;
723   }
724   return Name;
725 }
726 
727 std::string CodeGenSchedModels::createSchedClassName(const RecVec &InstDefs) {
728 
729   std::string Name;
730   for (RecIter I = InstDefs.begin(), E = InstDefs.end(); I != E; ++I) {
731     if (I != InstDefs.begin())
732       Name += '_';
733     Name += (*I)->getName();
734   }
735   return Name;
736 }
737 
738 /// Add an inferred sched class from an itinerary class and per-operand list of
739 /// SchedWrites and SchedReads. ProcIndices contains the set of IDs of
740 /// processors that may utilize this class.
741 unsigned CodeGenSchedModels::addSchedClass(Record *ItinClassDef,
742                                            ArrayRef<unsigned> OperWrites,
743                                            ArrayRef<unsigned> OperReads,
744                                            ArrayRef<unsigned> ProcIndices) {
745   assert(!ProcIndices.empty() && "expect at least one ProcIdx");
746 
747   unsigned Idx = findSchedClassIdx(ItinClassDef, OperWrites, OperReads);
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           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     DEBUG(dbgs() << "InstRW: New SC " << SCIdx << ":" << SC.Name << " on "
833           << InstRWDef->getValueAsDef("SchedModel")->getName() << "\n");
834 
835     // Preserve ItinDef and Writes/Reads for processors without an InstRW entry.
836     SC.ItinClassDef = SchedClasses[OldSCIdx].ItinClassDef;
837     SC.Writes = SchedClasses[OldSCIdx].Writes;
838     SC.Reads = SchedClasses[OldSCIdx].Reads;
839     SC.ProcIndices.push_back(0);
840     // If we had an old class, copy it's InstRWs to this new class.
841     if (OldSCIdx) {
842       Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
843       for (Record *OldRWDef : SchedClasses[OldSCIdx].InstRWs) {
844         if (OldRWDef->getValueAsDef("SchedModel") == RWModelDef) {
845           for (Record *InstDef : InstDefs) {
846             PrintFatalError(OldRWDef->getLoc(), "Overlapping InstRW def " +
847                        InstDef->getName() + " also matches " +
848                        OldRWDef->getValue("Instrs")->getValue()->getAsString());
849           }
850         }
851         assert(OldRWDef != InstRWDef &&
852                "SchedClass has duplicate InstRW def");
853         SC.InstRWs.push_back(OldRWDef);
854       }
855     }
856     // Map each Instr to this new class.
857     for (Record *InstDef : InstDefs)
858       InstrClassMap[InstDef] = SCIdx;
859     SC.InstRWs.push_back(InstRWDef);
860   }
861 }
862 
863 // True if collectProcItins found anything.
864 bool CodeGenSchedModels::hasItineraries() const {
865   for (const CodeGenProcModel &PM : make_range(procModelBegin(),procModelEnd())) {
866     if (PM.hasItineraries())
867       return true;
868   }
869   return false;
870 }
871 
872 // Gather the processor itineraries.
873 void CodeGenSchedModels::collectProcItins() {
874   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       Record *ItinDef = ItinData->getValueAsDef("TheClass");
889       bool FoundClass = false;
890       for (SchedClassIter SCI = schedClassBegin(), SCE = schedClassEnd();
891            SCI != SCE; ++SCI) {
892         // Multiple SchedClasses may share an itinerary. Update all of them.
893         if (SCI->ItinClassDef == ItinDef) {
894           ProcModel.ItinDefList[SCI->Index] = ItinData;
895           FoundClass = true;
896         }
897       }
898       if (!FoundClass) {
899         DEBUG(dbgs() << ProcModel.ItinsDef->getName()
900               << " missing class for itinerary " << ItinDef->getName() << '\n');
901       }
902     }
903     // Check for missing itinerary entries.
904     assert(!ProcModel.ItinDefList[0] && "NoItinerary class can't have rec");
905     DEBUG(
906       for (unsigned i = 1, N = ProcModel.ItinDefList.size(); i < N; ++i) {
907         if (!ProcModel.ItinDefList[i])
908           dbgs() << ProcModel.ItinsDef->getName()
909                  << " missing itinerary for class "
910                  << SchedClasses[i].Name << '\n';
911       });
912   }
913 }
914 
915 // Gather the read/write types for each itinerary class.
916 void CodeGenSchedModels::collectProcItinRW() {
917   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
918   llvm::sort(ItinRWDefs.begin(), ItinRWDefs.end(), LessRecord());
919   for (Record *RWDef  : ItinRWDefs) {
920     if (!RWDef->getValueInit("SchedModel")->isComplete())
921       PrintFatalError(RWDef->getLoc(), "SchedModel is undefined");
922     Record *ModelDef = RWDef->getValueAsDef("SchedModel");
923     ProcModelMapTy::const_iterator I = ProcModelMap.find(ModelDef);
924     if (I == ProcModelMap.end()) {
925       PrintFatalError(RWDef->getLoc(), "Undefined SchedMachineModel "
926                     + ModelDef->getName());
927     }
928     ProcModels[I->second].ItinRWDefs.push_back(RWDef);
929   }
930 }
931 
932 // Gather the unsupported features for processor models.
933 void CodeGenSchedModels::collectProcUnsupportedFeatures() {
934   for (CodeGenProcModel &ProcModel : ProcModels) {
935     for (Record *Pred : ProcModel.ModelDef->getValueAsListOfDefs("UnsupportedFeatures")) {
936        ProcModel.UnsupportedFeaturesDefs.push_back(Pred);
937     }
938   }
939 }
940 
941 /// Infer new classes from existing classes. In the process, this may create new
942 /// SchedWrites from sequences of existing SchedWrites.
943 void CodeGenSchedModels::inferSchedClasses() {
944   DEBUG(dbgs() << "\n+++ INFERRING SCHED CLASSES (inferSchedClasses) +++\n");
945   DEBUG(dbgs() << NumInstrSchedClasses << " instr sched classes.\n");
946 
947   // Visit all existing classes and newly created classes.
948   for (unsigned Idx = 0; Idx != SchedClasses.size(); ++Idx) {
949     assert(SchedClasses[Idx].Index == Idx && "bad SCIdx");
950 
951     if (SchedClasses[Idx].ItinClassDef)
952       inferFromItinClass(SchedClasses[Idx].ItinClassDef, Idx);
953     if (!SchedClasses[Idx].InstRWs.empty())
954       inferFromInstRWs(Idx);
955     if (!SchedClasses[Idx].Writes.empty()) {
956       inferFromRW(SchedClasses[Idx].Writes, SchedClasses[Idx].Reads,
957                   Idx, SchedClasses[Idx].ProcIndices);
958     }
959     assert(SchedClasses.size() < (NumInstrSchedClasses*6) &&
960            "too many SchedVariants");
961   }
962 }
963 
964 /// Infer classes from per-processor itinerary resources.
965 void CodeGenSchedModels::inferFromItinClass(Record *ItinClassDef,
966                                             unsigned FromClassIdx) {
967   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
968     const CodeGenProcModel &PM = ProcModels[PIdx];
969     // For all ItinRW entries.
970     bool HasMatch = false;
971     for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
972          II != IE; ++II) {
973       RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
974       if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
975         continue;
976       if (HasMatch)
977         PrintFatalError((*II)->getLoc(), "Duplicate itinerary class "
978                       + ItinClassDef->getName()
979                       + " in ItinResources for " + PM.ModelName);
980       HasMatch = true;
981       IdxVec Writes, Reads;
982       findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
983       inferFromRW(Writes, Reads, FromClassIdx, PIdx);
984     }
985   }
986 }
987 
988 /// Infer classes from per-processor InstReadWrite definitions.
989 void CodeGenSchedModels::inferFromInstRWs(unsigned SCIdx) {
990   for (unsigned I = 0, E = SchedClasses[SCIdx].InstRWs.size(); I != E; ++I) {
991     assert(SchedClasses[SCIdx].InstRWs.size() == E && "InstrRWs was mutated!");
992     Record *Rec = SchedClasses[SCIdx].InstRWs[I];
993     const RecVec *InstDefs = Sets.expand(Rec);
994     RecIter II = InstDefs->begin(), IE = InstDefs->end();
995     for (; II != IE; ++II) {
996       if (InstrClassMap[*II] == SCIdx)
997         break;
998     }
999     // If this class no longer has any instructions mapped to it, it has become
1000     // irrelevant.
1001     if (II == IE)
1002       continue;
1003     IdxVec Writes, Reads;
1004     findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1005     unsigned PIdx = getProcModel(Rec->getValueAsDef("SchedModel")).Index;
1006     inferFromRW(Writes, Reads, SCIdx, PIdx); // May mutate SchedClasses.
1007   }
1008 }
1009 
1010 namespace {
1011 
1012 // Helper for substituteVariantOperand.
1013 struct TransVariant {
1014   Record *VarOrSeqDef;  // Variant or sequence.
1015   unsigned RWIdx;       // Index of this variant or sequence's matched type.
1016   unsigned ProcIdx;     // Processor model index or zero for any.
1017   unsigned TransVecIdx; // Index into PredTransitions::TransVec.
1018 
1019   TransVariant(Record *def, unsigned rwi, unsigned pi, unsigned ti):
1020     VarOrSeqDef(def), RWIdx(rwi), ProcIdx(pi), TransVecIdx(ti) {}
1021 };
1022 
1023 // Associate a predicate with the SchedReadWrite that it guards.
1024 // RWIdx is the index of the read/write variant.
1025 struct PredCheck {
1026   bool IsRead;
1027   unsigned RWIdx;
1028   Record *Predicate;
1029 
1030   PredCheck(bool r, unsigned w, Record *p): IsRead(r), RWIdx(w), Predicate(p) {}
1031 };
1032 
1033 // A Predicate transition is a list of RW sequences guarded by a PredTerm.
1034 struct PredTransition {
1035   // A predicate term is a conjunction of PredChecks.
1036   SmallVector<PredCheck, 4> PredTerm;
1037   SmallVector<SmallVector<unsigned,4>, 16> WriteSequences;
1038   SmallVector<SmallVector<unsigned,4>, 16> ReadSequences;
1039   SmallVector<unsigned, 4> ProcIndices;
1040 };
1041 
1042 // Encapsulate a set of partially constructed transitions.
1043 // The results are built by repeated calls to substituteVariants.
1044 class PredTransitions {
1045   CodeGenSchedModels &SchedModels;
1046 
1047 public:
1048   std::vector<PredTransition> TransVec;
1049 
1050   PredTransitions(CodeGenSchedModels &sm): SchedModels(sm) {}
1051 
1052   void substituteVariantOperand(const SmallVectorImpl<unsigned> &RWSeq,
1053                                 bool IsRead, unsigned StartIdx);
1054 
1055   void substituteVariants(const PredTransition &Trans);
1056 
1057 #ifndef NDEBUG
1058   void dump() const;
1059 #endif
1060 
1061 private:
1062   bool mutuallyExclusive(Record *PredDef, ArrayRef<PredCheck> Term);
1063   void getIntersectingVariants(
1064     const CodeGenSchedRW &SchedRW, unsigned TransIdx,
1065     std::vector<TransVariant> &IntersectingVariants);
1066   void pushVariant(const TransVariant &VInfo, bool IsRead);
1067 };
1068 
1069 } // end anonymous namespace
1070 
1071 // Return true if this predicate is mutually exclusive with a PredTerm. This
1072 // degenerates into checking if the predicate is mutually exclusive with any
1073 // predicate in the Term's conjunction.
1074 //
1075 // All predicates associated with a given SchedRW are considered mutually
1076 // exclusive. This should work even if the conditions expressed by the
1077 // predicates are not exclusive because the predicates for a given SchedWrite
1078 // are always checked in the order they are defined in the .td file. Later
1079 // conditions implicitly negate any prior condition.
1080 bool PredTransitions::mutuallyExclusive(Record *PredDef,
1081                                         ArrayRef<PredCheck> Term) {
1082   for (const PredCheck &PC: Term) {
1083     if (PC.Predicate == PredDef)
1084       return false;
1085 
1086     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(PC.RWIdx, PC.IsRead);
1087     assert(SchedRW.HasVariants && "PredCheck must refer to a SchedVariant");
1088     RecVec Variants = SchedRW.TheDef->getValueAsListOfDefs("Variants");
1089     for (RecIter VI = Variants.begin(), VE = Variants.end(); VI != VE; ++VI) {
1090       if ((*VI)->getValueAsDef("Predicate") == PredDef)
1091         return true;
1092     }
1093   }
1094   return false;
1095 }
1096 
1097 static bool hasAliasedVariants(const CodeGenSchedRW &RW,
1098                                CodeGenSchedModels &SchedModels) {
1099   if (RW.HasVariants)
1100     return true;
1101 
1102   for (Record *Alias : RW.Aliases) {
1103     const CodeGenSchedRW &AliasRW =
1104       SchedModels.getSchedRW(Alias->getValueAsDef("AliasRW"));
1105     if (AliasRW.HasVariants)
1106       return true;
1107     if (AliasRW.IsSequence) {
1108       IdxVec ExpandedRWs;
1109       SchedModels.expandRWSequence(AliasRW.Index, ExpandedRWs, AliasRW.IsRead);
1110       for (IdxIter SI = ExpandedRWs.begin(), SE = ExpandedRWs.end();
1111            SI != SE; ++SI) {
1112         if (hasAliasedVariants(SchedModels.getSchedRW(*SI, AliasRW.IsRead),
1113                                SchedModels)) {
1114           return true;
1115         }
1116       }
1117     }
1118   }
1119   return false;
1120 }
1121 
1122 static bool hasVariant(ArrayRef<PredTransition> Transitions,
1123                        CodeGenSchedModels &SchedModels) {
1124   for (ArrayRef<PredTransition>::iterator
1125          PTI = Transitions.begin(), PTE = Transitions.end();
1126        PTI != PTE; ++PTI) {
1127     for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
1128            WSI = PTI->WriteSequences.begin(), WSE = PTI->WriteSequences.end();
1129          WSI != WSE; ++WSI) {
1130       for (SmallVectorImpl<unsigned>::const_iterator
1131              WI = WSI->begin(), WE = WSI->end(); WI != WE; ++WI) {
1132         if (hasAliasedVariants(SchedModels.getSchedWrite(*WI), SchedModels))
1133           return true;
1134       }
1135     }
1136     for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
1137            RSI = PTI->ReadSequences.begin(), RSE = PTI->ReadSequences.end();
1138          RSI != RSE; ++RSI) {
1139       for (SmallVectorImpl<unsigned>::const_iterator
1140              RI = RSI->begin(), RE = RSI->end(); RI != RE; ++RI) {
1141         if (hasAliasedVariants(SchedModels.getSchedRead(*RI), SchedModels))
1142           return true;
1143       }
1144     }
1145   }
1146   return false;
1147 }
1148 
1149 // Populate IntersectingVariants with any variants or aliased sequences of the
1150 // given SchedRW whose processor indices and predicates are not mutually
1151 // exclusive with the given transition.
1152 void PredTransitions::getIntersectingVariants(
1153   const CodeGenSchedRW &SchedRW, unsigned TransIdx,
1154   std::vector<TransVariant> &IntersectingVariants) {
1155 
1156   bool GenericRW = false;
1157 
1158   std::vector<TransVariant> Variants;
1159   if (SchedRW.HasVariants) {
1160     unsigned VarProcIdx = 0;
1161     if (SchedRW.TheDef->getValueInit("SchedModel")->isComplete()) {
1162       Record *ModelDef = SchedRW.TheDef->getValueAsDef("SchedModel");
1163       VarProcIdx = SchedModels.getProcModel(ModelDef).Index;
1164     }
1165     // Push each variant. Assign TransVecIdx later.
1166     const RecVec VarDefs = SchedRW.TheDef->getValueAsListOfDefs("Variants");
1167     for (Record *VarDef : VarDefs)
1168       Variants.push_back(TransVariant(VarDef, SchedRW.Index, VarProcIdx, 0));
1169     if (VarProcIdx == 0)
1170       GenericRW = true;
1171   }
1172   for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
1173        AI != AE; ++AI) {
1174     // If either the SchedAlias itself or the SchedReadWrite that it aliases
1175     // to is defined within a processor model, constrain all variants to
1176     // that processor.
1177     unsigned AliasProcIdx = 0;
1178     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
1179       Record *ModelDef = (*AI)->getValueAsDef("SchedModel");
1180       AliasProcIdx = SchedModels.getProcModel(ModelDef).Index;
1181     }
1182     const CodeGenSchedRW &AliasRW =
1183       SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
1184 
1185     if (AliasRW.HasVariants) {
1186       const RecVec VarDefs = AliasRW.TheDef->getValueAsListOfDefs("Variants");
1187       for (Record *VD : VarDefs)
1188         Variants.push_back(TransVariant(VD, AliasRW.Index, AliasProcIdx, 0));
1189     }
1190     if (AliasRW.IsSequence) {
1191       Variants.push_back(
1192         TransVariant(AliasRW.TheDef, SchedRW.Index, AliasProcIdx, 0));
1193     }
1194     if (AliasProcIdx == 0)
1195       GenericRW = true;
1196   }
1197   for (TransVariant &Variant : Variants) {
1198     // Don't expand variants if the processor models don't intersect.
1199     // A zero processor index means any processor.
1200     SmallVectorImpl<unsigned> &ProcIndices = TransVec[TransIdx].ProcIndices;
1201     if (ProcIndices[0] && Variant.ProcIdx) {
1202       unsigned Cnt = std::count(ProcIndices.begin(), ProcIndices.end(),
1203                                 Variant.ProcIdx);
1204       if (!Cnt)
1205         continue;
1206       if (Cnt > 1) {
1207         const CodeGenProcModel &PM =
1208           *(SchedModels.procModelBegin() + Variant.ProcIdx);
1209         PrintFatalError(Variant.VarOrSeqDef->getLoc(),
1210                         "Multiple variants defined for processor " +
1211                         PM.ModelName +
1212                         " Ensure only one SchedAlias exists per RW.");
1213       }
1214     }
1215     if (Variant.VarOrSeqDef->isSubClassOf("SchedVar")) {
1216       Record *PredDef = Variant.VarOrSeqDef->getValueAsDef("Predicate");
1217       if (mutuallyExclusive(PredDef, TransVec[TransIdx].PredTerm))
1218         continue;
1219     }
1220     if (IntersectingVariants.empty()) {
1221       // The first variant builds on the existing transition.
1222       Variant.TransVecIdx = TransIdx;
1223       IntersectingVariants.push_back(Variant);
1224     }
1225     else {
1226       // Push another copy of the current transition for more variants.
1227       Variant.TransVecIdx = TransVec.size();
1228       IntersectingVariants.push_back(Variant);
1229       TransVec.push_back(TransVec[TransIdx]);
1230     }
1231   }
1232   if (GenericRW && IntersectingVariants.empty()) {
1233     PrintFatalError(SchedRW.TheDef->getLoc(), "No variant of this type has "
1234                     "a matching predicate on any processor");
1235   }
1236 }
1237 
1238 // Push the Reads/Writes selected by this variant onto the PredTransition
1239 // specified by VInfo.
1240 void PredTransitions::
1241 pushVariant(const TransVariant &VInfo, bool IsRead) {
1242   PredTransition &Trans = TransVec[VInfo.TransVecIdx];
1243 
1244   // If this operand transition is reached through a processor-specific alias,
1245   // then the whole transition is specific to this processor.
1246   if (VInfo.ProcIdx != 0)
1247     Trans.ProcIndices.assign(1, VInfo.ProcIdx);
1248 
1249   IdxVec SelectedRWs;
1250   if (VInfo.VarOrSeqDef->isSubClassOf("SchedVar")) {
1251     Record *PredDef = VInfo.VarOrSeqDef->getValueAsDef("Predicate");
1252     Trans.PredTerm.push_back(PredCheck(IsRead, VInfo.RWIdx,PredDef));
1253     RecVec SelectedDefs = VInfo.VarOrSeqDef->getValueAsListOfDefs("Selected");
1254     SchedModels.findRWs(SelectedDefs, SelectedRWs, IsRead);
1255   }
1256   else {
1257     assert(VInfo.VarOrSeqDef->isSubClassOf("WriteSequence") &&
1258            "variant must be a SchedVariant or aliased WriteSequence");
1259     SelectedRWs.push_back(SchedModels.getSchedRWIdx(VInfo.VarOrSeqDef, IsRead));
1260   }
1261 
1262   const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(VInfo.RWIdx, IsRead);
1263 
1264   SmallVectorImpl<SmallVector<unsigned,4>> &RWSequences = IsRead
1265     ? Trans.ReadSequences : Trans.WriteSequences;
1266   if (SchedRW.IsVariadic) {
1267     unsigned OperIdx = RWSequences.size()-1;
1268     // Make N-1 copies of this transition's last sequence.
1269     for (unsigned i = 1, e = SelectedRWs.size(); i != e; ++i) {
1270       // Create a temporary copy the vector could reallocate.
1271       RWSequences.reserve(RWSequences.size() + 1);
1272       RWSequences.push_back(RWSequences[OperIdx]);
1273     }
1274     // Push each of the N elements of the SelectedRWs onto a copy of the last
1275     // sequence (split the current operand into N operands).
1276     // Note that write sequences should be expanded within this loop--the entire
1277     // sequence belongs to a single operand.
1278     for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
1279          RWI != RWE; ++RWI, ++OperIdx) {
1280       IdxVec ExpandedRWs;
1281       if (IsRead)
1282         ExpandedRWs.push_back(*RWI);
1283       else
1284         SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
1285       RWSequences[OperIdx].insert(RWSequences[OperIdx].end(),
1286                                   ExpandedRWs.begin(), ExpandedRWs.end());
1287     }
1288     assert(OperIdx == RWSequences.size() && "missed a sequence");
1289   }
1290   else {
1291     // Push this transition's expanded sequence onto this transition's last
1292     // sequence (add to the current operand's sequence).
1293     SmallVectorImpl<unsigned> &Seq = RWSequences.back();
1294     IdxVec ExpandedRWs;
1295     for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
1296          RWI != RWE; ++RWI) {
1297       if (IsRead)
1298         ExpandedRWs.push_back(*RWI);
1299       else
1300         SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
1301     }
1302     Seq.insert(Seq.end(), ExpandedRWs.begin(), ExpandedRWs.end());
1303   }
1304 }
1305 
1306 // RWSeq is a sequence of all Reads or all Writes for the next read or write
1307 // operand. StartIdx is an index into TransVec where partial results
1308 // starts. RWSeq must be applied to all transitions between StartIdx and the end
1309 // of TransVec.
1310 void PredTransitions::substituteVariantOperand(
1311   const SmallVectorImpl<unsigned> &RWSeq, bool IsRead, unsigned StartIdx) {
1312 
1313   // Visit each original RW within the current sequence.
1314   for (SmallVectorImpl<unsigned>::const_iterator
1315          RWI = RWSeq.begin(), RWE = RWSeq.end(); RWI != RWE; ++RWI) {
1316     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(*RWI, IsRead);
1317     // Push this RW on all partial PredTransitions or distribute variants.
1318     // New PredTransitions may be pushed within this loop which should not be
1319     // revisited (TransEnd must be loop invariant).
1320     for (unsigned TransIdx = StartIdx, TransEnd = TransVec.size();
1321          TransIdx != TransEnd; ++TransIdx) {
1322       // In the common case, push RW onto the current operand's sequence.
1323       if (!hasAliasedVariants(SchedRW, SchedModels)) {
1324         if (IsRead)
1325           TransVec[TransIdx].ReadSequences.back().push_back(*RWI);
1326         else
1327           TransVec[TransIdx].WriteSequences.back().push_back(*RWI);
1328         continue;
1329       }
1330       // Distribute this partial PredTransition across intersecting variants.
1331       // This will push a copies of TransVec[TransIdx] on the back of TransVec.
1332       std::vector<TransVariant> IntersectingVariants;
1333       getIntersectingVariants(SchedRW, TransIdx, IntersectingVariants);
1334       // Now expand each variant on top of its copy of the transition.
1335       for (std::vector<TransVariant>::const_iterator
1336              IVI = IntersectingVariants.begin(),
1337              IVE = IntersectingVariants.end();
1338            IVI != IVE; ++IVI) {
1339         pushVariant(*IVI, IsRead);
1340       }
1341     }
1342   }
1343 }
1344 
1345 // For each variant of a Read/Write in Trans, substitute the sequence of
1346 // Read/Writes guarded by the variant. This is exponential in the number of
1347 // variant Read/Writes, but in practice detection of mutually exclusive
1348 // predicates should result in linear growth in the total number variants.
1349 //
1350 // This is one step in a breadth-first search of nested variants.
1351 void PredTransitions::substituteVariants(const PredTransition &Trans) {
1352   // Build up a set of partial results starting at the back of
1353   // PredTransitions. Remember the first new transition.
1354   unsigned StartIdx = TransVec.size();
1355   TransVec.emplace_back();
1356   TransVec.back().PredTerm = Trans.PredTerm;
1357   TransVec.back().ProcIndices = Trans.ProcIndices;
1358 
1359   // Visit each original write sequence.
1360   for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
1361          WSI = Trans.WriteSequences.begin(), WSE = Trans.WriteSequences.end();
1362        WSI != WSE; ++WSI) {
1363     // Push a new (empty) write sequence onto all partial Transitions.
1364     for (std::vector<PredTransition>::iterator I =
1365            TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
1366       I->WriteSequences.emplace_back();
1367     }
1368     substituteVariantOperand(*WSI, /*IsRead=*/false, StartIdx);
1369   }
1370   // Visit each original read sequence.
1371   for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
1372          RSI = Trans.ReadSequences.begin(), RSE = Trans.ReadSequences.end();
1373        RSI != RSE; ++RSI) {
1374     // Push a new (empty) read sequence onto all partial Transitions.
1375     for (std::vector<PredTransition>::iterator I =
1376            TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
1377       I->ReadSequences.emplace_back();
1378     }
1379     substituteVariantOperand(*RSI, /*IsRead=*/true, StartIdx);
1380   }
1381 }
1382 
1383 // Create a new SchedClass for each variant found by inferFromRW. Pass
1384 static void inferFromTransitions(ArrayRef<PredTransition> LastTransitions,
1385                                  unsigned FromClassIdx,
1386                                  CodeGenSchedModels &SchedModels) {
1387   // For each PredTransition, create a new CodeGenSchedTransition, which usually
1388   // requires creating a new SchedClass.
1389   for (ArrayRef<PredTransition>::iterator
1390          I = LastTransitions.begin(), E = LastTransitions.end(); I != E; ++I) {
1391     IdxVec OperWritesVariant;
1392     transform(I->WriteSequences, std::back_inserter(OperWritesVariant),
1393               [&SchedModels](ArrayRef<unsigned> WS) {
1394                 return SchedModels.findOrInsertRW(WS, /*IsRead=*/false);
1395               });
1396     IdxVec OperReadsVariant;
1397     transform(I->ReadSequences, std::back_inserter(OperReadsVariant),
1398               [&SchedModels](ArrayRef<unsigned> RS) {
1399                 return SchedModels.findOrInsertRW(RS, /*IsRead=*/true);
1400               });
1401     CodeGenSchedTransition SCTrans;
1402     SCTrans.ToClassIdx =
1403       SchedModels.addSchedClass(/*ItinClassDef=*/nullptr, OperWritesVariant,
1404                                 OperReadsVariant, I->ProcIndices);
1405     SCTrans.ProcIndices.assign(I->ProcIndices.begin(), I->ProcIndices.end());
1406     // The final PredTerm is unique set of predicates guarding the transition.
1407     RecVec Preds;
1408     transform(I->PredTerm, std::back_inserter(Preds),
1409               [](const PredCheck &P) {
1410                 return P.Predicate;
1411               });
1412     Preds.erase(std::unique(Preds.begin(), Preds.end()), Preds.end());
1413     SCTrans.PredTerm = std::move(Preds);
1414     SchedModels.getSchedClass(FromClassIdx)
1415         .Transitions.push_back(std::move(SCTrans));
1416   }
1417 }
1418 
1419 // Create new SchedClasses for the given ReadWrite list. If any of the
1420 // ReadWrites refers to a SchedVariant, create a new SchedClass for each variant
1421 // of the ReadWrite list, following Aliases if necessary.
1422 void CodeGenSchedModels::inferFromRW(ArrayRef<unsigned> OperWrites,
1423                                      ArrayRef<unsigned> OperReads,
1424                                      unsigned FromClassIdx,
1425                                      ArrayRef<unsigned> ProcIndices) {
1426   DEBUG(dbgs() << "INFER RW proc("; dumpIdxVec(ProcIndices); dbgs() << ") ");
1427 
1428   // Create a seed transition with an empty PredTerm and the expanded sequences
1429   // of SchedWrites for the current SchedClass.
1430   std::vector<PredTransition> LastTransitions;
1431   LastTransitions.emplace_back();
1432   LastTransitions.back().ProcIndices.append(ProcIndices.begin(),
1433                                             ProcIndices.end());
1434 
1435   for (unsigned WriteIdx : OperWrites) {
1436     IdxVec WriteSeq;
1437     expandRWSequence(WriteIdx, WriteSeq, /*IsRead=*/false);
1438     LastTransitions[0].WriteSequences.emplace_back();
1439     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].WriteSequences.back();
1440     Seq.append(WriteSeq.begin(), WriteSeq.end());
1441     DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
1442   }
1443   DEBUG(dbgs() << " Reads: ");
1444   for (unsigned ReadIdx : OperReads) {
1445     IdxVec ReadSeq;
1446     expandRWSequence(ReadIdx, ReadSeq, /*IsRead=*/true);
1447     LastTransitions[0].ReadSequences.emplace_back();
1448     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].ReadSequences.back();
1449     Seq.append(ReadSeq.begin(), ReadSeq.end());
1450     DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
1451   }
1452   DEBUG(dbgs() << '\n');
1453 
1454   // Collect all PredTransitions for individual operands.
1455   // Iterate until no variant writes remain.
1456   while (hasVariant(LastTransitions, *this)) {
1457     PredTransitions Transitions(*this);
1458     for (const PredTransition &Trans : LastTransitions)
1459       Transitions.substituteVariants(Trans);
1460     DEBUG(Transitions.dump());
1461     LastTransitions.swap(Transitions.TransVec);
1462   }
1463   // If the first transition has no variants, nothing to do.
1464   if (LastTransitions[0].PredTerm.empty())
1465     return;
1466 
1467   // WARNING: We are about to mutate the SchedClasses vector. Do not refer to
1468   // OperWrites, OperReads, or ProcIndices after calling inferFromTransitions.
1469   inferFromTransitions(LastTransitions, FromClassIdx, *this);
1470 }
1471 
1472 // Check if any processor resource group contains all resource records in
1473 // SubUnits.
1474 bool CodeGenSchedModels::hasSuperGroup(RecVec &SubUnits, CodeGenProcModel &PM) {
1475   for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
1476     if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
1477       continue;
1478     RecVec SuperUnits =
1479       PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
1480     RecIter RI = SubUnits.begin(), RE = SubUnits.end();
1481     for ( ; RI != RE; ++RI) {
1482       if (!is_contained(SuperUnits, *RI)) {
1483         break;
1484       }
1485     }
1486     if (RI == RE)
1487       return true;
1488   }
1489   return false;
1490 }
1491 
1492 // Verify that overlapping groups have a common supergroup.
1493 void CodeGenSchedModels::verifyProcResourceGroups(CodeGenProcModel &PM) {
1494   for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
1495     if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
1496       continue;
1497     RecVec CheckUnits =
1498       PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
1499     for (unsigned j = i+1; j < e; ++j) {
1500       if (!PM.ProcResourceDefs[j]->isSubClassOf("ProcResGroup"))
1501         continue;
1502       RecVec OtherUnits =
1503         PM.ProcResourceDefs[j]->getValueAsListOfDefs("Resources");
1504       if (std::find_first_of(CheckUnits.begin(), CheckUnits.end(),
1505                              OtherUnits.begin(), OtherUnits.end())
1506           != CheckUnits.end()) {
1507         // CheckUnits and OtherUnits overlap
1508         OtherUnits.insert(OtherUnits.end(), CheckUnits.begin(),
1509                           CheckUnits.end());
1510         if (!hasSuperGroup(OtherUnits, PM)) {
1511           PrintFatalError((PM.ProcResourceDefs[i])->getLoc(),
1512                           "proc resource group overlaps with "
1513                           + PM.ProcResourceDefs[j]->getName()
1514                           + " but no supergroup contains both.");
1515         }
1516       }
1517     }
1518   }
1519 }
1520 
1521 // Collect all the RegisterFile definitions available in this target.
1522 void CodeGenSchedModels::collectRegisterFiles() {
1523   RecVec RegisterFileDefs = Records.getAllDerivedDefinitions("RegisterFile");
1524 
1525   // RegisterFiles is the vector of CodeGenRegisterFile.
1526   for (Record *RF : RegisterFileDefs) {
1527     // For each register file definition, construct a CodeGenRegisterFile object
1528     // and add it to the appropriate scheduling model.
1529     CodeGenProcModel &PM = getProcModel(RF->getValueAsDef("SchedModel"));
1530     PM.RegisterFiles.emplace_back(CodeGenRegisterFile(RF->getName(),RF));
1531     CodeGenRegisterFile &CGRF = PM.RegisterFiles.back();
1532 
1533     // Now set the number of physical registers as well as the cost of registers
1534     // in each register class.
1535     CGRF.NumPhysRegs = RF->getValueAsInt("NumPhysRegs");
1536     RecVec RegisterClasses = RF->getValueAsListOfDefs("RegClasses");
1537     std::vector<int64_t> RegisterCosts = RF->getValueAsListOfInts("RegCosts");
1538     for (unsigned I = 0, E = RegisterClasses.size(); I < E; ++I) {
1539       int Cost = RegisterCosts.size() > I ? RegisterCosts[I] : 1;
1540       CGRF.Costs.emplace_back(RegisterClasses[I], Cost);
1541     }
1542   }
1543 }
1544 
1545 // Collect all the RegisterFile definitions available in this target.
1546 void CodeGenSchedModels::collectPfmCounters() {
1547   for (Record *Def : Records.getAllDerivedDefinitions("PfmIssueCounter")) {
1548     CodeGenProcModel &PM = getProcModel(Def->getValueAsDef("SchedModel"));
1549     PM.PfmIssueCounterDefs.emplace_back(Def);
1550   }
1551   for (Record *Def : Records.getAllDerivedDefinitions("PfmCycleCounter")) {
1552     CodeGenProcModel &PM = getProcModel(Def->getValueAsDef("SchedModel"));
1553     if (PM.PfmCycleCounterDef) {
1554       PrintFatalError(Def->getLoc(),
1555                       "multiple cycle counters for " +
1556                           Def->getValueAsDef("SchedModel")->getName());
1557     }
1558     PM.PfmCycleCounterDef = Def;
1559   }
1560 }
1561 
1562 // Collect and sort WriteRes, ReadAdvance, and ProcResources.
1563 void CodeGenSchedModels::collectProcResources() {
1564   ProcResourceDefs = Records.getAllDerivedDefinitions("ProcResourceUnits");
1565   ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
1566 
1567   // Add any subtarget-specific SchedReadWrites that are directly associated
1568   // with processor resources. Refer to the parent SchedClass's ProcIndices to
1569   // determine which processors they apply to.
1570   for (SchedClassIter SCI = schedClassBegin(), SCE = schedClassEnd();
1571        SCI != SCE; ++SCI) {
1572     if (SCI->ItinClassDef)
1573       collectItinProcResources(SCI->ItinClassDef);
1574     else {
1575       // This class may have a default ReadWrite list which can be overriden by
1576       // InstRW definitions.
1577       if (!SCI->InstRWs.empty()) {
1578         for (RecIter RWI = SCI->InstRWs.begin(), RWE = SCI->InstRWs.end();
1579              RWI != RWE; ++RWI) {
1580           Record *RWModelDef = (*RWI)->getValueAsDef("SchedModel");
1581           unsigned PIdx = getProcModel(RWModelDef).Index;
1582           IdxVec Writes, Reads;
1583           findRWs((*RWI)->getValueAsListOfDefs("OperandReadWrites"),
1584                   Writes, Reads);
1585           collectRWResources(Writes, Reads, PIdx);
1586         }
1587       }
1588       collectRWResources(SCI->Writes, SCI->Reads, SCI->ProcIndices);
1589     }
1590   }
1591   // Add resources separately defined by each subtarget.
1592   RecVec WRDefs = Records.getAllDerivedDefinitions("WriteRes");
1593   for (Record *WR : WRDefs) {
1594     Record *ModelDef = WR->getValueAsDef("SchedModel");
1595     addWriteRes(WR, getProcModel(ModelDef).Index);
1596   }
1597   RecVec SWRDefs = Records.getAllDerivedDefinitions("SchedWriteRes");
1598   for (Record *SWR : SWRDefs) {
1599     Record *ModelDef = SWR->getValueAsDef("SchedModel");
1600     addWriteRes(SWR, getProcModel(ModelDef).Index);
1601   }
1602   RecVec RADefs = Records.getAllDerivedDefinitions("ReadAdvance");
1603   for (Record *RA : RADefs) {
1604     Record *ModelDef = RA->getValueAsDef("SchedModel");
1605     addReadAdvance(RA, getProcModel(ModelDef).Index);
1606   }
1607   RecVec SRADefs = Records.getAllDerivedDefinitions("SchedReadAdvance");
1608   for (Record *SRA : SRADefs) {
1609     if (SRA->getValueInit("SchedModel")->isComplete()) {
1610       Record *ModelDef = SRA->getValueAsDef("SchedModel");
1611       addReadAdvance(SRA, getProcModel(ModelDef).Index);
1612     }
1613   }
1614   // Add ProcResGroups that are defined within this processor model, which may
1615   // not be directly referenced but may directly specify a buffer size.
1616   RecVec ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
1617   for (Record *PRG : ProcResGroups) {
1618     if (!PRG->getValueInit("SchedModel")->isComplete())
1619       continue;
1620     CodeGenProcModel &PM = getProcModel(PRG->getValueAsDef("SchedModel"));
1621     if (!is_contained(PM.ProcResourceDefs, PRG))
1622       PM.ProcResourceDefs.push_back(PRG);
1623   }
1624   // Add ProcResourceUnits unconditionally.
1625   for (Record *PRU : Records.getAllDerivedDefinitions("ProcResourceUnits")) {
1626     if (!PRU->getValueInit("SchedModel")->isComplete())
1627       continue;
1628     CodeGenProcModel &PM = getProcModel(PRU->getValueAsDef("SchedModel"));
1629     if (!is_contained(PM.ProcResourceDefs, PRU))
1630       PM.ProcResourceDefs.push_back(PRU);
1631   }
1632   // Finalize each ProcModel by sorting the record arrays.
1633   for (CodeGenProcModel &PM : ProcModels) {
1634     llvm::sort(PM.WriteResDefs.begin(), PM.WriteResDefs.end(),
1635                LessRecord());
1636     llvm::sort(PM.ReadAdvanceDefs.begin(), PM.ReadAdvanceDefs.end(),
1637                LessRecord());
1638     llvm::sort(PM.ProcResourceDefs.begin(), PM.ProcResourceDefs.end(),
1639                LessRecord());
1640     DEBUG(
1641       PM.dump();
1642       dbgs() << "WriteResDefs: ";
1643       for (RecIter RI = PM.WriteResDefs.begin(),
1644              RE = PM.WriteResDefs.end(); RI != RE; ++RI) {
1645         if ((*RI)->isSubClassOf("WriteRes"))
1646           dbgs() << (*RI)->getValueAsDef("WriteType")->getName() << " ";
1647         else
1648           dbgs() << (*RI)->getName() << " ";
1649       }
1650       dbgs() << "\nReadAdvanceDefs: ";
1651       for (RecIter RI = PM.ReadAdvanceDefs.begin(),
1652              RE = PM.ReadAdvanceDefs.end(); RI != RE; ++RI) {
1653         if ((*RI)->isSubClassOf("ReadAdvance"))
1654           dbgs() << (*RI)->getValueAsDef("ReadType")->getName() << " ";
1655         else
1656           dbgs() << (*RI)->getName() << " ";
1657       }
1658       dbgs() << "\nProcResourceDefs: ";
1659       for (RecIter RI = PM.ProcResourceDefs.begin(),
1660              RE = PM.ProcResourceDefs.end(); RI != RE; ++RI) {
1661         dbgs() << (*RI)->getName() << " ";
1662       }
1663       dbgs() << '\n');
1664     verifyProcResourceGroups(PM);
1665   }
1666 
1667   ProcResourceDefs.clear();
1668   ProcResGroups.clear();
1669 }
1670 
1671 void CodeGenSchedModels::checkCompleteness() {
1672   bool Complete = true;
1673   bool HadCompleteModel = false;
1674   for (const CodeGenProcModel &ProcModel : procModels()) {
1675     const bool HasItineraries = ProcModel.hasItineraries();
1676     if (!ProcModel.ModelDef->getValueAsBit("CompleteModel"))
1677       continue;
1678     for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
1679       if (Inst->hasNoSchedulingInfo)
1680         continue;
1681       if (ProcModel.isUnsupported(*Inst))
1682         continue;
1683       unsigned SCIdx = getSchedClassIdx(*Inst);
1684       if (!SCIdx) {
1685         if (Inst->TheDef->isValueUnset("SchedRW") && !HadCompleteModel) {
1686           PrintError("No schedule information for instruction '"
1687                      + Inst->TheDef->getName() + "'");
1688           Complete = false;
1689         }
1690         continue;
1691       }
1692 
1693       const CodeGenSchedClass &SC = getSchedClass(SCIdx);
1694       if (!SC.Writes.empty())
1695         continue;
1696       if (HasItineraries && SC.ItinClassDef != nullptr &&
1697           SC.ItinClassDef->getName() != "NoItinerary")
1698         continue;
1699 
1700       const RecVec &InstRWs = SC.InstRWs;
1701       auto I = find_if(InstRWs, [&ProcModel](const Record *R) {
1702         return R->getValueAsDef("SchedModel") == ProcModel.ModelDef;
1703       });
1704       if (I == InstRWs.end()) {
1705         PrintError("'" + ProcModel.ModelName + "' lacks information for '" +
1706                    Inst->TheDef->getName() + "'");
1707         Complete = false;
1708       }
1709     }
1710     HadCompleteModel = true;
1711   }
1712   if (!Complete) {
1713     errs() << "\n\nIncomplete schedule models found.\n"
1714       << "- Consider setting 'CompleteModel = 0' while developing new models.\n"
1715       << "- Pseudo instructions can be marked with 'hasNoSchedulingInfo = 1'.\n"
1716       << "- Instructions should usually have Sched<[...]> as a superclass, "
1717          "you may temporarily use an empty list.\n"
1718       << "- Instructions related to unsupported features can be excluded with "
1719          "list<Predicate> UnsupportedFeatures = [HasA,..,HasY]; in the "
1720          "processor model.\n\n";
1721     PrintFatalError("Incomplete schedule model");
1722   }
1723 }
1724 
1725 // Collect itinerary class resources for each processor.
1726 void CodeGenSchedModels::collectItinProcResources(Record *ItinClassDef) {
1727   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
1728     const CodeGenProcModel &PM = ProcModels[PIdx];
1729     // For all ItinRW entries.
1730     bool HasMatch = false;
1731     for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
1732          II != IE; ++II) {
1733       RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
1734       if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
1735         continue;
1736       if (HasMatch)
1737         PrintFatalError((*II)->getLoc(), "Duplicate itinerary class "
1738                         + ItinClassDef->getName()
1739                         + " in ItinResources for " + PM.ModelName);
1740       HasMatch = true;
1741       IdxVec Writes, Reads;
1742       findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1743       collectRWResources(Writes, Reads, PIdx);
1744     }
1745   }
1746 }
1747 
1748 void CodeGenSchedModels::collectRWResources(unsigned RWIdx, bool IsRead,
1749                                             ArrayRef<unsigned> ProcIndices) {
1750   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
1751   if (SchedRW.TheDef) {
1752     if (!IsRead && SchedRW.TheDef->isSubClassOf("SchedWriteRes")) {
1753       for (unsigned Idx : ProcIndices)
1754         addWriteRes(SchedRW.TheDef, Idx);
1755     }
1756     else if (IsRead && SchedRW.TheDef->isSubClassOf("SchedReadAdvance")) {
1757       for (unsigned Idx : ProcIndices)
1758         addReadAdvance(SchedRW.TheDef, Idx);
1759     }
1760   }
1761   for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
1762        AI != AE; ++AI) {
1763     IdxVec AliasProcIndices;
1764     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
1765       AliasProcIndices.push_back(
1766         getProcModel((*AI)->getValueAsDef("SchedModel")).Index);
1767     }
1768     else
1769       AliasProcIndices = ProcIndices;
1770     const CodeGenSchedRW &AliasRW = getSchedRW((*AI)->getValueAsDef("AliasRW"));
1771     assert(AliasRW.IsRead == IsRead && "cannot alias reads to writes");
1772 
1773     IdxVec ExpandedRWs;
1774     expandRWSequence(AliasRW.Index, ExpandedRWs, IsRead);
1775     for (IdxIter SI = ExpandedRWs.begin(), SE = ExpandedRWs.end();
1776          SI != SE; ++SI) {
1777       collectRWResources(*SI, IsRead, AliasProcIndices);
1778     }
1779   }
1780 }
1781 
1782 // Collect resources for a set of read/write types and processor indices.
1783 void CodeGenSchedModels::collectRWResources(ArrayRef<unsigned> Writes,
1784                                             ArrayRef<unsigned> Reads,
1785                                             ArrayRef<unsigned> ProcIndices) {
1786   for (unsigned Idx : Writes)
1787     collectRWResources(Idx, /*IsRead=*/false, ProcIndices);
1788 
1789   for (unsigned Idx : Reads)
1790     collectRWResources(Idx, /*IsRead=*/true, ProcIndices);
1791 }
1792 
1793 // Find the processor's resource units for this kind of resource.
1794 Record *CodeGenSchedModels::findProcResUnits(Record *ProcResKind,
1795                                              const CodeGenProcModel &PM,
1796                                              ArrayRef<SMLoc> Loc) const {
1797   if (ProcResKind->isSubClassOf("ProcResourceUnits"))
1798     return ProcResKind;
1799 
1800   Record *ProcUnitDef = nullptr;
1801   assert(!ProcResourceDefs.empty());
1802   assert(!ProcResGroups.empty());
1803 
1804   for (Record *ProcResDef : ProcResourceDefs) {
1805     if (ProcResDef->getValueAsDef("Kind") == ProcResKind
1806         && ProcResDef->getValueAsDef("SchedModel") == PM.ModelDef) {
1807       if (ProcUnitDef) {
1808         PrintFatalError(Loc,
1809                         "Multiple ProcessorResourceUnits associated with "
1810                         + ProcResKind->getName());
1811       }
1812       ProcUnitDef = ProcResDef;
1813     }
1814   }
1815   for (Record *ProcResGroup : ProcResGroups) {
1816     if (ProcResGroup == ProcResKind
1817         && ProcResGroup->getValueAsDef("SchedModel") == PM.ModelDef) {
1818       if (ProcUnitDef) {
1819         PrintFatalError(Loc,
1820                         "Multiple ProcessorResourceUnits associated with "
1821                         + ProcResKind->getName());
1822       }
1823       ProcUnitDef = ProcResGroup;
1824     }
1825   }
1826   if (!ProcUnitDef) {
1827     PrintFatalError(Loc,
1828                     "No ProcessorResources associated with "
1829                     + ProcResKind->getName());
1830   }
1831   return ProcUnitDef;
1832 }
1833 
1834 // Iteratively add a resource and its super resources.
1835 void CodeGenSchedModels::addProcResource(Record *ProcResKind,
1836                                          CodeGenProcModel &PM,
1837                                          ArrayRef<SMLoc> Loc) {
1838   while (true) {
1839     Record *ProcResUnits = findProcResUnits(ProcResKind, PM, Loc);
1840 
1841     // See if this ProcResource is already associated with this processor.
1842     if (is_contained(PM.ProcResourceDefs, ProcResUnits))
1843       return;
1844 
1845     PM.ProcResourceDefs.push_back(ProcResUnits);
1846     if (ProcResUnits->isSubClassOf("ProcResGroup"))
1847       return;
1848 
1849     if (!ProcResUnits->getValueInit("Super")->isComplete())
1850       return;
1851 
1852     ProcResKind = ProcResUnits->getValueAsDef("Super");
1853   }
1854 }
1855 
1856 // Add resources for a SchedWrite to this processor if they don't exist.
1857 void CodeGenSchedModels::addWriteRes(Record *ProcWriteResDef, unsigned PIdx) {
1858   assert(PIdx && "don't add resources to an invalid Processor model");
1859 
1860   RecVec &WRDefs = ProcModels[PIdx].WriteResDefs;
1861   if (is_contained(WRDefs, ProcWriteResDef))
1862     return;
1863   WRDefs.push_back(ProcWriteResDef);
1864 
1865   // Visit ProcResourceKinds referenced by the newly discovered WriteRes.
1866   RecVec ProcResDefs = ProcWriteResDef->getValueAsListOfDefs("ProcResources");
1867   for (RecIter WritePRI = ProcResDefs.begin(), WritePRE = ProcResDefs.end();
1868        WritePRI != WritePRE; ++WritePRI) {
1869     addProcResource(*WritePRI, ProcModels[PIdx], ProcWriteResDef->getLoc());
1870   }
1871 }
1872 
1873 // Add resources for a ReadAdvance to this processor if they don't exist.
1874 void CodeGenSchedModels::addReadAdvance(Record *ProcReadAdvanceDef,
1875                                         unsigned PIdx) {
1876   RecVec &RADefs = ProcModels[PIdx].ReadAdvanceDefs;
1877   if (is_contained(RADefs, ProcReadAdvanceDef))
1878     return;
1879   RADefs.push_back(ProcReadAdvanceDef);
1880 }
1881 
1882 unsigned CodeGenProcModel::getProcResourceIdx(Record *PRDef) const {
1883   RecIter PRPos = find(ProcResourceDefs, PRDef);
1884   if (PRPos == ProcResourceDefs.end())
1885     PrintFatalError(PRDef->getLoc(), "ProcResource def is not included in "
1886                     "the ProcResources list for " + ModelName);
1887   // Idx=0 is reserved for invalid.
1888   return 1 + (PRPos - ProcResourceDefs.begin());
1889 }
1890 
1891 bool CodeGenProcModel::isUnsupported(const CodeGenInstruction &Inst) const {
1892   for (const Record *TheDef : UnsupportedFeaturesDefs) {
1893     for (const Record *PredDef : Inst.TheDef->getValueAsListOfDefs("Predicates")) {
1894       if (TheDef->getName() == PredDef->getName())
1895         return true;
1896     }
1897   }
1898   return false;
1899 }
1900 
1901 #ifndef NDEBUG
1902 void CodeGenProcModel::dump() const {
1903   dbgs() << Index << ": " << ModelName << " "
1904          << (ModelDef ? ModelDef->getName() : "inferred") << " "
1905          << (ItinsDef ? ItinsDef->getName() : "no itinerary") << '\n';
1906 }
1907 
1908 void CodeGenSchedRW::dump() const {
1909   dbgs() << Name << (IsVariadic ? " (V) " : " ");
1910   if (IsSequence) {
1911     dbgs() << "(";
1912     dumpIdxVec(Sequence);
1913     dbgs() << ")";
1914   }
1915 }
1916 
1917 void CodeGenSchedClass::dump(const CodeGenSchedModels* SchedModels) const {
1918   dbgs() << "SCHEDCLASS " << Index << ":" << Name << '\n'
1919          << "  Writes: ";
1920   for (unsigned i = 0, N = Writes.size(); i < N; ++i) {
1921     SchedModels->getSchedWrite(Writes[i]).dump();
1922     if (i < N-1) {
1923       dbgs() << '\n';
1924       dbgs().indent(10);
1925     }
1926   }
1927   dbgs() << "\n  Reads: ";
1928   for (unsigned i = 0, N = Reads.size(); i < N; ++i) {
1929     SchedModels->getSchedRead(Reads[i]).dump();
1930     if (i < N-1) {
1931       dbgs() << '\n';
1932       dbgs().indent(10);
1933     }
1934   }
1935   dbgs() << "\n  ProcIdx: "; dumpIdxVec(ProcIndices); dbgs() << '\n';
1936   if (!Transitions.empty()) {
1937     dbgs() << "\n Transitions for Proc ";
1938     for (const CodeGenSchedTransition &Transition : Transitions) {
1939       dumpIdxVec(Transition.ProcIndices);
1940     }
1941   }
1942 }
1943 
1944 void PredTransitions::dump() const {
1945   dbgs() << "Expanded Variants:\n";
1946   for (std::vector<PredTransition>::const_iterator
1947          TI = TransVec.begin(), TE = TransVec.end(); TI != TE; ++TI) {
1948     dbgs() << "{";
1949     for (SmallVectorImpl<PredCheck>::const_iterator
1950            PCI = TI->PredTerm.begin(), PCE = TI->PredTerm.end();
1951          PCI != PCE; ++PCI) {
1952       if (PCI != TI->PredTerm.begin())
1953         dbgs() << ", ";
1954       dbgs() << SchedModels.getSchedRW(PCI->RWIdx, PCI->IsRead).Name
1955              << ":" << PCI->Predicate->getName();
1956     }
1957     dbgs() << "},\n  => {";
1958     for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
1959            WSI = TI->WriteSequences.begin(), WSE = TI->WriteSequences.end();
1960          WSI != WSE; ++WSI) {
1961       dbgs() << "(";
1962       for (SmallVectorImpl<unsigned>::const_iterator
1963              WI = WSI->begin(), WE = WSI->end(); WI != WE; ++WI) {
1964         if (WI != WSI->begin())
1965           dbgs() << ", ";
1966         dbgs() << SchedModels.getSchedWrite(*WI).Name;
1967       }
1968       dbgs() << "),";
1969     }
1970     dbgs() << "}\n";
1971   }
1972 }
1973 #endif // NDEBUG
1974