xref: /src/contrib/llvm-project/llvm/utils/TableGen/Common/CodeGenSchedule.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
158b69754SDimitry Andric //===- CodeGenSchedule.cpp - Scheduling MachineModels ---------------------===//
258b69754SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
658b69754SDimitry Andric //
758b69754SDimitry Andric //===----------------------------------------------------------------------===//
858b69754SDimitry Andric //
95ca98fd9SDimitry Andric // This file defines structures to encapsulate the machine model as described in
1058b69754SDimitry Andric // the target description.
1158b69754SDimitry Andric //
1258b69754SDimitry Andric //===----------------------------------------------------------------------===//
1358b69754SDimitry Andric 
1458b69754SDimitry Andric #include "CodeGenSchedule.h"
15eb11fae6SDimitry Andric #include "CodeGenInstruction.h"
1658b69754SDimitry Andric #include "CodeGenTarget.h"
17eb11fae6SDimitry Andric #include "llvm/ADT/MapVector.h"
18eb11fae6SDimitry Andric #include "llvm/ADT/STLExtras.h"
19b915e9e0SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
20b915e9e0SDimitry Andric #include "llvm/ADT/SmallVector.h"
21b915e9e0SDimitry Andric #include "llvm/Support/Casting.h"
2258b69754SDimitry Andric #include "llvm/Support/Debug.h"
23522600a2SDimitry Andric #include "llvm/Support/Regex.h"
24eb11fae6SDimitry Andric #include "llvm/Support/raw_ostream.h"
254a16efa3SDimitry Andric #include "llvm/TableGen/Error.h"
26b915e9e0SDimitry Andric #include <algorithm>
27b915e9e0SDimitry Andric #include <iterator>
28b915e9e0SDimitry Andric #include <utility>
2958b69754SDimitry Andric 
3058b69754SDimitry Andric using namespace llvm;
3158b69754SDimitry Andric 
325ca98fd9SDimitry Andric #define DEBUG_TYPE "subtarget-emitter"
335ca98fd9SDimitry Andric 
34522600a2SDimitry Andric #ifndef NDEBUG
dumpIdxVec(ArrayRef<unsigned> V)35dd58ef01SDimitry Andric static void dumpIdxVec(ArrayRef<unsigned> V) {
36dd58ef01SDimitry Andric   for (unsigned Idx : V)
37dd58ef01SDimitry Andric     dbgs() << Idx << ", ";
38522600a2SDimitry Andric }
39522600a2SDimitry Andric #endif
40522600a2SDimitry Andric 
41f8af5cf6SDimitry Andric namespace {
42b915e9e0SDimitry Andric 
43522600a2SDimitry Andric // (instrs a, b, ...) Evaluate and union all arguments. Identical to AddOp.
44522600a2SDimitry Andric struct InstrsOp : public SetTheory::Operator {
apply__anon5fa3bdea0111::InstrsOp455ca98fd9SDimitry Andric   void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
465ca98fd9SDimitry Andric              ArrayRef<SMLoc> Loc) override {
47522600a2SDimitry Andric     ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts, Loc);
48522600a2SDimitry Andric   }
49522600a2SDimitry Andric };
50522600a2SDimitry Andric 
51522600a2SDimitry Andric // (instregex "OpcPat",...) Find all instructions matching an opcode pattern.
52522600a2SDimitry Andric struct InstRegexOp : public SetTheory::Operator {
53522600a2SDimitry Andric   const CodeGenTarget &Target;
InstRegexOp__anon5fa3bdea0111::InstRegexOp54522600a2SDimitry Andric   InstRegexOp(const CodeGenTarget &t) : Target(t) {}
55522600a2SDimitry Andric 
56eb11fae6SDimitry Andric   /// Remove any text inside of parentheses from S.
removeParens__anon5fa3bdea0111::InstRegexOp57eb11fae6SDimitry Andric   static std::string removeParens(llvm::StringRef S) {
58eb11fae6SDimitry Andric     std::string Result;
59eb11fae6SDimitry Andric     unsigned Paren = 0;
60eb11fae6SDimitry Andric     // NB: We don't care about escaped parens here.
61eb11fae6SDimitry Andric     for (char C : S) {
62eb11fae6SDimitry Andric       switch (C) {
63eb11fae6SDimitry Andric       case '(':
64eb11fae6SDimitry Andric         ++Paren;
65eb11fae6SDimitry Andric         break;
66eb11fae6SDimitry Andric       case ')':
67eb11fae6SDimitry Andric         --Paren;
68eb11fae6SDimitry Andric         break;
69eb11fae6SDimitry Andric       default:
70eb11fae6SDimitry Andric         if (Paren == 0)
71eb11fae6SDimitry Andric           Result += C;
72eb11fae6SDimitry Andric       }
73eb11fae6SDimitry Andric     }
74eb11fae6SDimitry Andric     return Result;
75eb11fae6SDimitry Andric   }
76eb11fae6SDimitry Andric 
apply__anon5fa3bdea0111::InstRegexOp77522600a2SDimitry Andric   void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
785ca98fd9SDimitry Andric              ArrayRef<SMLoc> Loc) override {
79eb11fae6SDimitry Andric     ArrayRef<const CodeGenInstruction *> Instructions =
80eb11fae6SDimitry Andric         Target.getInstructionsByEnumValue();
81eb11fae6SDimitry Andric 
82eb11fae6SDimitry Andric     unsigned NumGeneric = Target.getNumFixedInstructions();
83eb11fae6SDimitry Andric     unsigned NumPseudos = Target.getNumPseudoInstructions();
84eb11fae6SDimitry Andric     auto Generics = Instructions.slice(0, NumGeneric);
85eb11fae6SDimitry Andric     auto Pseudos = Instructions.slice(NumGeneric, NumPseudos);
86eb11fae6SDimitry Andric     auto NonPseudos = Instructions.slice(NumGeneric + NumPseudos);
87eb11fae6SDimitry Andric 
88b60736ecSDimitry Andric     for (Init *Arg : Expr->getArgs()) {
89044eb2f6SDimitry Andric       StringInit *SI = dyn_cast<StringInit>(Arg);
90522600a2SDimitry Andric       if (!SI)
91eb11fae6SDimitry Andric         PrintFatalError(Loc, "instregex requires pattern string: " +
92eb11fae6SDimitry Andric                                  Expr->getAsString());
93eb11fae6SDimitry Andric       StringRef Original = SI->getValue();
94b1c73532SDimitry Andric       // Drop an explicit ^ anchor to not interfere with prefix search.
95b1c73532SDimitry Andric       bool HadAnchor = Original.consume_front("^");
96eb11fae6SDimitry Andric 
97eb11fae6SDimitry Andric       // Extract a prefix that we can binary search on.
98eb11fae6SDimitry Andric       static const char RegexMetachars[] = "()^$|*+?.[]\\{}";
99eb11fae6SDimitry Andric       auto FirstMeta = Original.find_first_of(RegexMetachars);
100b1c73532SDimitry Andric       if (FirstMeta != StringRef::npos && FirstMeta > 0) {
101b1c73532SDimitry Andric         // If we have a regex like ABC* we can only use AB as the prefix, as
102b1c73532SDimitry Andric         // the * acts on C.
103b1c73532SDimitry Andric         switch (Original[FirstMeta]) {
104b1c73532SDimitry Andric         case '+':
105b1c73532SDimitry Andric         case '*':
106b1c73532SDimitry Andric         case '?':
107b1c73532SDimitry Andric           --FirstMeta;
108b1c73532SDimitry Andric           break;
109b1c73532SDimitry Andric         default:
110b1c73532SDimitry Andric           break;
111b1c73532SDimitry Andric         }
112b1c73532SDimitry Andric       }
113eb11fae6SDimitry Andric 
114eb11fae6SDimitry Andric       // Look for top-level | or ?. We cannot optimize them to binary search.
115eb11fae6SDimitry Andric       if (removeParens(Original).find_first_of("|?") != std::string::npos)
116eb11fae6SDimitry Andric         FirstMeta = 0;
117eb11fae6SDimitry Andric 
118e3b55780SDimitry Andric       std::optional<Regex> Regexpr;
119eb11fae6SDimitry Andric       StringRef Prefix = Original.substr(0, FirstMeta);
120eb11fae6SDimitry Andric       StringRef PatStr = Original.substr(FirstMeta);
121eb11fae6SDimitry Andric       if (!PatStr.empty()) {
122eb11fae6SDimitry Andric         // For the rest use a python-style prefix match.
123cfca06d7SDimitry Andric         std::string pat = std::string(PatStr);
124b1c73532SDimitry Andric         // Add ^ anchor. If we had one originally, don't need the group.
125b1c73532SDimitry Andric         if (HadAnchor) {
126b1c73532SDimitry Andric           pat.insert(0, "^");
127b1c73532SDimitry Andric         } else {
128522600a2SDimitry Andric           pat.insert(0, "^(");
129522600a2SDimitry Andric           pat.insert(pat.end(), ')');
130522600a2SDimitry Andric         }
131eb11fae6SDimitry Andric         Regexpr = Regex(pat);
132522600a2SDimitry Andric       }
133eb11fae6SDimitry Andric 
134eb11fae6SDimitry Andric       int NumMatches = 0;
135eb11fae6SDimitry Andric 
136eb11fae6SDimitry Andric       // The generic opcodes are unsorted, handle them manually.
137eb11fae6SDimitry Andric       for (auto *Inst : Generics) {
138eb11fae6SDimitry Andric         StringRef InstName = Inst->TheDef->getName();
139b1c73532SDimitry Andric         if (InstName.starts_with(Prefix) &&
140eb11fae6SDimitry Andric             (!Regexpr || Regexpr->match(InstName.substr(Prefix.size())))) {
14167c32a98SDimitry Andric           Elts.insert(Inst->TheDef);
142eb11fae6SDimitry Andric           NumMatches++;
143522600a2SDimitry Andric         }
144522600a2SDimitry Andric       }
145eb11fae6SDimitry Andric 
146eb11fae6SDimitry Andric       // Target instructions are split into two ranges: pseudo instructions
147eb11fae6SDimitry Andric       // first, than non-pseudos. Each range is in lexicographical order
148eb11fae6SDimitry Andric       // sorted by name. Find the sub-ranges that start with our prefix.
149eb11fae6SDimitry Andric       struct Comp {
150eb11fae6SDimitry Andric         bool operator()(const CodeGenInstruction *LHS, StringRef RHS) {
151eb11fae6SDimitry Andric           return LHS->TheDef->getName() < RHS;
152eb11fae6SDimitry Andric         }
153eb11fae6SDimitry Andric         bool operator()(StringRef LHS, const CodeGenInstruction *RHS) {
154eb11fae6SDimitry Andric           return LHS < RHS->TheDef->getName() &&
155b1c73532SDimitry Andric                  !RHS->TheDef->getName().starts_with(LHS);
156eb11fae6SDimitry Andric         }
157eb11fae6SDimitry Andric       };
158eb11fae6SDimitry Andric       auto Range1 =
159eb11fae6SDimitry Andric           std::equal_range(Pseudos.begin(), Pseudos.end(), Prefix, Comp());
160eb11fae6SDimitry Andric       auto Range2 = std::equal_range(NonPseudos.begin(), NonPseudos.end(),
161eb11fae6SDimitry Andric                                      Prefix, Comp());
162eb11fae6SDimitry Andric 
163eb11fae6SDimitry Andric       // For these ranges we know that instruction names start with the prefix.
164eb11fae6SDimitry Andric       // Check if there's a regex that needs to be checked.
165eb11fae6SDimitry Andric       const auto HandleNonGeneric = [&](const CodeGenInstruction *Inst) {
166eb11fae6SDimitry Andric         StringRef InstName = Inst->TheDef->getName();
167eb11fae6SDimitry Andric         if (!Regexpr || Regexpr->match(InstName.substr(Prefix.size()))) {
168eb11fae6SDimitry Andric           Elts.insert(Inst->TheDef);
169eb11fae6SDimitry Andric           NumMatches++;
170eb11fae6SDimitry Andric         }
171eb11fae6SDimitry Andric       };
172eb11fae6SDimitry Andric       std::for_each(Range1.first, Range1.second, HandleNonGeneric);
173eb11fae6SDimitry Andric       std::for_each(Range2.first, Range2.second, HandleNonGeneric);
174eb11fae6SDimitry Andric 
175eb11fae6SDimitry Andric       if (0 == NumMatches)
176eb11fae6SDimitry Andric         PrintFatalError(Loc, "instregex has no matches: " + Original);
177eb11fae6SDimitry Andric     }
178522600a2SDimitry Andric   }
179522600a2SDimitry Andric };
180b915e9e0SDimitry Andric 
181f8af5cf6SDimitry Andric } // end anonymous namespace
182522600a2SDimitry Andric 
183522600a2SDimitry Andric /// CodeGenModels ctor interprets machine model records and populates maps.
CodeGenSchedModels(RecordKeeper & RK,const CodeGenTarget & TGT)18458b69754SDimitry Andric CodeGenSchedModels::CodeGenSchedModels(RecordKeeper &RK,
185ac9a064cSDimitry Andric                                        const CodeGenTarget &TGT)
186ac9a064cSDimitry Andric     : Records(RK), Target(TGT) {
18758b69754SDimitry Andric 
188522600a2SDimitry Andric   Sets.addFieldExpander("InstRW", "Instrs");
18958b69754SDimitry Andric 
190522600a2SDimitry Andric   // Allow Set evaluation to recognize the dags used in InstRW records:
191522600a2SDimitry Andric   // (instrs Op1, Op1...)
1921d5ae102SDimitry Andric   Sets.addOperator("instrs", std::make_unique<InstrsOp>());
1931d5ae102SDimitry Andric   Sets.addOperator("instregex", std::make_unique<InstRegexOp>(Target));
194522600a2SDimitry Andric 
195522600a2SDimitry Andric   // Instantiate a CodeGenProcModel for each SchedMachineModel with the values
196522600a2SDimitry Andric   // that are explicitly referenced in tablegen records. Resources associated
197522600a2SDimitry Andric   // with each processor will be derived later. Populate ProcModelMap with the
198522600a2SDimitry Andric   // CodeGenProcModel instances.
199522600a2SDimitry Andric   collectProcModels();
200522600a2SDimitry Andric 
201522600a2SDimitry Andric   // Instantiate a CodeGenSchedRW for each SchedReadWrite record explicitly
202522600a2SDimitry Andric   // defined, and populate SchedReads and SchedWrites vectors. Implicit
203522600a2SDimitry Andric   // SchedReadWrites that represent sequences derived from expanded variant will
204522600a2SDimitry Andric   // be inferred later.
205522600a2SDimitry Andric   collectSchedRW();
206522600a2SDimitry Andric 
207522600a2SDimitry Andric   // Instantiate a CodeGenSchedClass for each unique SchedRW signature directly
208522600a2SDimitry Andric   // required by an instruction definition, and populate SchedClassIdxMap. Set
209522600a2SDimitry Andric   // NumItineraryClasses to the number of explicit itinerary classes referenced
210522600a2SDimitry Andric   // by instructions. Set NumInstrSchedClasses to the number of itinerary
211522600a2SDimitry Andric   // classes plus any classes implied by instructions that derive from class
212522600a2SDimitry Andric   // Sched and provide SchedRW list. This does not infer any new classes from
213522600a2SDimitry Andric   // SchedVariant.
214522600a2SDimitry Andric   collectSchedClasses();
215522600a2SDimitry Andric 
216522600a2SDimitry Andric   // Find instruction itineraries for each processor. Sort and populate
217522600a2SDimitry Andric   // CodeGenProcModel::ItinDefList. (Cycle-to-cycle itineraries). This requires
218522600a2SDimitry Andric   // all itinerary classes to be discovered.
219522600a2SDimitry Andric   collectProcItins();
220522600a2SDimitry Andric 
221522600a2SDimitry Andric   // Find ItinRW records for each processor and itinerary class.
222522600a2SDimitry Andric   // (For per-operand resources mapped to itinerary classes).
223522600a2SDimitry Andric   collectProcItinRW();
224522600a2SDimitry Andric 
22501095a5dSDimitry Andric   // Find UnsupportedFeatures records for each processor.
22601095a5dSDimitry Andric   // (For per-operand resources mapped to itinerary classes).
22701095a5dSDimitry Andric   collectProcUnsupportedFeatures();
22801095a5dSDimitry Andric 
229522600a2SDimitry Andric   // Infer new SchedClasses from SchedVariant.
230522600a2SDimitry Andric   inferSchedClasses();
231522600a2SDimitry Andric 
232522600a2SDimitry Andric   // Populate each CodeGenProcModel's WriteResDefs, ReadAdvanceDefs, and
233522600a2SDimitry Andric   // ProcResourceDefs.
234eb11fae6SDimitry Andric   LLVM_DEBUG(
235eb11fae6SDimitry Andric       dbgs() << "\n+++ RESOURCE DEFINITIONS (collectProcResources) +++\n");
236522600a2SDimitry Andric   collectProcResources();
23701095a5dSDimitry Andric 
238eb11fae6SDimitry Andric   // Collect optional processor description.
239eb11fae6SDimitry Andric   collectOptionalProcessorInfo();
240eb11fae6SDimitry Andric 
241d8e91e46SDimitry Andric   // Check MCInstPredicate definitions.
242d8e91e46SDimitry Andric   checkMCInstPredicates();
243d8e91e46SDimitry Andric 
244d8e91e46SDimitry Andric   // Check STIPredicate definitions.
245d8e91e46SDimitry Andric   checkSTIPredicates();
246d8e91e46SDimitry Andric 
247d8e91e46SDimitry Andric   // Find STIPredicate definitions for each processor model, and construct
248d8e91e46SDimitry Andric   // STIPredicateFunction objects.
249d8e91e46SDimitry Andric   collectSTIPredicates();
250d8e91e46SDimitry Andric 
251eb11fae6SDimitry Andric   checkCompleteness();
252eb11fae6SDimitry Andric }
253eb11fae6SDimitry Andric 
checkSTIPredicates() const254d8e91e46SDimitry Andric void CodeGenSchedModels::checkSTIPredicates() const {
255d8e91e46SDimitry Andric   DenseMap<StringRef, const Record *> Declarations;
256d8e91e46SDimitry Andric 
257d8e91e46SDimitry Andric   // There cannot be multiple declarations with the same name.
258d8e91e46SDimitry Andric   const RecVec Decls = Records.getAllDerivedDefinitions("STIPredicateDecl");
259d8e91e46SDimitry Andric   for (const Record *R : Decls) {
260d8e91e46SDimitry Andric     StringRef Name = R->getValueAsString("Name");
261d8e91e46SDimitry Andric     const auto It = Declarations.find(Name);
262d8e91e46SDimitry Andric     if (It == Declarations.end()) {
263d8e91e46SDimitry Andric       Declarations[Name] = R;
264d8e91e46SDimitry Andric       continue;
265d8e91e46SDimitry Andric     }
266d8e91e46SDimitry Andric 
267d8e91e46SDimitry Andric     PrintError(R->getLoc(), "STIPredicate " + Name + " multiply declared.");
268b60736ecSDimitry Andric     PrintFatalNote(It->second->getLoc(), "Previous declaration was here.");
269d8e91e46SDimitry Andric   }
270d8e91e46SDimitry Andric 
271d8e91e46SDimitry Andric   // Disallow InstructionEquivalenceClasses with an empty instruction list.
272d8e91e46SDimitry Andric   const RecVec Defs =
273d8e91e46SDimitry Andric       Records.getAllDerivedDefinitions("InstructionEquivalenceClass");
274d8e91e46SDimitry Andric   for (const Record *R : Defs) {
275d8e91e46SDimitry Andric     RecVec Opcodes = R->getValueAsListOfDefs("Opcodes");
276d8e91e46SDimitry Andric     if (Opcodes.empty()) {
277d8e91e46SDimitry Andric       PrintFatalError(R->getLoc(), "Invalid InstructionEquivalenceClass "
278d8e91e46SDimitry Andric                                    "defined with an empty opcode list.");
279d8e91e46SDimitry Andric     }
280d8e91e46SDimitry Andric   }
281d8e91e46SDimitry Andric }
282d8e91e46SDimitry Andric 
283d8e91e46SDimitry Andric // Used by function `processSTIPredicate` to construct a mask of machine
284d8e91e46SDimitry Andric // instruction operands.
constructOperandMask(ArrayRef<int64_t> Indices)285d8e91e46SDimitry Andric static APInt constructOperandMask(ArrayRef<int64_t> Indices) {
286d8e91e46SDimitry Andric   APInt OperandMask;
287d8e91e46SDimitry Andric   if (Indices.empty())
288d8e91e46SDimitry Andric     return OperandMask;
289d8e91e46SDimitry Andric 
290ac9a064cSDimitry Andric   int64_t MaxIndex = *llvm::max_element(Indices);
291d8e91e46SDimitry Andric   assert(MaxIndex >= 0 && "Invalid negative indices in input!");
292d8e91e46SDimitry Andric   OperandMask = OperandMask.zext(MaxIndex + 1);
293d8e91e46SDimitry Andric   for (const int64_t Index : Indices) {
294d8e91e46SDimitry Andric     assert(Index >= 0 && "Invalid negative indices!");
295d8e91e46SDimitry Andric     OperandMask.setBit(Index);
296d8e91e46SDimitry Andric   }
297d8e91e46SDimitry Andric 
298d8e91e46SDimitry Andric   return OperandMask;
299d8e91e46SDimitry Andric }
300d8e91e46SDimitry Andric 
processSTIPredicate(STIPredicateFunction & Fn,const ProcModelMapTy & ProcModelMap)301ac9a064cSDimitry Andric static void processSTIPredicate(STIPredicateFunction &Fn,
302b60736ecSDimitry Andric                                 const ProcModelMapTy &ProcModelMap) {
303d8e91e46SDimitry Andric   DenseMap<const Record *, unsigned> Opcode2Index;
304d8e91e46SDimitry Andric   using OpcodeMapPair = std::pair<const Record *, OpcodeInfo>;
305d8e91e46SDimitry Andric   std::vector<OpcodeMapPair> OpcodeMappings;
306d8e91e46SDimitry Andric   std::vector<std::pair<APInt, APInt>> OpcodeMasks;
307d8e91e46SDimitry Andric 
308d8e91e46SDimitry Andric   DenseMap<const Record *, unsigned> Predicate2Index;
309d8e91e46SDimitry Andric   unsigned NumUniquePredicates = 0;
310d8e91e46SDimitry Andric 
311d8e91e46SDimitry Andric   // Number unique predicates and opcodes used by InstructionEquivalenceClass
312d8e91e46SDimitry Andric   // definitions. Each unique opcode will be associated with an OpcodeInfo
313d8e91e46SDimitry Andric   // object.
314d8e91e46SDimitry Andric   for (const Record *Def : Fn.getDefinitions()) {
315d8e91e46SDimitry Andric     RecVec Classes = Def->getValueAsListOfDefs("Classes");
316d8e91e46SDimitry Andric     for (const Record *EC : Classes) {
317d8e91e46SDimitry Andric       const Record *Pred = EC->getValueAsDef("Predicate");
3187fa27ce4SDimitry Andric       if (!Predicate2Index.contains(Pred))
319d8e91e46SDimitry Andric         Predicate2Index[Pred] = NumUniquePredicates++;
320d8e91e46SDimitry Andric 
321d8e91e46SDimitry Andric       RecVec Opcodes = EC->getValueAsListOfDefs("Opcodes");
322d8e91e46SDimitry Andric       for (const Record *Opcode : Opcodes) {
3237fa27ce4SDimitry Andric         if (!Opcode2Index.contains(Opcode)) {
324d8e91e46SDimitry Andric           Opcode2Index[Opcode] = OpcodeMappings.size();
325d8e91e46SDimitry Andric           OpcodeMappings.emplace_back(Opcode, OpcodeInfo());
326d8e91e46SDimitry Andric         }
327d8e91e46SDimitry Andric       }
328d8e91e46SDimitry Andric     }
329d8e91e46SDimitry Andric   }
330d8e91e46SDimitry Andric 
331d8e91e46SDimitry Andric   // Initialize vector `OpcodeMasks` with default values.  We want to keep track
332d8e91e46SDimitry Andric   // of which processors "use" which opcodes.  We also want to be able to
333d8e91e46SDimitry Andric   // identify predicates that are used by different processors for a same
334d8e91e46SDimitry Andric   // opcode.
335d8e91e46SDimitry Andric   // This information is used later on by this algorithm to sort OpcodeMapping
336d8e91e46SDimitry Andric   // elements based on their processor and predicate sets.
337d8e91e46SDimitry Andric   OpcodeMasks.resize(OpcodeMappings.size());
338d8e91e46SDimitry Andric   APInt DefaultProcMask(ProcModelMap.size(), 0);
339d8e91e46SDimitry Andric   APInt DefaultPredMask(NumUniquePredicates, 0);
340d8e91e46SDimitry Andric   for (std::pair<APInt, APInt> &MaskPair : OpcodeMasks)
341ac9a064cSDimitry Andric     MaskPair = std::pair(DefaultProcMask, DefaultPredMask);
342d8e91e46SDimitry Andric 
343d8e91e46SDimitry Andric   // Construct a OpcodeInfo object for every unique opcode declared by an
344d8e91e46SDimitry Andric   // InstructionEquivalenceClass definition.
345d8e91e46SDimitry Andric   for (const Record *Def : Fn.getDefinitions()) {
346d8e91e46SDimitry Andric     RecVec Classes = Def->getValueAsListOfDefs("Classes");
347d8e91e46SDimitry Andric     const Record *SchedModel = Def->getValueAsDef("SchedModel");
348d8e91e46SDimitry Andric     unsigned ProcIndex = ProcModelMap.find(SchedModel)->second;
349d8e91e46SDimitry Andric     APInt ProcMask(ProcModelMap.size(), 0);
350d8e91e46SDimitry Andric     ProcMask.setBit(ProcIndex);
351d8e91e46SDimitry Andric 
352d8e91e46SDimitry Andric     for (const Record *EC : Classes) {
353d8e91e46SDimitry Andric       RecVec Opcodes = EC->getValueAsListOfDefs("Opcodes");
354d8e91e46SDimitry Andric 
355d8e91e46SDimitry Andric       std::vector<int64_t> OpIndices =
356d8e91e46SDimitry Andric           EC->getValueAsListOfInts("OperandIndices");
357d8e91e46SDimitry Andric       APInt OperandMask = constructOperandMask(OpIndices);
358d8e91e46SDimitry Andric 
359d8e91e46SDimitry Andric       const Record *Pred = EC->getValueAsDef("Predicate");
360d8e91e46SDimitry Andric       APInt PredMask(NumUniquePredicates, 0);
361d8e91e46SDimitry Andric       PredMask.setBit(Predicate2Index[Pred]);
362d8e91e46SDimitry Andric 
363d8e91e46SDimitry Andric       for (const Record *Opcode : Opcodes) {
364d8e91e46SDimitry Andric         unsigned OpcodeIdx = Opcode2Index[Opcode];
365d8e91e46SDimitry Andric         if (OpcodeMasks[OpcodeIdx].first[ProcIndex]) {
366d8e91e46SDimitry Andric           std::string Message =
367d8e91e46SDimitry Andric               "Opcode " + Opcode->getName().str() +
368d8e91e46SDimitry Andric               " used by multiple InstructionEquivalenceClass definitions.";
369d8e91e46SDimitry Andric           PrintFatalError(EC->getLoc(), Message);
370d8e91e46SDimitry Andric         }
371d8e91e46SDimitry Andric         OpcodeMasks[OpcodeIdx].first |= ProcMask;
372d8e91e46SDimitry Andric         OpcodeMasks[OpcodeIdx].second |= PredMask;
373d8e91e46SDimitry Andric         OpcodeInfo &OI = OpcodeMappings[OpcodeIdx].second;
374d8e91e46SDimitry Andric 
375d8e91e46SDimitry Andric         OI.addPredicateForProcModel(ProcMask, OperandMask, Pred);
376d8e91e46SDimitry Andric       }
377d8e91e46SDimitry Andric     }
378d8e91e46SDimitry Andric   }
379d8e91e46SDimitry Andric 
380d8e91e46SDimitry Andric   // Sort OpcodeMappings elements based on their CPU and predicate masks.
381d8e91e46SDimitry Andric   // As a last resort, order elements by opcode identifier.
382ac9a064cSDimitry Andric   llvm::sort(
383ac9a064cSDimitry Andric       OpcodeMappings, [&](const OpcodeMapPair &Lhs, const OpcodeMapPair &Rhs) {
384d8e91e46SDimitry Andric         unsigned LhsIdx = Opcode2Index[Lhs.first];
385d8e91e46SDimitry Andric         unsigned RhsIdx = Opcode2Index[Rhs.first];
386e6d15924SDimitry Andric         const std::pair<APInt, APInt> &LhsMasks = OpcodeMasks[LhsIdx];
387e6d15924SDimitry Andric         const std::pair<APInt, APInt> &RhsMasks = OpcodeMasks[RhsIdx];
388d8e91e46SDimitry Andric 
389b1c73532SDimitry Andric         auto PopulationCountAndLeftBit =
390b1c73532SDimitry Andric             [](const APInt &Other) -> std::pair<int, int> {
391ac9a064cSDimitry Andric           return std::pair<int, int>(Other.popcount(), -Other.countl_zero());
392e6d15924SDimitry Andric         };
393b1c73532SDimitry Andric         auto lhsmask_first = PopulationCountAndLeftBit(LhsMasks.first);
394b1c73532SDimitry Andric         auto rhsmask_first = PopulationCountAndLeftBit(RhsMasks.first);
395b1c73532SDimitry Andric         if (lhsmask_first != rhsmask_first)
396b1c73532SDimitry Andric           return lhsmask_first < rhsmask_first;
397d8e91e46SDimitry Andric 
398b1c73532SDimitry Andric         auto lhsmask_second = PopulationCountAndLeftBit(LhsMasks.second);
399b1c73532SDimitry Andric         auto rhsmask_second = PopulationCountAndLeftBit(RhsMasks.second);
400b1c73532SDimitry Andric         if (lhsmask_second != rhsmask_second)
401b1c73532SDimitry Andric           return lhsmask_second < rhsmask_second;
402d8e91e46SDimitry Andric 
403d8e91e46SDimitry Andric         return LhsIdx < RhsIdx;
404d8e91e46SDimitry Andric       });
405d8e91e46SDimitry Andric 
406d8e91e46SDimitry Andric   // Now construct opcode groups. Groups are used by the SubtargetEmitter when
407d8e91e46SDimitry Andric   // expanding the body of a STIPredicate function. In particular, each opcode
408d8e91e46SDimitry Andric   // group is expanded into a sequence of labels in a switch statement.
409d8e91e46SDimitry Andric   // It identifies opcodes for which different processors define same predicates
410d8e91e46SDimitry Andric   // and same opcode masks.
411d8e91e46SDimitry Andric   for (OpcodeMapPair &Info : OpcodeMappings)
412d8e91e46SDimitry Andric     Fn.addOpcode(Info.first, std::move(Info.second));
413d8e91e46SDimitry Andric }
414d8e91e46SDimitry Andric 
collectSTIPredicates()415d8e91e46SDimitry Andric void CodeGenSchedModels::collectSTIPredicates() {
416d8e91e46SDimitry Andric   // Map STIPredicateDecl records to elements of vector
417d8e91e46SDimitry Andric   // CodeGenSchedModels::STIPredicates.
418d8e91e46SDimitry Andric   DenseMap<const Record *, unsigned> Decl2Index;
419d8e91e46SDimitry Andric 
420d8e91e46SDimitry Andric   RecVec RV = Records.getAllDerivedDefinitions("STIPredicate");
421d8e91e46SDimitry Andric   for (const Record *R : RV) {
422d8e91e46SDimitry Andric     const Record *Decl = R->getValueAsDef("Declaration");
423d8e91e46SDimitry Andric 
424d8e91e46SDimitry Andric     const auto It = Decl2Index.find(Decl);
425d8e91e46SDimitry Andric     if (It == Decl2Index.end()) {
426d8e91e46SDimitry Andric       Decl2Index[Decl] = STIPredicates.size();
427d8e91e46SDimitry Andric       STIPredicateFunction Predicate(Decl);
428d8e91e46SDimitry Andric       Predicate.addDefinition(R);
429d8e91e46SDimitry Andric       STIPredicates.emplace_back(std::move(Predicate));
430d8e91e46SDimitry Andric       continue;
431d8e91e46SDimitry Andric     }
432d8e91e46SDimitry Andric 
433d8e91e46SDimitry Andric     STIPredicateFunction &PreviousDef = STIPredicates[It->second];
434d8e91e46SDimitry Andric     PreviousDef.addDefinition(R);
435d8e91e46SDimitry Andric   }
436d8e91e46SDimitry Andric 
437d8e91e46SDimitry Andric   for (STIPredicateFunction &Fn : STIPredicates)
438d8e91e46SDimitry Andric     processSTIPredicate(Fn, ProcModelMap);
439d8e91e46SDimitry Andric }
440d8e91e46SDimitry Andric 
addPredicateForProcModel(const llvm::APInt & CpuMask,const llvm::APInt & OperandMask,const Record * Predicate)441d8e91e46SDimitry Andric void OpcodeInfo::addPredicateForProcModel(const llvm::APInt &CpuMask,
442d8e91e46SDimitry Andric                                           const llvm::APInt &OperandMask,
443d8e91e46SDimitry Andric                                           const Record *Predicate) {
444d8e91e46SDimitry Andric   auto It = llvm::find_if(
445d8e91e46SDimitry Andric       Predicates, [&OperandMask, &Predicate](const PredicateInfo &P) {
446d8e91e46SDimitry Andric         return P.Predicate == Predicate && P.OperandMask == OperandMask;
447d8e91e46SDimitry Andric       });
448d8e91e46SDimitry Andric   if (It == Predicates.end()) {
449d8e91e46SDimitry Andric     Predicates.emplace_back(CpuMask, OperandMask, Predicate);
450d8e91e46SDimitry Andric     return;
451d8e91e46SDimitry Andric   }
452d8e91e46SDimitry Andric   It->ProcModelMask |= CpuMask;
453d8e91e46SDimitry Andric }
454d8e91e46SDimitry Andric 
checkMCInstPredicates() const455d8e91e46SDimitry Andric void CodeGenSchedModels::checkMCInstPredicates() const {
456d8e91e46SDimitry Andric   RecVec MCPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
457d8e91e46SDimitry Andric   if (MCPredicates.empty())
458d8e91e46SDimitry Andric     return;
459d8e91e46SDimitry Andric 
460d8e91e46SDimitry Andric   // A target cannot have multiple TIIPredicate definitions with a same name.
461d8e91e46SDimitry Andric   llvm::StringMap<const Record *> TIIPredicates(MCPredicates.size());
462d8e91e46SDimitry Andric   for (const Record *TIIPred : MCPredicates) {
463d8e91e46SDimitry Andric     StringRef Name = TIIPred->getValueAsString("FunctionName");
464d8e91e46SDimitry Andric     StringMap<const Record *>::const_iterator It = TIIPredicates.find(Name);
465d8e91e46SDimitry Andric     if (It == TIIPredicates.end()) {
466d8e91e46SDimitry Andric       TIIPredicates[Name] = TIIPred;
467d8e91e46SDimitry Andric       continue;
468d8e91e46SDimitry Andric     }
469d8e91e46SDimitry Andric 
470d8e91e46SDimitry Andric     PrintError(TIIPred->getLoc(),
471d8e91e46SDimitry Andric                "TIIPredicate " + Name + " is multiply defined.");
472b60736ecSDimitry Andric     PrintFatalNote(It->second->getLoc(),
473d8e91e46SDimitry Andric                    " Previous definition of " + Name + " was here.");
474d8e91e46SDimitry Andric   }
475d8e91e46SDimitry Andric }
476d8e91e46SDimitry Andric 
collectRetireControlUnits()477eb11fae6SDimitry Andric void CodeGenSchedModels::collectRetireControlUnits() {
478eb11fae6SDimitry Andric   RecVec Units = Records.getAllDerivedDefinitions("RetireControlUnit");
479eb11fae6SDimitry Andric 
480eb11fae6SDimitry Andric   for (Record *RCU : Units) {
481eb11fae6SDimitry Andric     CodeGenProcModel &PM = getProcModel(RCU->getValueAsDef("SchedModel"));
482eb11fae6SDimitry Andric     if (PM.RetireControlUnit) {
483eb11fae6SDimitry Andric       PrintError(RCU->getLoc(),
484eb11fae6SDimitry Andric                  "Expected a single RetireControlUnit definition");
485eb11fae6SDimitry Andric       PrintNote(PM.RetireControlUnit->getLoc(),
486eb11fae6SDimitry Andric                 "Previous definition of RetireControlUnit was here");
487eb11fae6SDimitry Andric     }
488eb11fae6SDimitry Andric     PM.RetireControlUnit = RCU;
489eb11fae6SDimitry Andric   }
490eb11fae6SDimitry Andric }
491eb11fae6SDimitry Andric 
collectLoadStoreQueueInfo()492d8e91e46SDimitry Andric void CodeGenSchedModels::collectLoadStoreQueueInfo() {
493d8e91e46SDimitry Andric   RecVec Queues = Records.getAllDerivedDefinitions("MemoryQueue");
494d8e91e46SDimitry Andric 
495d8e91e46SDimitry Andric   for (Record *Queue : Queues) {
496d8e91e46SDimitry Andric     CodeGenProcModel &PM = getProcModel(Queue->getValueAsDef("SchedModel"));
497d8e91e46SDimitry Andric     if (Queue->isSubClassOf("LoadQueue")) {
498d8e91e46SDimitry Andric       if (PM.LoadQueue) {
499ac9a064cSDimitry Andric         PrintError(Queue->getLoc(), "Expected a single LoadQueue definition");
500d8e91e46SDimitry Andric         PrintNote(PM.LoadQueue->getLoc(),
501d8e91e46SDimitry Andric                   "Previous definition of LoadQueue was here");
502d8e91e46SDimitry Andric       }
503d8e91e46SDimitry Andric 
504d8e91e46SDimitry Andric       PM.LoadQueue = Queue;
505d8e91e46SDimitry Andric     }
506d8e91e46SDimitry Andric 
507d8e91e46SDimitry Andric     if (Queue->isSubClassOf("StoreQueue")) {
508d8e91e46SDimitry Andric       if (PM.StoreQueue) {
509ac9a064cSDimitry Andric         PrintError(Queue->getLoc(), "Expected a single StoreQueue definition");
510e3b55780SDimitry Andric         PrintNote(PM.StoreQueue->getLoc(),
511d8e91e46SDimitry Andric                   "Previous definition of StoreQueue was here");
512d8e91e46SDimitry Andric       }
513d8e91e46SDimitry Andric 
514d8e91e46SDimitry Andric       PM.StoreQueue = Queue;
515d8e91e46SDimitry Andric     }
516d8e91e46SDimitry Andric   }
517d8e91e46SDimitry Andric }
518d8e91e46SDimitry Andric 
519eb11fae6SDimitry Andric /// Collect optional processor information.
collectOptionalProcessorInfo()520eb11fae6SDimitry Andric void CodeGenSchedModels::collectOptionalProcessorInfo() {
521eb11fae6SDimitry Andric   // Find register file definitions for each processor.
522eb11fae6SDimitry Andric   collectRegisterFiles();
523eb11fae6SDimitry Andric 
524eb11fae6SDimitry Andric   // Collect processor RetireControlUnit descriptors if available.
525eb11fae6SDimitry Andric   collectRetireControlUnits();
526eb11fae6SDimitry Andric 
527d8e91e46SDimitry Andric   // Collect information about load/store queues.
528d8e91e46SDimitry Andric   collectLoadStoreQueueInfo();
529eb11fae6SDimitry Andric 
53001095a5dSDimitry Andric   checkCompleteness();
53158b69754SDimitry Andric }
53258b69754SDimitry Andric 
533522600a2SDimitry Andric /// Gather all processor models.
collectProcModels()534522600a2SDimitry Andric void CodeGenSchedModels::collectProcModels() {
535522600a2SDimitry Andric   RecVec ProcRecords = Records.getAllDerivedDefinitions("Processor");
536d8e91e46SDimitry Andric   llvm::sort(ProcRecords, LessRecordFieldName());
53758b69754SDimitry Andric 
538ecbca9f5SDimitry Andric   // Check for duplicated names.
539ecbca9f5SDimitry Andric   auto I = std::adjacent_find(ProcRecords.begin(), ProcRecords.end(),
540ecbca9f5SDimitry Andric                               [](const Record *Rec1, const Record *Rec2) {
541ac9a064cSDimitry Andric                                 return Rec1->getValueAsString("Name") ==
542ac9a064cSDimitry Andric                                        Rec2->getValueAsString("Name");
543ecbca9f5SDimitry Andric                               });
544ecbca9f5SDimitry Andric   if (I != ProcRecords.end())
545ecbca9f5SDimitry Andric     PrintFatalError((*I)->getLoc(), "Duplicate processor name " +
546ecbca9f5SDimitry Andric                                         (*I)->getValueAsString("Name"));
547ecbca9f5SDimitry Andric 
548522600a2SDimitry Andric   // Reserve space because we can. Reallocation would be ok.
549522600a2SDimitry Andric   ProcModels.reserve(ProcRecords.size() + 1);
550522600a2SDimitry Andric 
551522600a2SDimitry Andric   // Use idx=0 for NoModel/NoItineraries.
552522600a2SDimitry Andric   Record *NoModelDef = Records.getDef("NoSchedModel");
553522600a2SDimitry Andric   Record *NoItinsDef = Records.getDef("NoItineraries");
55485d8b2bbSDimitry Andric   ProcModels.emplace_back(0, "NoSchedModel", NoModelDef, NoItinsDef);
555522600a2SDimitry Andric   ProcModelMap[NoModelDef] = 0;
556522600a2SDimitry Andric 
557522600a2SDimitry Andric   // For each processor, find a unique machine model.
558eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "+++ PROCESSOR MODELs (addProcModel) +++\n");
559044eb2f6SDimitry Andric   for (Record *ProcRecord : ProcRecords)
560044eb2f6SDimitry Andric     addProcModel(ProcRecord);
561522600a2SDimitry Andric }
562522600a2SDimitry Andric 
563522600a2SDimitry Andric /// Get a unique processor model based on the defined MachineModel and
564522600a2SDimitry Andric /// ProcessorItineraries.
addProcModel(Record * ProcDef)565522600a2SDimitry Andric void CodeGenSchedModels::addProcModel(Record *ProcDef) {
566522600a2SDimitry Andric   Record *ModelKey = getModelOrItinDef(ProcDef);
567ac9a064cSDimitry Andric   if (!ProcModelMap.insert(std::pair(ModelKey, ProcModels.size())).second)
568522600a2SDimitry Andric     return;
569522600a2SDimitry Andric 
570cfca06d7SDimitry Andric   std::string Name = std::string(ModelKey->getName());
571522600a2SDimitry Andric   if (ModelKey->isSubClassOf("SchedMachineModel")) {
572522600a2SDimitry Andric     Record *ItinsDef = ModelKey->getValueAsDef("Itineraries");
57385d8b2bbSDimitry Andric     ProcModels.emplace_back(ProcModels.size(), Name, ModelKey, ItinsDef);
574ac9a064cSDimitry Andric   } else {
575522600a2SDimitry Andric     // An itinerary is defined without a machine model. Infer a new model.
576522600a2SDimitry Andric     if (!ModelKey->getValueAsListOfDefs("IID").empty())
577522600a2SDimitry Andric       Name = Name + "Model";
57885d8b2bbSDimitry Andric     ProcModels.emplace_back(ProcModels.size(), Name,
57985d8b2bbSDimitry Andric                             ProcDef->getValueAsDef("SchedModel"), ModelKey);
580522600a2SDimitry Andric   }
581eb11fae6SDimitry Andric   LLVM_DEBUG(ProcModels.back().dump());
582522600a2SDimitry Andric }
583522600a2SDimitry Andric 
584522600a2SDimitry Andric // Recursively find all reachable SchedReadWrite records.
scanSchedRW(Record * RWDef,RecVec & RWDefs,SmallPtrSet<Record *,16> & RWSet)585522600a2SDimitry Andric static void scanSchedRW(Record *RWDef, RecVec &RWDefs,
586522600a2SDimitry Andric                         SmallPtrSet<Record *, 16> &RWSet) {
58767c32a98SDimitry Andric   if (!RWSet.insert(RWDef).second)
588522600a2SDimitry Andric     return;
589522600a2SDimitry Andric   RWDefs.push_back(RWDef);
590044eb2f6SDimitry Andric   // Reads don't currently have sequence records, but it can be added later.
591522600a2SDimitry Andric   if (RWDef->isSubClassOf("WriteSequence")) {
592522600a2SDimitry Andric     RecVec Seq = RWDef->getValueAsListOfDefs("Writes");
593044eb2f6SDimitry Andric     for (Record *WSRec : Seq)
594044eb2f6SDimitry Andric       scanSchedRW(WSRec, RWDefs, RWSet);
595ac9a064cSDimitry Andric   } else if (RWDef->isSubClassOf("SchedVariant")) {
596522600a2SDimitry Andric     // Visit each variant (guarded by a different predicate).
597522600a2SDimitry Andric     RecVec Vars = RWDef->getValueAsListOfDefs("Variants");
598044eb2f6SDimitry Andric     for (Record *Variant : Vars) {
599522600a2SDimitry Andric       // Visit each RW in the sequence selected by the current variant.
600044eb2f6SDimitry Andric       RecVec Selected = Variant->getValueAsListOfDefs("Selected");
601044eb2f6SDimitry Andric       for (Record *SelDef : Selected)
602044eb2f6SDimitry Andric         scanSchedRW(SelDef, RWDefs, RWSet);
603522600a2SDimitry Andric     }
604522600a2SDimitry Andric   }
605522600a2SDimitry Andric }
606522600a2SDimitry Andric 
607522600a2SDimitry Andric // Collect and sort all SchedReadWrites reachable via tablegen records.
608522600a2SDimitry Andric // More may be inferred later when inferring new SchedClasses from variants.
collectSchedRW()609522600a2SDimitry Andric void CodeGenSchedModels::collectSchedRW() {
610522600a2SDimitry Andric   // Reserve idx=0 for invalid writes/reads.
611522600a2SDimitry Andric   SchedWrites.resize(1);
612522600a2SDimitry Andric   SchedReads.resize(1);
613522600a2SDimitry Andric 
614522600a2SDimitry Andric   SmallPtrSet<Record *, 16> RWSet;
615522600a2SDimitry Andric 
616522600a2SDimitry Andric   // Find all SchedReadWrites referenced by instruction defs.
617522600a2SDimitry Andric   RecVec SWDefs, SRDefs;
61801095a5dSDimitry Andric   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
61967c32a98SDimitry Andric     Record *SchedDef = Inst->TheDef;
6204a16efa3SDimitry Andric     if (SchedDef->isValueUnset("SchedRW"))
621522600a2SDimitry Andric       continue;
622522600a2SDimitry Andric     RecVec RWs = SchedDef->getValueAsListOfDefs("SchedRW");
623044eb2f6SDimitry Andric     for (Record *RW : RWs) {
624044eb2f6SDimitry Andric       if (RW->isSubClassOf("SchedWrite"))
625044eb2f6SDimitry Andric         scanSchedRW(RW, SWDefs, RWSet);
626522600a2SDimitry Andric       else {
627044eb2f6SDimitry Andric         assert(RW->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
628044eb2f6SDimitry Andric         scanSchedRW(RW, SRDefs, RWSet);
629522600a2SDimitry Andric       }
630522600a2SDimitry Andric     }
631522600a2SDimitry Andric   }
632522600a2SDimitry Andric   // Find all ReadWrites referenced by InstRW.
633522600a2SDimitry Andric   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
634044eb2f6SDimitry Andric   for (Record *InstRWDef : InstRWDefs) {
635522600a2SDimitry Andric     // For all OperandReadWrites.
636044eb2f6SDimitry Andric     RecVec RWDefs = InstRWDef->getValueAsListOfDefs("OperandReadWrites");
637044eb2f6SDimitry Andric     for (Record *RWDef : RWDefs) {
638044eb2f6SDimitry Andric       if (RWDef->isSubClassOf("SchedWrite"))
639044eb2f6SDimitry Andric         scanSchedRW(RWDef, SWDefs, RWSet);
640522600a2SDimitry Andric       else {
641044eb2f6SDimitry Andric         assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
642044eb2f6SDimitry Andric         scanSchedRW(RWDef, SRDefs, RWSet);
643522600a2SDimitry Andric       }
644522600a2SDimitry Andric     }
645522600a2SDimitry Andric   }
646522600a2SDimitry Andric   // Find all ReadWrites referenced by ItinRW.
647522600a2SDimitry Andric   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
648044eb2f6SDimitry Andric   for (Record *ItinRWDef : ItinRWDefs) {
649522600a2SDimitry Andric     // For all OperandReadWrites.
650044eb2f6SDimitry Andric     RecVec RWDefs = ItinRWDef->getValueAsListOfDefs("OperandReadWrites");
651044eb2f6SDimitry Andric     for (Record *RWDef : RWDefs) {
652044eb2f6SDimitry Andric       if (RWDef->isSubClassOf("SchedWrite"))
653044eb2f6SDimitry Andric         scanSchedRW(RWDef, SWDefs, RWSet);
654522600a2SDimitry Andric       else {
655044eb2f6SDimitry Andric         assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
656044eb2f6SDimitry Andric         scanSchedRW(RWDef, SRDefs, RWSet);
657522600a2SDimitry Andric       }
658522600a2SDimitry Andric     }
659522600a2SDimitry Andric   }
660522600a2SDimitry Andric   // Find all ReadWrites referenced by SchedAlias. AliasDefs needs to be sorted
661522600a2SDimitry Andric   // for the loop below that initializes Alias vectors.
662522600a2SDimitry Andric   RecVec AliasDefs = Records.getAllDerivedDefinitions("SchedAlias");
663d8e91e46SDimitry Andric   llvm::sort(AliasDefs, LessRecord());
664044eb2f6SDimitry Andric   for (Record *ADef : AliasDefs) {
665044eb2f6SDimitry Andric     Record *MatchDef = ADef->getValueAsDef("MatchRW");
666044eb2f6SDimitry Andric     Record *AliasDef = ADef->getValueAsDef("AliasRW");
667522600a2SDimitry Andric     if (MatchDef->isSubClassOf("SchedWrite")) {
668522600a2SDimitry Andric       if (!AliasDef->isSubClassOf("SchedWrite"))
669044eb2f6SDimitry Andric         PrintFatalError(ADef->getLoc(), "SchedWrite Alias must be SchedWrite");
670522600a2SDimitry Andric       scanSchedRW(AliasDef, SWDefs, RWSet);
671ac9a064cSDimitry Andric     } else {
672522600a2SDimitry Andric       assert(MatchDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
673522600a2SDimitry Andric       if (!AliasDef->isSubClassOf("SchedRead"))
674044eb2f6SDimitry Andric         PrintFatalError(ADef->getLoc(), "SchedRead Alias must be SchedRead");
675522600a2SDimitry Andric       scanSchedRW(AliasDef, SRDefs, RWSet);
676522600a2SDimitry Andric     }
677522600a2SDimitry Andric   }
678522600a2SDimitry Andric   // Sort and add the SchedReadWrites directly referenced by instructions or
679522600a2SDimitry Andric   // itinerary resources. Index reads and writes in separate domains.
680d8e91e46SDimitry Andric   llvm::sort(SWDefs, LessRecord());
681044eb2f6SDimitry Andric   for (Record *SWDef : SWDefs) {
682044eb2f6SDimitry Andric     assert(!getSchedRWIdx(SWDef, /*IsRead=*/false) && "duplicate SchedWrite");
683044eb2f6SDimitry Andric     SchedWrites.emplace_back(SchedWrites.size(), SWDef);
684522600a2SDimitry Andric   }
685d8e91e46SDimitry Andric   llvm::sort(SRDefs, LessRecord());
686044eb2f6SDimitry Andric   for (Record *SRDef : SRDefs) {
687044eb2f6SDimitry Andric     assert(!getSchedRWIdx(SRDef, /*IsRead-*/ true) && "duplicate SchedWrite");
688044eb2f6SDimitry Andric     SchedReads.emplace_back(SchedReads.size(), SRDef);
689522600a2SDimitry Andric   }
690522600a2SDimitry Andric   // Initialize WriteSequence vectors.
691044eb2f6SDimitry Andric   for (CodeGenSchedRW &CGRW : SchedWrites) {
692044eb2f6SDimitry Andric     if (!CGRW.IsSequence)
693522600a2SDimitry Andric       continue;
694044eb2f6SDimitry Andric     findRWs(CGRW.TheDef->getValueAsListOfDefs("Writes"), CGRW.Sequence,
695522600a2SDimitry Andric             /*IsRead=*/false);
696522600a2SDimitry Andric   }
697522600a2SDimitry Andric   // Initialize Aliases vectors.
698044eb2f6SDimitry Andric   for (Record *ADef : AliasDefs) {
699044eb2f6SDimitry Andric     Record *AliasDef = ADef->getValueAsDef("AliasRW");
700522600a2SDimitry Andric     getSchedRW(AliasDef).IsAlias = true;
701044eb2f6SDimitry Andric     Record *MatchDef = ADef->getValueAsDef("MatchRW");
702522600a2SDimitry Andric     CodeGenSchedRW &RW = getSchedRW(MatchDef);
703522600a2SDimitry Andric     if (RW.IsAlias)
704044eb2f6SDimitry Andric       PrintFatalError(ADef->getLoc(), "Cannot Alias an Alias");
705044eb2f6SDimitry Andric     RW.Aliases.push_back(ADef);
706522600a2SDimitry Andric   }
707eb11fae6SDimitry Andric   LLVM_DEBUG(
7089df3605dSDimitry Andric       dbgs() << "\n+++ SCHED READS and WRITES (collectSchedRW) +++\n";
709522600a2SDimitry Andric       for (unsigned WIdx = 0, WEnd = SchedWrites.size(); WIdx != WEnd; ++WIdx) {
710522600a2SDimitry Andric         dbgs() << WIdx << ": ";
711522600a2SDimitry Andric         SchedWrites[WIdx].dump();
712522600a2SDimitry Andric         dbgs() << '\n';
713eb11fae6SDimitry Andric       } for (unsigned RIdx = 0, REnd = SchedReads.size(); RIdx != REnd;
714eb11fae6SDimitry Andric              ++RIdx) {
715522600a2SDimitry Andric         dbgs() << RIdx << ": ";
716522600a2SDimitry Andric         SchedReads[RIdx].dump();
717522600a2SDimitry Andric         dbgs() << '\n';
718eb11fae6SDimitry Andric       } RecVec RWDefs = Records.getAllDerivedDefinitions("SchedReadWrite");
719eb11fae6SDimitry Andric       for (Record *RWDef
720eb11fae6SDimitry Andric            : RWDefs) {
721044eb2f6SDimitry Andric         if (!getSchedRWIdx(RWDef, RWDef->isSubClassOf("SchedRead"))) {
722eb11fae6SDimitry Andric           StringRef Name = RWDef->getName();
723522600a2SDimitry Andric           if (Name != "NoWrite" && Name != "ReadDefault")
724eb11fae6SDimitry Andric             dbgs() << "Unused SchedReadWrite " << Name << '\n';
725522600a2SDimitry Andric         }
726522600a2SDimitry Andric       });
727522600a2SDimitry Andric }
728522600a2SDimitry Andric 
729522600a2SDimitry Andric /// Compute a SchedWrite name from a sequence of writes.
genRWName(ArrayRef<unsigned> Seq,bool IsRead)730dd58ef01SDimitry Andric std::string CodeGenSchedModels::genRWName(ArrayRef<unsigned> Seq, bool IsRead) {
731522600a2SDimitry Andric   std::string Name("(");
732344a3780SDimitry Andric   ListSeparator LS("_");
733344a3780SDimitry Andric   for (unsigned I : Seq) {
734344a3780SDimitry Andric     Name += LS;
735344a3780SDimitry Andric     Name += getSchedRW(I, IsRead).Name;
736522600a2SDimitry Andric   }
737522600a2SDimitry Andric   Name += ')';
738522600a2SDimitry Andric   return Name;
739522600a2SDimitry Andric }
740522600a2SDimitry Andric 
getSchedRWIdx(const Record * Def,bool IsRead) const741eb11fae6SDimitry Andric unsigned CodeGenSchedModels::getSchedRWIdx(const Record *Def,
742eb11fae6SDimitry Andric                                            bool IsRead) const {
743522600a2SDimitry Andric   const std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
744eb11fae6SDimitry Andric   const auto I = find_if(
745eb11fae6SDimitry Andric       RWVec, [Def](const CodeGenSchedRW &RW) { return RW.TheDef == Def; });
746eb11fae6SDimitry Andric   return I == RWVec.end() ? 0 : std::distance(RWVec.begin(), I);
747522600a2SDimitry Andric }
748522600a2SDimitry Andric 
splitSchedReadWrites(const RecVec & RWDefs,RecVec & WriteDefs,RecVec & ReadDefs)749ac9a064cSDimitry Andric static void splitSchedReadWrites(const RecVec &RWDefs, RecVec &WriteDefs,
750ac9a064cSDimitry Andric                                  RecVec &ReadDefs) {
751044eb2f6SDimitry Andric   for (Record *RWDef : RWDefs) {
752044eb2f6SDimitry Andric     if (RWDef->isSubClassOf("SchedWrite"))
753044eb2f6SDimitry Andric       WriteDefs.push_back(RWDef);
754522600a2SDimitry Andric     else {
755044eb2f6SDimitry Andric       assert(RWDef->isSubClassOf("SchedRead") && "unknown SchedReadWrite");
756044eb2f6SDimitry Andric       ReadDefs.push_back(RWDef);
757522600a2SDimitry Andric     }
758522600a2SDimitry Andric   }
759522600a2SDimitry Andric }
760b915e9e0SDimitry Andric 
761522600a2SDimitry Andric // Split the SchedReadWrites defs and call findRWs for each list.
findRWs(const RecVec & RWDefs,IdxVec & Writes,IdxVec & Reads) const762ac9a064cSDimitry Andric void CodeGenSchedModels::findRWs(const RecVec &RWDefs, IdxVec &Writes,
763ac9a064cSDimitry Andric                                  IdxVec &Reads) const {
764522600a2SDimitry Andric   RecVec WriteDefs;
765522600a2SDimitry Andric   RecVec ReadDefs;
766522600a2SDimitry Andric   splitSchedReadWrites(RWDefs, WriteDefs, ReadDefs);
767522600a2SDimitry Andric   findRWs(WriteDefs, Writes, false);
768522600a2SDimitry Andric   findRWs(ReadDefs, Reads, true);
769522600a2SDimitry Andric }
770522600a2SDimitry Andric 
771522600a2SDimitry Andric // Call getSchedRWIdx for all elements in a sequence of SchedRW defs.
findRWs(const RecVec & RWDefs,IdxVec & RWs,bool IsRead) const772522600a2SDimitry Andric void CodeGenSchedModels::findRWs(const RecVec &RWDefs, IdxVec &RWs,
773522600a2SDimitry Andric                                  bool IsRead) const {
774044eb2f6SDimitry Andric   for (Record *RWDef : RWDefs) {
775044eb2f6SDimitry Andric     unsigned Idx = getSchedRWIdx(RWDef, IsRead);
776522600a2SDimitry Andric     assert(Idx && "failed to collect SchedReadWrite");
777522600a2SDimitry Andric     RWs.push_back(Idx);
778522600a2SDimitry Andric   }
779522600a2SDimitry Andric }
780522600a2SDimitry Andric 
expandRWSequence(unsigned RWIdx,IdxVec & RWSeq,bool IsRead) const781522600a2SDimitry Andric void CodeGenSchedModels::expandRWSequence(unsigned RWIdx, IdxVec &RWSeq,
782522600a2SDimitry Andric                                           bool IsRead) const {
783522600a2SDimitry Andric   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
784522600a2SDimitry Andric   if (!SchedRW.IsSequence) {
785522600a2SDimitry Andric     RWSeq.push_back(RWIdx);
786522600a2SDimitry Andric     return;
787522600a2SDimitry Andric   }
788ac9a064cSDimitry Andric   int Repeat = SchedRW.TheDef ? SchedRW.TheDef->getValueAsInt("Repeat") : 1;
789522600a2SDimitry Andric   for (int i = 0; i < Repeat; ++i) {
790044eb2f6SDimitry Andric     for (unsigned I : SchedRW.Sequence) {
791044eb2f6SDimitry Andric       expandRWSequence(I, RWSeq, IsRead);
792522600a2SDimitry Andric     }
793522600a2SDimitry Andric   }
794522600a2SDimitry Andric }
795522600a2SDimitry Andric 
796522600a2SDimitry Andric // Expand a SchedWrite as a sequence following any aliases that coincide with
797522600a2SDimitry Andric // the given processor model.
expandRWSeqForProc(unsigned RWIdx,IdxVec & RWSeq,bool IsRead,const CodeGenProcModel & ProcModel) const798522600a2SDimitry Andric void CodeGenSchedModels::expandRWSeqForProc(
799522600a2SDimitry Andric     unsigned RWIdx, IdxVec &RWSeq, bool IsRead,
800522600a2SDimitry Andric     const CodeGenProcModel &ProcModel) const {
801522600a2SDimitry Andric 
802522600a2SDimitry Andric   const CodeGenSchedRW &SchedWrite = getSchedRW(RWIdx, IsRead);
8035ca98fd9SDimitry Andric   Record *AliasDef = nullptr;
804eb11fae6SDimitry Andric   for (const Record *Rec : SchedWrite.Aliases) {
805eb11fae6SDimitry Andric     const CodeGenSchedRW &AliasRW = getSchedRW(Rec->getValueAsDef("AliasRW"));
806eb11fae6SDimitry Andric     if (Rec->getValueInit("SchedModel")->isComplete()) {
807eb11fae6SDimitry Andric       Record *ModelDef = Rec->getValueAsDef("SchedModel");
808522600a2SDimitry Andric       if (&getProcModel(ModelDef) != &ProcModel)
809522600a2SDimitry Andric         continue;
810522600a2SDimitry Andric     }
811522600a2SDimitry Andric     if (AliasDef)
812ac9a064cSDimitry Andric       PrintFatalError(AliasRW.TheDef->getLoc(),
813ac9a064cSDimitry Andric                       "Multiple aliases "
814ac9a064cSDimitry Andric                       "defined for processor " +
815ac9a064cSDimitry Andric                           ProcModel.ModelName +
816522600a2SDimitry Andric                           " Ensure only one SchedAlias exists per RW.");
817522600a2SDimitry Andric     AliasDef = AliasRW.TheDef;
818522600a2SDimitry Andric   }
819522600a2SDimitry Andric   if (AliasDef) {
820ac9a064cSDimitry Andric     expandRWSeqForProc(getSchedRWIdx(AliasDef, IsRead), RWSeq, IsRead,
821ac9a064cSDimitry Andric                        ProcModel);
822522600a2SDimitry Andric     return;
823522600a2SDimitry Andric   }
824522600a2SDimitry Andric   if (!SchedWrite.IsSequence) {
825522600a2SDimitry Andric     RWSeq.push_back(RWIdx);
826522600a2SDimitry Andric     return;
827522600a2SDimitry Andric   }
828522600a2SDimitry Andric   int Repeat =
829522600a2SDimitry Andric       SchedWrite.TheDef ? SchedWrite.TheDef->getValueAsInt("Repeat") : 1;
830eb11fae6SDimitry Andric   for (int I = 0, E = Repeat; I < E; ++I) {
831eb11fae6SDimitry Andric     for (unsigned Idx : SchedWrite.Sequence) {
832eb11fae6SDimitry Andric       expandRWSeqForProc(Idx, RWSeq, IsRead, ProcModel);
833522600a2SDimitry Andric     }
834522600a2SDimitry Andric   }
835522600a2SDimitry Andric }
836522600a2SDimitry Andric 
837522600a2SDimitry Andric // Find the existing SchedWrite that models this sequence of writes.
findRWForSequence(ArrayRef<unsigned> Seq,bool IsRead)838dd58ef01SDimitry Andric unsigned CodeGenSchedModels::findRWForSequence(ArrayRef<unsigned> Seq,
839522600a2SDimitry Andric                                                bool IsRead) {
840522600a2SDimitry Andric   std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
841522600a2SDimitry Andric 
842eb11fae6SDimitry Andric   auto I = find_if(RWVec, [Seq](CodeGenSchedRW &RW) {
843e3b55780SDimitry Andric     return ArrayRef(RW.Sequence) == Seq;
844eb11fae6SDimitry Andric   });
845522600a2SDimitry Andric   // Index zero reserved for invalid RW.
846eb11fae6SDimitry Andric   return I == RWVec.end() ? 0 : std::distance(RWVec.begin(), I);
847522600a2SDimitry Andric }
848522600a2SDimitry Andric 
849522600a2SDimitry Andric /// Add this ReadWrite if it doesn't already exist.
findOrInsertRW(ArrayRef<unsigned> Seq,bool IsRead)850522600a2SDimitry Andric unsigned CodeGenSchedModels::findOrInsertRW(ArrayRef<unsigned> Seq,
851522600a2SDimitry Andric                                             bool IsRead) {
852522600a2SDimitry Andric   assert(!Seq.empty() && "cannot insert empty sequence");
853522600a2SDimitry Andric   if (Seq.size() == 1)
854522600a2SDimitry Andric     return Seq.back();
855522600a2SDimitry Andric 
856522600a2SDimitry Andric   unsigned Idx = findRWForSequence(Seq, IsRead);
857522600a2SDimitry Andric   if (Idx)
858522600a2SDimitry Andric     return Idx;
859522600a2SDimitry Andric 
860eb11fae6SDimitry Andric   std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
861eb11fae6SDimitry Andric   unsigned RWIdx = RWVec.size();
862522600a2SDimitry Andric   CodeGenSchedRW SchedRW(RWIdx, IsRead, Seq, genRWName(Seq, IsRead));
863eb11fae6SDimitry Andric   RWVec.push_back(SchedRW);
864522600a2SDimitry Andric   return RWIdx;
865522600a2SDimitry Andric }
866522600a2SDimitry Andric 
867522600a2SDimitry Andric /// Visit all the instruction definitions for this target to gather and
868522600a2SDimitry Andric /// enumerate the itinerary classes. These are the explicitly specified
869522600a2SDimitry Andric /// SchedClasses. More SchedClasses may be inferred.
collectSchedClasses()870522600a2SDimitry Andric void CodeGenSchedModels::collectSchedClasses() {
871522600a2SDimitry Andric 
872522600a2SDimitry Andric   // NoItinerary is always the first class at Idx=0
873eb11fae6SDimitry Andric   assert(SchedClasses.empty() && "Expected empty sched class");
874ac9a064cSDimitry Andric   SchedClasses.emplace_back(0, "NoInstrModel", Records.getDef("NoItinerary"));
875522600a2SDimitry Andric   SchedClasses.back().ProcIndices.push_back(0);
87658b69754SDimitry Andric 
8774a16efa3SDimitry Andric   // Create a SchedClass for each unique combination of itinerary class and
8784a16efa3SDimitry Andric   // SchedRW list.
87901095a5dSDimitry Andric   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
88067c32a98SDimitry Andric     Record *ItinDef = Inst->TheDef->getValueAsDef("Itinerary");
881522600a2SDimitry Andric     IdxVec Writes, Reads;
88267c32a98SDimitry Andric     if (!Inst->TheDef->isValueUnset("SchedRW"))
88367c32a98SDimitry Andric       findRWs(Inst->TheDef->getValueAsListOfDefs("SchedRW"), Writes, Reads);
8844a16efa3SDimitry Andric 
885522600a2SDimitry Andric     // ProcIdx == 0 indicates the class applies to all processors.
886eb11fae6SDimitry Andric     unsigned SCIdx = addSchedClass(ItinDef, Writes, Reads, /*ProcIndices*/ {0});
88767c32a98SDimitry Andric     InstrClassMap[Inst->TheDef] = SCIdx;
88858b69754SDimitry Andric   }
889522600a2SDimitry Andric   // Create classes for InstRW defs.
890522600a2SDimitry Andric   RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
891d8e91e46SDimitry Andric   llvm::sort(InstRWDefs, LessRecord());
892eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "\n+++ SCHED CLASSES (createInstRWClass) +++\n");
893044eb2f6SDimitry Andric   for (Record *RWDef : InstRWDefs)
894044eb2f6SDimitry Andric     createInstRWClass(RWDef);
89558b69754SDimitry Andric 
896522600a2SDimitry Andric   NumInstrSchedClasses = SchedClasses.size();
89758b69754SDimitry Andric 
898522600a2SDimitry Andric   bool EnableDump = false;
899eb11fae6SDimitry Andric   LLVM_DEBUG(EnableDump = true);
900522600a2SDimitry Andric   if (!EnableDump)
90158b69754SDimitry Andric     return;
9024a16efa3SDimitry Andric 
903eb11fae6SDimitry Andric   LLVM_DEBUG(
904eb11fae6SDimitry Andric       dbgs()
905eb11fae6SDimitry Andric       << "\n+++ ITINERARIES and/or MACHINE MODELS (collectSchedClasses) +++\n");
90601095a5dSDimitry Andric   for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
907f382538dSDimitry Andric     StringRef InstName = Inst->TheDef->getName();
908eb11fae6SDimitry Andric     unsigned SCIdx = getSchedClassIdx(*Inst);
9094a16efa3SDimitry Andric     if (!SCIdx) {
910eb11fae6SDimitry Andric       LLVM_DEBUG({
91101095a5dSDimitry Andric         if (!Inst->hasNoSchedulingInfo)
91267c32a98SDimitry Andric           dbgs() << "No machine model for " << Inst->TheDef->getName() << '\n';
913eb11fae6SDimitry Andric       });
9144a16efa3SDimitry Andric       continue;
9154a16efa3SDimitry Andric     }
9164a16efa3SDimitry Andric     CodeGenSchedClass &SC = getSchedClass(SCIdx);
9174a16efa3SDimitry Andric     if (SC.ProcIndices[0] != 0)
918ac9a064cSDimitry Andric       PrintFatalError(Inst->TheDef->getLoc(),
919ac9a064cSDimitry Andric                       "Instruction's sched class "
9204a16efa3SDimitry Andric                       "must not be subtarget specific.");
9214a16efa3SDimitry Andric 
9224a16efa3SDimitry Andric     IdxVec ProcIndices;
9234a16efa3SDimitry Andric     if (SC.ItinClassDef->getName() != "NoItinerary") {
9244a16efa3SDimitry Andric       ProcIndices.push_back(0);
9254a16efa3SDimitry Andric       dbgs() << "Itinerary for " << InstName << ": "
9264a16efa3SDimitry Andric              << SC.ItinClassDef->getName() << '\n';
9274a16efa3SDimitry Andric     }
9284a16efa3SDimitry Andric     if (!SC.Writes.empty()) {
9294a16efa3SDimitry Andric       ProcIndices.push_back(0);
930eb11fae6SDimitry Andric       LLVM_DEBUG({
931522600a2SDimitry Andric         dbgs() << "SchedRW machine model for " << InstName;
932344a3780SDimitry Andric         for (unsigned int Write : SC.Writes)
933344a3780SDimitry Andric           dbgs() << " " << SchedWrites[Write].Name;
934344a3780SDimitry Andric         for (unsigned int Read : SC.Reads)
935344a3780SDimitry Andric           dbgs() << " " << SchedReads[Read].Name;
936522600a2SDimitry Andric         dbgs() << '\n';
937eb11fae6SDimitry Andric       });
938522600a2SDimitry Andric     }
939522600a2SDimitry Andric     const RecVec &RWDefs = SchedClasses[SCIdx].InstRWs;
940044eb2f6SDimitry Andric     for (Record *RWDef : RWDefs) {
941522600a2SDimitry Andric       const CodeGenProcModel &ProcModel =
942044eb2f6SDimitry Andric           getProcModel(RWDef->getValueAsDef("SchedModel"));
9434a16efa3SDimitry Andric       ProcIndices.push_back(ProcModel.Index);
944eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "InstRW on " << ProcModel.ModelName << " for "
945eb11fae6SDimitry Andric                         << InstName);
946522600a2SDimitry Andric       IdxVec Writes;
947522600a2SDimitry Andric       IdxVec Reads;
948ac9a064cSDimitry Andric       findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
949eb11fae6SDimitry Andric       LLVM_DEBUG({
950044eb2f6SDimitry Andric         for (unsigned WIdx : Writes)
951044eb2f6SDimitry Andric           dbgs() << " " << SchedWrites[WIdx].Name;
952044eb2f6SDimitry Andric         for (unsigned RIdx : Reads)
953044eb2f6SDimitry Andric           dbgs() << " " << SchedReads[RIdx].Name;
954522600a2SDimitry Andric         dbgs() << '\n';
955eb11fae6SDimitry Andric       });
956522600a2SDimitry Andric     }
957b915e9e0SDimitry Andric     // If ProcIndices contains zero, the class applies to all processors.
958eb11fae6SDimitry Andric     LLVM_DEBUG({
959b60736ecSDimitry Andric       if (!llvm::is_contained(ProcIndices, 0)) {
960044eb2f6SDimitry Andric         for (const CodeGenProcModel &PM : ProcModels) {
961b60736ecSDimitry Andric           if (!llvm::is_contained(ProcIndices, PM.Index))
96267c32a98SDimitry Andric             dbgs() << "No machine model for " << Inst->TheDef->getName()
963044eb2f6SDimitry Andric                    << " on processor " << PM.ModelName << '\n';
96458b69754SDimitry Andric         }
96558b69754SDimitry Andric       }
966eb11fae6SDimitry Andric     });
967522600a2SDimitry Andric   }
968b915e9e0SDimitry Andric }
969522600a2SDimitry Andric 
970522600a2SDimitry Andric // Get the SchedClass index for an instruction.
971eb11fae6SDimitry Andric unsigned
getSchedClassIdx(const CodeGenInstruction & Inst) const972eb11fae6SDimitry Andric CodeGenSchedModels::getSchedClassIdx(const CodeGenInstruction &Inst) const {
9734a16efa3SDimitry Andric   return InstrClassMap.lookup(Inst.TheDef);
974522600a2SDimitry Andric }
975522600a2SDimitry Andric 
976dd58ef01SDimitry Andric std::string
createSchedClassName(Record * ItinClassDef,ArrayRef<unsigned> OperWrites,ArrayRef<unsigned> OperReads)977dd58ef01SDimitry Andric CodeGenSchedModels::createSchedClassName(Record *ItinClassDef,
978dd58ef01SDimitry Andric                                          ArrayRef<unsigned> OperWrites,
979dd58ef01SDimitry Andric                                          ArrayRef<unsigned> OperReads) {
980522600a2SDimitry Andric 
981522600a2SDimitry Andric   std::string Name;
9824a16efa3SDimitry Andric   if (ItinClassDef && ItinClassDef->getName() != "NoItinerary")
983cfca06d7SDimitry Andric     Name = std::string(ItinClassDef->getName());
984dd58ef01SDimitry Andric   for (unsigned Idx : OperWrites) {
9854a16efa3SDimitry Andric     if (!Name.empty())
986522600a2SDimitry Andric       Name += '_';
987dd58ef01SDimitry Andric     Name += SchedWrites[Idx].Name;
988522600a2SDimitry Andric   }
989dd58ef01SDimitry Andric   for (unsigned Idx : OperReads) {
990522600a2SDimitry Andric     Name += '_';
991dd58ef01SDimitry Andric     Name += SchedReads[Idx].Name;
992522600a2SDimitry Andric   }
993522600a2SDimitry Andric   return Name;
994522600a2SDimitry Andric }
995522600a2SDimitry Andric 
createSchedClassName(const RecVec & InstDefs)996522600a2SDimitry Andric std::string CodeGenSchedModels::createSchedClassName(const RecVec &InstDefs) {
997522600a2SDimitry Andric 
998522600a2SDimitry Andric   std::string Name;
999344a3780SDimitry Andric   ListSeparator LS("_");
1000344a3780SDimitry Andric   for (const Record *InstDef : InstDefs) {
1001344a3780SDimitry Andric     Name += LS;
1002344a3780SDimitry Andric     Name += InstDef->getName();
1003522600a2SDimitry Andric   }
1004522600a2SDimitry Andric   return Name;
1005522600a2SDimitry Andric }
1006522600a2SDimitry Andric 
10074a16efa3SDimitry Andric /// Add an inferred sched class from an itinerary class and per-operand list of
10084a16efa3SDimitry Andric /// SchedWrites and SchedReads. ProcIndices contains the set of IDs of
10094a16efa3SDimitry Andric /// processors that may utilize this class.
addSchedClass(Record * ItinClassDef,ArrayRef<unsigned> OperWrites,ArrayRef<unsigned> OperReads,ArrayRef<unsigned> ProcIndices)10104a16efa3SDimitry Andric unsigned CodeGenSchedModels::addSchedClass(Record *ItinClassDef,
1011dd58ef01SDimitry Andric                                            ArrayRef<unsigned> OperWrites,
1012dd58ef01SDimitry Andric                                            ArrayRef<unsigned> OperReads,
1013dd58ef01SDimitry Andric                                            ArrayRef<unsigned> ProcIndices) {
1014522600a2SDimitry Andric   assert(!ProcIndices.empty() && "expect at least one ProcIdx");
1015522600a2SDimitry Andric 
1016eb11fae6SDimitry Andric   auto IsKeyEqual = [=](const CodeGenSchedClass &SC) {
1017eb11fae6SDimitry Andric     return SC.isKeyEqual(ItinClassDef, OperWrites, OperReads);
1018eb11fae6SDimitry Andric   };
1019eb11fae6SDimitry Andric 
1020eb11fae6SDimitry Andric   auto I = find_if(make_range(schedClassBegin(), schedClassEnd()), IsKeyEqual);
1021eb11fae6SDimitry Andric   unsigned Idx = I == schedClassEnd() ? 0 : std::distance(schedClassBegin(), I);
10224a16efa3SDimitry Andric   if (Idx || SchedClasses[0].isKeyEqual(ItinClassDef, OperWrites, OperReads)) {
1023522600a2SDimitry Andric     IdxVec PI;
1024522600a2SDimitry Andric     std::set_union(SchedClasses[Idx].ProcIndices.begin(),
1025ac9a064cSDimitry Andric                    SchedClasses[Idx].ProcIndices.end(), ProcIndices.begin(),
1026ac9a064cSDimitry Andric                    ProcIndices.end(), std::back_inserter(PI));
1027eb11fae6SDimitry Andric     SchedClasses[Idx].ProcIndices = std::move(PI);
1028522600a2SDimitry Andric     return Idx;
1029522600a2SDimitry Andric   }
1030522600a2SDimitry Andric   Idx = SchedClasses.size();
1031ac9a064cSDimitry Andric   SchedClasses.emplace_back(
1032ac9a064cSDimitry Andric       Idx, createSchedClassName(ItinClassDef, OperWrites, OperReads),
1033eb11fae6SDimitry Andric       ItinClassDef);
1034522600a2SDimitry Andric   CodeGenSchedClass &SC = SchedClasses.back();
1035522600a2SDimitry Andric   SC.Writes = OperWrites;
1036522600a2SDimitry Andric   SC.Reads = OperReads;
1037522600a2SDimitry Andric   SC.ProcIndices = ProcIndices;
1038522600a2SDimitry Andric 
1039522600a2SDimitry Andric   return Idx;
1040522600a2SDimitry Andric }
1041522600a2SDimitry Andric 
1042522600a2SDimitry Andric // Create classes for each set of opcodes that are in the same InstReadWrite
1043522600a2SDimitry Andric // definition across all processors.
createInstRWClass(Record * InstRWDef)1044522600a2SDimitry Andric void CodeGenSchedModels::createInstRWClass(Record *InstRWDef) {
1045522600a2SDimitry Andric   // ClassInstrs will hold an entry for each subset of Instrs in InstRWDef that
1046522600a2SDimitry Andric   // intersects with an existing class via a previous InstRWDef. Instrs that do
1047522600a2SDimitry Andric   // not intersect with an existing class refer back to their former class as
1048522600a2SDimitry Andric   // determined from ItinDef or SchedRW.
1049eb11fae6SDimitry Andric   SmallMapVector<unsigned, SmallVector<Record *, 8>, 4> ClassInstrs;
1050522600a2SDimitry Andric   // Sort Instrs into sets.
1051522600a2SDimitry Andric   const RecVec *InstDefs = Sets.expand(InstRWDef);
1052522600a2SDimitry Andric   if (InstDefs->empty())
1053522600a2SDimitry Andric     PrintFatalError(InstRWDef->getLoc(), "No matching instruction opcodes");
1054522600a2SDimitry Andric 
1055eb11fae6SDimitry Andric   for (Record *InstDef : *InstDefs) {
1056044eb2f6SDimitry Andric     InstClassMapTy::const_iterator Pos = InstrClassMap.find(InstDef);
10574a16efa3SDimitry Andric     if (Pos == InstrClassMap.end())
1058044eb2f6SDimitry Andric       PrintFatalError(InstDef->getLoc(), "No sched class for instruction.");
10594a16efa3SDimitry Andric     unsigned SCIdx = Pos->second;
1060eb11fae6SDimitry Andric     ClassInstrs[SCIdx].push_back(InstDef);
1061522600a2SDimitry Andric   }
1062522600a2SDimitry Andric   // For each set of Instrs, create a new class if necessary, and map or remap
1063522600a2SDimitry Andric   // the Instrs to it.
1064eb11fae6SDimitry Andric   for (auto &Entry : ClassInstrs) {
1065eb11fae6SDimitry Andric     unsigned OldSCIdx = Entry.first;
1066eb11fae6SDimitry Andric     ArrayRef<Record *> InstDefs = Entry.second;
1067522600a2SDimitry Andric     // If the all instrs in the current class are accounted for, then leave
1068522600a2SDimitry Andric     // them mapped to their old class.
1069f8af5cf6SDimitry Andric     if (OldSCIdx) {
1070f8af5cf6SDimitry Andric       const RecVec &RWDefs = SchedClasses[OldSCIdx].InstRWs;
1071f8af5cf6SDimitry Andric       if (!RWDefs.empty()) {
1072f8af5cf6SDimitry Andric         const RecVec *OrigInstDefs = Sets.expand(RWDefs[0]);
1073ac9a064cSDimitry Andric         unsigned OrigNumInstrs = count_if(*OrigInstDefs, [&](Record *OIDef) {
1074eb11fae6SDimitry Andric           return InstrClassMap[OIDef] == OldSCIdx;
1075eb11fae6SDimitry Andric         });
1076f8af5cf6SDimitry Andric         if (OrigNumInstrs == InstDefs.size()) {
1077522600a2SDimitry Andric           assert(SchedClasses[OldSCIdx].ProcIndices[0] == 0 &&
1078522600a2SDimitry Andric                  "expected a generic SchedClass");
1079eb11fae6SDimitry Andric           Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
1080eb11fae6SDimitry Andric           // Make sure we didn't already have a InstRW containing this
1081eb11fae6SDimitry Andric           // instruction on this model.
1082eb11fae6SDimitry Andric           for (Record *RWD : RWDefs) {
1083eb11fae6SDimitry Andric             if (RWD->getValueAsDef("SchedModel") == RWModelDef &&
1084eb11fae6SDimitry Andric                 RWModelDef->getValueAsBit("FullInstRWOverlapCheck")) {
1085cfca06d7SDimitry Andric               assert(!InstDefs.empty()); // Checked at function start.
1086b60736ecSDimitry Andric               PrintError(
1087b60736ecSDimitry Andric                   InstRWDef->getLoc(),
10881d5ae102SDimitry Andric                   "Overlapping InstRW definition for \"" +
1089cfca06d7SDimitry Andric                       InstDefs.front()->getName() +
10901d5ae102SDimitry Andric                       "\" also matches previous \"" +
10911d5ae102SDimitry Andric                       RWD->getValue("Instrs")->getValue()->getAsString() +
10921d5ae102SDimitry Andric                       "\".");
1093b60736ecSDimitry Andric               PrintFatalNote(RWD->getLoc(), "Previous match was here.");
1094eb11fae6SDimitry Andric             }
1095eb11fae6SDimitry Andric           }
1096eb11fae6SDimitry Andric           LLVM_DEBUG(dbgs() << "InstRW: Reuse SC " << OldSCIdx << ":"
1097f8af5cf6SDimitry Andric                             << SchedClasses[OldSCIdx].Name << " on "
1098eb11fae6SDimitry Andric                             << RWModelDef->getName() << "\n");
1099f8af5cf6SDimitry Andric           SchedClasses[OldSCIdx].InstRWs.push_back(InstRWDef);
1100522600a2SDimitry Andric           continue;
1101522600a2SDimitry Andric         }
1102f8af5cf6SDimitry Andric       }
1103f8af5cf6SDimitry Andric     }
1104522600a2SDimitry Andric     unsigned SCIdx = SchedClasses.size();
1105eb11fae6SDimitry Andric     SchedClasses.emplace_back(SCIdx, createSchedClassName(InstDefs), nullptr);
1106522600a2SDimitry Andric     CodeGenSchedClass &SC = SchedClasses.back();
1107eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "InstRW: New SC " << SCIdx << ":" << SC.Name << " on "
1108eb11fae6SDimitry Andric                       << InstRWDef->getValueAsDef("SchedModel")->getName()
1109eb11fae6SDimitry Andric                       << "\n");
1110f8af5cf6SDimitry Andric 
1111522600a2SDimitry Andric     // Preserve ItinDef and Writes/Reads for processors without an InstRW entry.
1112522600a2SDimitry Andric     SC.ItinClassDef = SchedClasses[OldSCIdx].ItinClassDef;
1113522600a2SDimitry Andric     SC.Writes = SchedClasses[OldSCIdx].Writes;
1114522600a2SDimitry Andric     SC.Reads = SchedClasses[OldSCIdx].Reads;
1115522600a2SDimitry Andric     SC.ProcIndices.push_back(0);
1116eb11fae6SDimitry Andric     // If we had an old class, copy it's InstRWs to this new class.
1117eb11fae6SDimitry Andric     if (OldSCIdx) {
1118522600a2SDimitry Andric       Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
1119eb11fae6SDimitry Andric       for (Record *OldRWDef : SchedClasses[OldSCIdx].InstRWs) {
1120eb11fae6SDimitry Andric         if (OldRWDef->getValueAsDef("SchedModel") == RWModelDef) {
1121cfca06d7SDimitry Andric           assert(!InstDefs.empty()); // Checked at function start.
1122b60736ecSDimitry Andric           PrintError(
1123b60736ecSDimitry Andric               InstRWDef->getLoc(),
11241d5ae102SDimitry Andric               "Overlapping InstRW definition for \"" +
1125b60736ecSDimitry Andric                   InstDefs.front()->getName() + "\" also matches previous \"" +
11261d5ae102SDimitry Andric                   OldRWDef->getValue("Instrs")->getValue()->getAsString() +
11271d5ae102SDimitry Andric                   "\".");
1128b60736ecSDimitry Andric           PrintFatalNote(OldRWDef->getLoc(), "Previous match was here.");
1129522600a2SDimitry Andric         }
1130ac9a064cSDimitry Andric         assert(OldRWDef != InstRWDef && "SchedClass has duplicate InstRW def");
1131eb11fae6SDimitry Andric         SC.InstRWs.push_back(OldRWDef);
1132522600a2SDimitry Andric       }
1133eb11fae6SDimitry Andric     }
1134eb11fae6SDimitry Andric     // Map each Instr to this new class.
1135eb11fae6SDimitry Andric     for (Record *InstDef : InstDefs)
1136eb11fae6SDimitry Andric       InstrClassMap[InstDef] = SCIdx;
1137522600a2SDimitry Andric     SC.InstRWs.push_back(InstRWDef);
1138522600a2SDimitry Andric   }
113958b69754SDimitry Andric }
114058b69754SDimitry Andric 
11414a16efa3SDimitry Andric // True if collectProcItins found anything.
hasItineraries() const11424a16efa3SDimitry Andric bool CodeGenSchedModels::hasItineraries() const {
1143ac9a064cSDimitry Andric   for (const CodeGenProcModel &PM :
1144ac9a064cSDimitry Andric        make_range(procModelBegin(), procModelEnd()))
1145044eb2f6SDimitry Andric     if (PM.hasItineraries())
11464a16efa3SDimitry Andric       return true;
11474a16efa3SDimitry Andric   return false;
11484a16efa3SDimitry Andric }
11494a16efa3SDimitry Andric 
115058b69754SDimitry Andric // Gather the processor itineraries.
collectProcItins()1151522600a2SDimitry Andric void CodeGenSchedModels::collectProcItins() {
1152eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "\n+++ PROBLEM ITINERARIES (collectProcItins) +++\n");
115367c32a98SDimitry Andric   for (CodeGenProcModel &ProcModel : ProcModels) {
11544a16efa3SDimitry Andric     if (!ProcModel.hasItineraries())
1155522600a2SDimitry Andric       continue;
115658b69754SDimitry Andric 
11574a16efa3SDimitry Andric     RecVec ItinRecords = ProcModel.ItinsDef->getValueAsListOfDefs("IID");
11584a16efa3SDimitry Andric     assert(!ItinRecords.empty() && "ProcModel.hasItineraries is incorrect");
11594a16efa3SDimitry Andric 
11604a16efa3SDimitry Andric     // Populate ItinDefList with Itinerary records.
11614a16efa3SDimitry Andric     ProcModel.ItinDefList.resize(NumInstrSchedClasses);
116258b69754SDimitry Andric 
116358b69754SDimitry Andric     // Insert each itinerary data record in the correct position within
116458b69754SDimitry Andric     // the processor model's ItinDefList.
1165044eb2f6SDimitry Andric     for (Record *ItinData : ItinRecords) {
1166eb11fae6SDimitry Andric       const Record *ItinDef = ItinData->getValueAsDef("TheClass");
11674a16efa3SDimitry Andric       bool FoundClass = false;
1168eb11fae6SDimitry Andric 
1169eb11fae6SDimitry Andric       for (const CodeGenSchedClass &SC :
1170eb11fae6SDimitry Andric            make_range(schedClassBegin(), schedClassEnd())) {
11714a16efa3SDimitry Andric         // Multiple SchedClasses may share an itinerary. Update all of them.
1172eb11fae6SDimitry Andric         if (SC.ItinClassDef == ItinDef) {
1173eb11fae6SDimitry Andric           ProcModel.ItinDefList[SC.Index] = ItinData;
11744a16efa3SDimitry Andric           FoundClass = true;
117558b69754SDimitry Andric         }
11764a16efa3SDimitry Andric       }
11774a16efa3SDimitry Andric       if (!FoundClass) {
1178eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << ProcModel.ItinsDef->getName()
1179eb11fae6SDimitry Andric                           << " missing class for itinerary "
1180eb11fae6SDimitry Andric                           << ItinDef->getName() << '\n');
11814a16efa3SDimitry Andric       }
118258b69754SDimitry Andric     }
118358b69754SDimitry Andric     // Check for missing itinerary entries.
118458b69754SDimitry Andric     assert(!ProcModel.ItinDefList[0] && "NoItinerary class can't have rec");
1185eb11fae6SDimitry Andric     LLVM_DEBUG(
118658b69754SDimitry Andric         for (unsigned i = 1, N = ProcModel.ItinDefList.size(); i < N; ++i) {
118758b69754SDimitry Andric           if (!ProcModel.ItinDefList[i])
1188522600a2SDimitry Andric             dbgs() << ProcModel.ItinsDef->getName()
1189eb11fae6SDimitry Andric                    << " missing itinerary for class " << SchedClasses[i].Name
1190eb11fae6SDimitry Andric                    << '\n';
1191522600a2SDimitry Andric         });
119258b69754SDimitry Andric   }
1193522600a2SDimitry Andric }
1194522600a2SDimitry Andric 
1195522600a2SDimitry Andric // Gather the read/write types for each itinerary class.
collectProcItinRW()1196522600a2SDimitry Andric void CodeGenSchedModels::collectProcItinRW() {
1197522600a2SDimitry Andric   RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
1198d8e91e46SDimitry Andric   llvm::sort(ItinRWDefs, LessRecord());
1199044eb2f6SDimitry Andric   for (Record *RWDef : ItinRWDefs) {
1200044eb2f6SDimitry Andric     if (!RWDef->getValueInit("SchedModel")->isComplete())
1201044eb2f6SDimitry Andric       PrintFatalError(RWDef->getLoc(), "SchedModel is undefined");
1202044eb2f6SDimitry Andric     Record *ModelDef = RWDef->getValueAsDef("SchedModel");
1203522600a2SDimitry Andric     ProcModelMapTy::const_iterator I = ProcModelMap.find(ModelDef);
1204522600a2SDimitry Andric     if (I == ProcModelMap.end()) {
1205ac9a064cSDimitry Andric       PrintFatalError(RWDef->getLoc(),
1206ac9a064cSDimitry Andric                       "Undefined SchedMachineModel " + ModelDef->getName());
1207522600a2SDimitry Andric     }
1208044eb2f6SDimitry Andric     ProcModels[I->second].ItinRWDefs.push_back(RWDef);
1209522600a2SDimitry Andric   }
1210522600a2SDimitry Andric }
1211522600a2SDimitry Andric 
121201095a5dSDimitry Andric // Gather the unsupported features for processor models.
collectProcUnsupportedFeatures()121301095a5dSDimitry Andric void CodeGenSchedModels::collectProcUnsupportedFeatures() {
1214b60736ecSDimitry Andric   for (CodeGenProcModel &ProcModel : ProcModels)
1215b60736ecSDimitry Andric     append_range(
1216b60736ecSDimitry Andric         ProcModel.UnsupportedFeaturesDefs,
1217b60736ecSDimitry Andric         ProcModel.ModelDef->getValueAsListOfDefs("UnsupportedFeatures"));
121801095a5dSDimitry Andric }
121901095a5dSDimitry Andric 
1220522600a2SDimitry Andric /// Infer new classes from existing classes. In the process, this may create new
1221522600a2SDimitry Andric /// SchedWrites from sequences of existing SchedWrites.
inferSchedClasses()1222522600a2SDimitry Andric void CodeGenSchedModels::inferSchedClasses() {
1223eb11fae6SDimitry Andric   LLVM_DEBUG(
1224eb11fae6SDimitry Andric       dbgs() << "\n+++ INFERRING SCHED CLASSES (inferSchedClasses) +++\n");
1225eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << NumInstrSchedClasses << " instr sched classes.\n");
12264a16efa3SDimitry Andric 
1227522600a2SDimitry Andric   // Visit all existing classes and newly created classes.
1228522600a2SDimitry Andric   for (unsigned Idx = 0; Idx != SchedClasses.size(); ++Idx) {
12294a16efa3SDimitry Andric     assert(SchedClasses[Idx].Index == Idx && "bad SCIdx");
12304a16efa3SDimitry Andric 
1231522600a2SDimitry Andric     if (SchedClasses[Idx].ItinClassDef)
1232522600a2SDimitry Andric       inferFromItinClass(SchedClasses[Idx].ItinClassDef, Idx);
12334a16efa3SDimitry Andric     if (!SchedClasses[Idx].InstRWs.empty())
1234522600a2SDimitry Andric       inferFromInstRWs(Idx);
12354a16efa3SDimitry Andric     if (!SchedClasses[Idx].Writes.empty()) {
1236ac9a064cSDimitry Andric       inferFromRW(SchedClasses[Idx].Writes, SchedClasses[Idx].Reads, Idx,
1237ac9a064cSDimitry Andric                   SchedClasses[Idx].ProcIndices);
1238522600a2SDimitry Andric     }
1239522600a2SDimitry Andric     assert(SchedClasses.size() < (NumInstrSchedClasses * 6) &&
1240522600a2SDimitry Andric            "too many SchedVariants");
1241522600a2SDimitry Andric   }
1242522600a2SDimitry Andric }
1243522600a2SDimitry Andric 
1244522600a2SDimitry Andric /// Infer classes from per-processor itinerary resources.
inferFromItinClass(Record * ItinClassDef,unsigned FromClassIdx)1245522600a2SDimitry Andric void CodeGenSchedModels::inferFromItinClass(Record *ItinClassDef,
1246522600a2SDimitry Andric                                             unsigned FromClassIdx) {
1247522600a2SDimitry Andric   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
1248522600a2SDimitry Andric     const CodeGenProcModel &PM = ProcModels[PIdx];
1249522600a2SDimitry Andric     // For all ItinRW entries.
1250522600a2SDimitry Andric     bool HasMatch = false;
1251eb11fae6SDimitry Andric     for (const Record *Rec : PM.ItinRWDefs) {
1252eb11fae6SDimitry Andric       RecVec Matched = Rec->getValueAsListOfDefs("MatchedItinClasses");
1253b60736ecSDimitry Andric       if (!llvm::is_contained(Matched, ItinClassDef))
1254522600a2SDimitry Andric         continue;
1255522600a2SDimitry Andric       if (HasMatch)
1256ac9a064cSDimitry Andric         PrintFatalError(Rec->getLoc(),
1257ac9a064cSDimitry Andric                         "Duplicate itinerary class " + ItinClassDef->getName() +
1258ac9a064cSDimitry Andric                             " in ItinResources for " + PM.ModelName);
1259522600a2SDimitry Andric       HasMatch = true;
1260522600a2SDimitry Andric       IdxVec Writes, Reads;
1261eb11fae6SDimitry Andric       findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1262eb11fae6SDimitry Andric       inferFromRW(Writes, Reads, FromClassIdx, PIdx);
1263522600a2SDimitry Andric     }
1264522600a2SDimitry Andric   }
1265522600a2SDimitry Andric }
1266522600a2SDimitry Andric 
1267522600a2SDimitry Andric /// Infer classes from per-processor InstReadWrite definitions.
inferFromInstRWs(unsigned SCIdx)1268522600a2SDimitry Andric void CodeGenSchedModels::inferFromInstRWs(unsigned SCIdx) {
1269f8af5cf6SDimitry Andric   for (unsigned I = 0, E = SchedClasses[SCIdx].InstRWs.size(); I != E; ++I) {
1270f8af5cf6SDimitry Andric     assert(SchedClasses[SCIdx].InstRWs.size() == E && "InstrRWs was mutated!");
1271f8af5cf6SDimitry Andric     Record *Rec = SchedClasses[SCIdx].InstRWs[I];
1272f8af5cf6SDimitry Andric     const RecVec *InstDefs = Sets.expand(Rec);
1273522600a2SDimitry Andric     RecIter II = InstDefs->begin(), IE = InstDefs->end();
1274522600a2SDimitry Andric     for (; II != IE; ++II) {
1275522600a2SDimitry Andric       if (InstrClassMap[*II] == SCIdx)
1276522600a2SDimitry Andric         break;
1277522600a2SDimitry Andric     }
1278522600a2SDimitry Andric     // If this class no longer has any instructions mapped to it, it has become
1279522600a2SDimitry Andric     // irrelevant.
1280522600a2SDimitry Andric     if (II == IE)
1281522600a2SDimitry Andric       continue;
1282522600a2SDimitry Andric     IdxVec Writes, Reads;
1283f8af5cf6SDimitry Andric     findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1284f8af5cf6SDimitry Andric     unsigned PIdx = getProcModel(Rec->getValueAsDef("SchedModel")).Index;
1285eb11fae6SDimitry Andric     inferFromRW(Writes, Reads, SCIdx, PIdx); // May mutate SchedClasses.
1286b60736ecSDimitry Andric     SchedClasses[SCIdx].InstRWProcIndices.insert(PIdx);
1287522600a2SDimitry Andric   }
1288522600a2SDimitry Andric }
1289522600a2SDimitry Andric 
1290522600a2SDimitry Andric namespace {
1291b915e9e0SDimitry Andric 
1292522600a2SDimitry Andric // Helper for substituteVariantOperand.
1293522600a2SDimitry Andric struct TransVariant {
1294522600a2SDimitry Andric   Record *VarOrSeqDef;  // Variant or sequence.
1295522600a2SDimitry Andric   unsigned RWIdx;       // Index of this variant or sequence's matched type.
1296522600a2SDimitry Andric   unsigned ProcIdx;     // Processor model index or zero for any.
1297522600a2SDimitry Andric   unsigned TransVecIdx; // Index into PredTransitions::TransVec.
1298522600a2SDimitry Andric 
TransVariant__anon5fa3bdea0b11::TransVariant1299ac9a064cSDimitry Andric   TransVariant(Record *def, unsigned rwi, unsigned pi, unsigned ti)
1300ac9a064cSDimitry Andric       : VarOrSeqDef(def), RWIdx(rwi), ProcIdx(pi), TransVecIdx(ti) {}
1301522600a2SDimitry Andric };
1302522600a2SDimitry Andric 
1303522600a2SDimitry Andric // Associate a predicate with the SchedReadWrite that it guards.
1304522600a2SDimitry Andric // RWIdx is the index of the read/write variant.
1305522600a2SDimitry Andric struct PredCheck {
1306522600a2SDimitry Andric   bool IsRead;
1307522600a2SDimitry Andric   unsigned RWIdx;
1308522600a2SDimitry Andric   Record *Predicate;
1309522600a2SDimitry Andric 
PredCheck__anon5fa3bdea0b11::PredCheck1310ac9a064cSDimitry Andric   PredCheck(bool r, unsigned w, Record *p)
1311ac9a064cSDimitry Andric       : IsRead(r), RWIdx(w), Predicate(p) {}
1312522600a2SDimitry Andric };
1313522600a2SDimitry Andric 
1314522600a2SDimitry Andric // A Predicate transition is a list of RW sequences guarded by a PredTerm.
1315522600a2SDimitry Andric struct PredTransition {
1316522600a2SDimitry Andric   // A predicate term is a conjunction of PredChecks.
1317522600a2SDimitry Andric   SmallVector<PredCheck, 4> PredTerm;
1318522600a2SDimitry Andric   SmallVector<SmallVector<unsigned, 4>, 16> WriteSequences;
1319522600a2SDimitry Andric   SmallVector<SmallVector<unsigned, 4>, 16> ReadSequences;
1320b60736ecSDimitry Andric   unsigned ProcIndex = 0;
1321b60736ecSDimitry Andric 
1322b60736ecSDimitry Andric   PredTransition() = default;
PredTransition__anon5fa3bdea0b11::PredTransition1323b60736ecSDimitry Andric   PredTransition(ArrayRef<PredCheck> PT, unsigned ProcId) {
1324b60736ecSDimitry Andric     PredTerm.assign(PT.begin(), PT.end());
1325b60736ecSDimitry Andric     ProcIndex = ProcId;
1326b60736ecSDimitry Andric   }
1327522600a2SDimitry Andric };
1328522600a2SDimitry Andric 
1329522600a2SDimitry Andric // Encapsulate a set of partially constructed transitions.
1330522600a2SDimitry Andric // The results are built by repeated calls to substituteVariants.
1331522600a2SDimitry Andric class PredTransitions {
1332522600a2SDimitry Andric   CodeGenSchedModels &SchedModels;
1333522600a2SDimitry Andric 
1334522600a2SDimitry Andric public:
1335522600a2SDimitry Andric   std::vector<PredTransition> TransVec;
1336522600a2SDimitry Andric 
PredTransitions(CodeGenSchedModels & sm)1337522600a2SDimitry Andric   PredTransitions(CodeGenSchedModels &sm) : SchedModels(sm) {}
1338522600a2SDimitry Andric 
1339b60736ecSDimitry Andric   bool substituteVariantOperand(const SmallVectorImpl<unsigned> &RWSeq,
1340522600a2SDimitry Andric                                 bool IsRead, unsigned StartIdx);
1341522600a2SDimitry Andric 
1342b60736ecSDimitry Andric   bool substituteVariants(const PredTransition &Trans);
1343522600a2SDimitry Andric 
1344522600a2SDimitry Andric #ifndef NDEBUG
1345522600a2SDimitry Andric   void dump() const;
134658b69754SDimitry Andric #endif
1347522600a2SDimitry Andric 
1348522600a2SDimitry Andric private:
1349b60736ecSDimitry Andric   bool mutuallyExclusive(Record *PredDef, ArrayRef<Record *> Preds,
1350b60736ecSDimitry Andric                          ArrayRef<PredCheck> Term);
1351ac9a064cSDimitry Andric   void getIntersectingVariants(const CodeGenSchedRW &SchedRW, unsigned TransIdx,
1352522600a2SDimitry Andric                                std::vector<TransVariant> &IntersectingVariants);
1353522600a2SDimitry Andric   void pushVariant(const TransVariant &VInfo, bool IsRead);
1354522600a2SDimitry Andric };
1355b915e9e0SDimitry Andric 
1356b915e9e0SDimitry Andric } // end anonymous namespace
1357522600a2SDimitry Andric 
1358522600a2SDimitry Andric // Return true if this predicate is mutually exclusive with a PredTerm. This
1359522600a2SDimitry Andric // degenerates into checking if the predicate is mutually exclusive with any
1360522600a2SDimitry Andric // predicate in the Term's conjunction.
1361522600a2SDimitry Andric //
1362522600a2SDimitry Andric // All predicates associated with a given SchedRW are considered mutually
1363522600a2SDimitry Andric // exclusive. This should work even if the conditions expressed by the
1364522600a2SDimitry Andric // predicates are not exclusive because the predicates for a given SchedWrite
1365522600a2SDimitry Andric // are always checked in the order they are defined in the .td file. Later
1366522600a2SDimitry Andric // conditions implicitly negate any prior condition.
mutuallyExclusive(Record * PredDef,ArrayRef<Record * > Preds,ArrayRef<PredCheck> Term)1367522600a2SDimitry Andric bool PredTransitions::mutuallyExclusive(Record *PredDef,
1368b60736ecSDimitry Andric                                         ArrayRef<Record *> Preds,
1369522600a2SDimitry Andric                                         ArrayRef<PredCheck> Term) {
1370044eb2f6SDimitry Andric   for (const PredCheck &PC : Term) {
1371044eb2f6SDimitry Andric     if (PC.Predicate == PredDef)
1372522600a2SDimitry Andric       return false;
1373522600a2SDimitry Andric 
1374044eb2f6SDimitry Andric     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(PC.RWIdx, PC.IsRead);
1375522600a2SDimitry Andric     assert(SchedRW.HasVariants && "PredCheck must refer to a SchedVariant");
1376522600a2SDimitry Andric     RecVec Variants = SchedRW.TheDef->getValueAsListOfDefs("Variants");
1377eb11fae6SDimitry Andric     if (any_of(Variants, [PredDef](const Record *R) {
1378eb11fae6SDimitry Andric           return R->getValueAsDef("Predicate") == PredDef;
1379b60736ecSDimitry Andric         })) {
1380b60736ecSDimitry Andric       // To check if PredDef is mutually exclusive with PC we also need to
1381b60736ecSDimitry Andric       // check that PC.Predicate is exclusive with all predicates from variant
1382b60736ecSDimitry Andric       // we're expanding. Consider following RW sequence with two variants
1383b60736ecSDimitry Andric       // (1 & 2), where A, B and C are predicates from corresponding SchedVars:
1384b60736ecSDimitry Andric       //
1385b60736ecSDimitry Andric       // 1:A/B - 2:C/B
1386b60736ecSDimitry Andric       //
1387b60736ecSDimitry Andric       // Here C is not mutually exclusive with variant (1), because A doesn't
1388b60736ecSDimitry Andric       // exist in variant (2). This means we have possible transitions from A
1389b60736ecSDimitry Andric       // to C and from A to B, and fully expanded sequence would look like:
1390b60736ecSDimitry Andric       //
1391b60736ecSDimitry Andric       // if (A & C) return ...;
1392b60736ecSDimitry Andric       // if (A & B) return ...;
1393b60736ecSDimitry Andric       // if (B) return ...;
1394b60736ecSDimitry Andric       //
1395b60736ecSDimitry Andric       // Now let's consider another sequence:
1396b60736ecSDimitry Andric       //
1397b60736ecSDimitry Andric       // 1:A/B - 2:A/B
1398b60736ecSDimitry Andric       //
1399b60736ecSDimitry Andric       // Here A in variant (2) is mutually exclusive with variant (1), because
1400b60736ecSDimitry Andric       // A also exists in (2). This means A->B transition is impossible and
1401b60736ecSDimitry Andric       // expanded sequence would look like:
1402b60736ecSDimitry Andric       //
1403b60736ecSDimitry Andric       // if (A) return ...;
1404b60736ecSDimitry Andric       // if (B) return ...;
140577fc4c14SDimitry Andric       if (!llvm::is_contained(Preds, PC.Predicate))
1406b60736ecSDimitry Andric         continue;
1407522600a2SDimitry Andric       return true;
140858b69754SDimitry Andric     }
1409522600a2SDimitry Andric   }
1410522600a2SDimitry Andric   return false;
1411522600a2SDimitry Andric }
1412522600a2SDimitry Andric 
getAllPredicates(ArrayRef<TransVariant> Variants,unsigned ProcId)1413b60736ecSDimitry Andric static std::vector<Record *> getAllPredicates(ArrayRef<TransVariant> Variants,
1414b60736ecSDimitry Andric                                               unsigned ProcId) {
1415b60736ecSDimitry Andric   std::vector<Record *> Preds;
1416b60736ecSDimitry Andric   for (auto &Variant : Variants) {
1417b60736ecSDimitry Andric     if (!Variant.VarOrSeqDef->isSubClassOf("SchedVar"))
1418b60736ecSDimitry Andric       continue;
1419b60736ecSDimitry Andric     Preds.push_back(Variant.VarOrSeqDef->getValueAsDef("Predicate"));
1420522600a2SDimitry Andric   }
1421b60736ecSDimitry Andric   return Preds;
1422522600a2SDimitry Andric }
1423522600a2SDimitry Andric 
1424522600a2SDimitry Andric // Populate IntersectingVariants with any variants or aliased sequences of the
1425522600a2SDimitry Andric // given SchedRW whose processor indices and predicates are not mutually
14264a16efa3SDimitry Andric // exclusive with the given transition.
getIntersectingVariants(const CodeGenSchedRW & SchedRW,unsigned TransIdx,std::vector<TransVariant> & IntersectingVariants)1427522600a2SDimitry Andric void PredTransitions::getIntersectingVariants(
1428522600a2SDimitry Andric     const CodeGenSchedRW &SchedRW, unsigned TransIdx,
1429522600a2SDimitry Andric     std::vector<TransVariant> &IntersectingVariants) {
1430522600a2SDimitry Andric 
14314a16efa3SDimitry Andric   bool GenericRW = false;
14324a16efa3SDimitry Andric 
1433522600a2SDimitry Andric   std::vector<TransVariant> Variants;
1434522600a2SDimitry Andric   if (SchedRW.HasVariants) {
1435522600a2SDimitry Andric     unsigned VarProcIdx = 0;
1436522600a2SDimitry Andric     if (SchedRW.TheDef->getValueInit("SchedModel")->isComplete()) {
1437522600a2SDimitry Andric       Record *ModelDef = SchedRW.TheDef->getValueAsDef("SchedModel");
1438522600a2SDimitry Andric       VarProcIdx = SchedModels.getProcModel(ModelDef).Index;
1439522600a2SDimitry Andric     }
1440b60736ecSDimitry Andric     if (VarProcIdx == 0 || VarProcIdx == TransVec[TransIdx].ProcIndex) {
1441522600a2SDimitry Andric       // Push each variant. Assign TransVecIdx later.
1442522600a2SDimitry Andric       const RecVec VarDefs = SchedRW.TheDef->getValueAsListOfDefs("Variants");
1443044eb2f6SDimitry Andric       for (Record *VarDef : VarDefs)
1444eb11fae6SDimitry Andric         Variants.emplace_back(VarDef, SchedRW.Index, VarProcIdx, 0);
14454a16efa3SDimitry Andric       if (VarProcIdx == 0)
14464a16efa3SDimitry Andric         GenericRW = true;
1447522600a2SDimitry Andric     }
1448b60736ecSDimitry Andric   }
1449522600a2SDimitry Andric   for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
1450522600a2SDimitry Andric        AI != AE; ++AI) {
1451522600a2SDimitry Andric     // If either the SchedAlias itself or the SchedReadWrite that it aliases
1452522600a2SDimitry Andric     // to is defined within a processor model, constrain all variants to
1453522600a2SDimitry Andric     // that processor.
1454522600a2SDimitry Andric     unsigned AliasProcIdx = 0;
1455522600a2SDimitry Andric     if ((*AI)->getValueInit("SchedModel")->isComplete()) {
1456522600a2SDimitry Andric       Record *ModelDef = (*AI)->getValueAsDef("SchedModel");
1457522600a2SDimitry Andric       AliasProcIdx = SchedModels.getProcModel(ModelDef).Index;
1458522600a2SDimitry Andric     }
1459b60736ecSDimitry Andric     if (AliasProcIdx && AliasProcIdx != TransVec[TransIdx].ProcIndex)
1460b60736ecSDimitry Andric       continue;
1461b60736ecSDimitry Andric     if (!Variants.empty()) {
1462b60736ecSDimitry Andric       const CodeGenProcModel &PM =
1463b60736ecSDimitry Andric           *(SchedModels.procModelBegin() + AliasProcIdx);
1464b60736ecSDimitry Andric       PrintFatalError((*AI)->getLoc(),
1465b60736ecSDimitry Andric                       "Multiple variants defined for processor " +
1466b60736ecSDimitry Andric                           PM.ModelName +
1467b60736ecSDimitry Andric                           " Ensure only one SchedAlias exists per RW.");
1468b60736ecSDimitry Andric     }
1469b60736ecSDimitry Andric 
1470522600a2SDimitry Andric     const CodeGenSchedRW &AliasRW =
1471522600a2SDimitry Andric         SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
1472522600a2SDimitry Andric 
1473522600a2SDimitry Andric     if (AliasRW.HasVariants) {
1474522600a2SDimitry Andric       const RecVec VarDefs = AliasRW.TheDef->getValueAsListOfDefs("Variants");
1475044eb2f6SDimitry Andric       for (Record *VD : VarDefs)
1476eb11fae6SDimitry Andric         Variants.emplace_back(VD, AliasRW.Index, AliasProcIdx, 0);
1477522600a2SDimitry Andric     }
1478eb11fae6SDimitry Andric     if (AliasRW.IsSequence)
1479eb11fae6SDimitry Andric       Variants.emplace_back(AliasRW.TheDef, SchedRW.Index, AliasProcIdx, 0);
14804a16efa3SDimitry Andric     if (AliasProcIdx == 0)
14814a16efa3SDimitry Andric       GenericRW = true;
1482522600a2SDimitry Andric   }
1483b60736ecSDimitry Andric   std::vector<Record *> AllPreds =
1484b60736ecSDimitry Andric       getAllPredicates(Variants, TransVec[TransIdx].ProcIndex);
1485044eb2f6SDimitry Andric   for (TransVariant &Variant : Variants) {
1486522600a2SDimitry Andric     // Don't expand variants if the processor models don't intersect.
1487522600a2SDimitry Andric     // A zero processor index means any processor.
1488522600a2SDimitry Andric     if (Variant.VarOrSeqDef->isSubClassOf("SchedVar")) {
1489522600a2SDimitry Andric       Record *PredDef = Variant.VarOrSeqDef->getValueAsDef("Predicate");
1490b60736ecSDimitry Andric       if (mutuallyExclusive(PredDef, AllPreds, TransVec[TransIdx].PredTerm))
1491522600a2SDimitry Andric         continue;
1492522600a2SDimitry Andric     }
1493b60736ecSDimitry Andric 
1494522600a2SDimitry Andric     if (IntersectingVariants.empty()) {
1495522600a2SDimitry Andric       // The first variant builds on the existing transition.
1496522600a2SDimitry Andric       Variant.TransVecIdx = TransIdx;
1497522600a2SDimitry Andric       IntersectingVariants.push_back(Variant);
1498ac9a064cSDimitry Andric     } else {
1499522600a2SDimitry Andric       // Push another copy of the current transition for more variants.
1500522600a2SDimitry Andric       Variant.TransVecIdx = TransVec.size();
1501522600a2SDimitry Andric       IntersectingVariants.push_back(Variant);
1502522600a2SDimitry Andric       TransVec.push_back(TransVec[TransIdx]);
1503522600a2SDimitry Andric     }
1504522600a2SDimitry Andric   }
15054a16efa3SDimitry Andric   if (GenericRW && IntersectingVariants.empty()) {
1506ac9a064cSDimitry Andric     PrintFatalError(SchedRW.TheDef->getLoc(),
1507ac9a064cSDimitry Andric                     "No variant of this type has "
15084a16efa3SDimitry Andric                     "a matching predicate on any processor");
15094a16efa3SDimitry Andric   }
1510522600a2SDimitry Andric }
1511522600a2SDimitry Andric 
1512522600a2SDimitry Andric // Push the Reads/Writes selected by this variant onto the PredTransition
1513522600a2SDimitry Andric // specified by VInfo.
pushVariant(const TransVariant & VInfo,bool IsRead)1514ac9a064cSDimitry Andric void PredTransitions::pushVariant(const TransVariant &VInfo, bool IsRead) {
1515522600a2SDimitry Andric   PredTransition &Trans = TransVec[VInfo.TransVecIdx];
1516522600a2SDimitry Andric 
1517522600a2SDimitry Andric   // If this operand transition is reached through a processor-specific alias,
1518522600a2SDimitry Andric   // then the whole transition is specific to this processor.
1519522600a2SDimitry Andric   IdxVec SelectedRWs;
1520522600a2SDimitry Andric   if (VInfo.VarOrSeqDef->isSubClassOf("SchedVar")) {
1521522600a2SDimitry Andric     Record *PredDef = VInfo.VarOrSeqDef->getValueAsDef("Predicate");
1522eb11fae6SDimitry Andric     Trans.PredTerm.emplace_back(IsRead, VInfo.RWIdx, PredDef);
1523522600a2SDimitry Andric     RecVec SelectedDefs = VInfo.VarOrSeqDef->getValueAsListOfDefs("Selected");
1524522600a2SDimitry Andric     SchedModels.findRWs(SelectedDefs, SelectedRWs, IsRead);
1525ac9a064cSDimitry Andric   } else {
1526522600a2SDimitry Andric     assert(VInfo.VarOrSeqDef->isSubClassOf("WriteSequence") &&
1527522600a2SDimitry Andric            "variant must be a SchedVariant or aliased WriteSequence");
1528522600a2SDimitry Andric     SelectedRWs.push_back(SchedModels.getSchedRWIdx(VInfo.VarOrSeqDef, IsRead));
1529522600a2SDimitry Andric   }
1530522600a2SDimitry Andric 
1531522600a2SDimitry Andric   const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(VInfo.RWIdx, IsRead);
1532522600a2SDimitry Andric 
1533ac9a064cSDimitry Andric   SmallVectorImpl<SmallVector<unsigned, 4>> &RWSequences =
1534ac9a064cSDimitry Andric       IsRead ? Trans.ReadSequences : Trans.WriteSequences;
1535522600a2SDimitry Andric   if (SchedRW.IsVariadic) {
1536522600a2SDimitry Andric     unsigned OperIdx = RWSequences.size() - 1;
1537522600a2SDimitry Andric     // Make N-1 copies of this transition's last sequence.
1538b60736ecSDimitry Andric     RWSequences.reserve(RWSequences.size() + SelectedRWs.size() - 1);
1539eb11fae6SDimitry Andric     RWSequences.insert(RWSequences.end(), SelectedRWs.size() - 1,
1540eb11fae6SDimitry Andric                        RWSequences[OperIdx]);
1541522600a2SDimitry Andric     // Push each of the N elements of the SelectedRWs onto a copy of the last
1542522600a2SDimitry Andric     // sequence (split the current operand into N operands).
1543522600a2SDimitry Andric     // Note that write sequences should be expanded within this loop--the entire
1544522600a2SDimitry Andric     // sequence belongs to a single operand.
1545ac9a064cSDimitry Andric     for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end(); RWI != RWE;
1546ac9a064cSDimitry Andric          ++RWI, ++OperIdx) {
1547522600a2SDimitry Andric       IdxVec ExpandedRWs;
1548522600a2SDimitry Andric       if (IsRead)
1549522600a2SDimitry Andric         ExpandedRWs.push_back(*RWI);
1550522600a2SDimitry Andric       else
1551522600a2SDimitry Andric         SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
1552b60736ecSDimitry Andric       llvm::append_range(RWSequences[OperIdx], ExpandedRWs);
1553522600a2SDimitry Andric     }
1554522600a2SDimitry Andric     assert(OperIdx == RWSequences.size() && "missed a sequence");
1555ac9a064cSDimitry Andric   } else {
1556522600a2SDimitry Andric     // Push this transition's expanded sequence onto this transition's last
1557522600a2SDimitry Andric     // sequence (add to the current operand's sequence).
1558522600a2SDimitry Andric     SmallVectorImpl<unsigned> &Seq = RWSequences.back();
1559522600a2SDimitry Andric     IdxVec ExpandedRWs;
1560344a3780SDimitry Andric     for (unsigned int SelectedRW : SelectedRWs) {
1561522600a2SDimitry Andric       if (IsRead)
1562344a3780SDimitry Andric         ExpandedRWs.push_back(SelectedRW);
1563522600a2SDimitry Andric       else
1564344a3780SDimitry Andric         SchedModels.expandRWSequence(SelectedRW, ExpandedRWs, IsRead);
1565522600a2SDimitry Andric     }
1566b60736ecSDimitry Andric     llvm::append_range(Seq, ExpandedRWs);
1567522600a2SDimitry Andric   }
1568522600a2SDimitry Andric }
1569522600a2SDimitry Andric 
1570522600a2SDimitry Andric // RWSeq is a sequence of all Reads or all Writes for the next read or write
1571522600a2SDimitry Andric // operand. StartIdx is an index into TransVec where partial results
1572522600a2SDimitry Andric // starts. RWSeq must be applied to all transitions between StartIdx and the end
1573522600a2SDimitry Andric // of TransVec.
substituteVariantOperand(const SmallVectorImpl<unsigned> & RWSeq,bool IsRead,unsigned StartIdx)1574b60736ecSDimitry Andric bool PredTransitions::substituteVariantOperand(
1575522600a2SDimitry Andric     const SmallVectorImpl<unsigned> &RWSeq, bool IsRead, unsigned StartIdx) {
1576b60736ecSDimitry Andric   bool Subst = false;
1577522600a2SDimitry Andric   // Visit each original RW within the current sequence.
1578344a3780SDimitry Andric   for (unsigned int RWI : RWSeq) {
1579344a3780SDimitry Andric     const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(RWI, IsRead);
1580522600a2SDimitry Andric     // Push this RW on all partial PredTransitions or distribute variants.
1581522600a2SDimitry Andric     // New PredTransitions may be pushed within this loop which should not be
1582522600a2SDimitry Andric     // revisited (TransEnd must be loop invariant).
1583522600a2SDimitry Andric     for (unsigned TransIdx = StartIdx, TransEnd = TransVec.size();
1584522600a2SDimitry Andric          TransIdx != TransEnd; ++TransIdx) {
1585522600a2SDimitry Andric       // Distribute this partial PredTransition across intersecting variants.
1586522600a2SDimitry Andric       // This will push a copies of TransVec[TransIdx] on the back of TransVec.
1587522600a2SDimitry Andric       std::vector<TransVariant> IntersectingVariants;
1588522600a2SDimitry Andric       getIntersectingVariants(SchedRW, TransIdx, IntersectingVariants);
1589522600a2SDimitry Andric       // Now expand each variant on top of its copy of the transition.
1590b60736ecSDimitry Andric       for (const TransVariant &IV : IntersectingVariants)
1591b60736ecSDimitry Andric         pushVariant(IV, IsRead);
1592b60736ecSDimitry Andric       if (IntersectingVariants.empty()) {
1593b60736ecSDimitry Andric         if (IsRead)
1594344a3780SDimitry Andric           TransVec[TransIdx].ReadSequences.back().push_back(RWI);
1595b60736ecSDimitry Andric         else
1596344a3780SDimitry Andric           TransVec[TransIdx].WriteSequences.back().push_back(RWI);
1597b60736ecSDimitry Andric         continue;
1598b60736ecSDimitry Andric       } else {
1599b60736ecSDimitry Andric         Subst = true;
1600522600a2SDimitry Andric       }
1601522600a2SDimitry Andric     }
1602522600a2SDimitry Andric   }
1603b60736ecSDimitry Andric   return Subst;
1604522600a2SDimitry Andric }
1605522600a2SDimitry Andric 
1606522600a2SDimitry Andric // For each variant of a Read/Write in Trans, substitute the sequence of
1607522600a2SDimitry Andric // Read/Writes guarded by the variant. This is exponential in the number of
1608522600a2SDimitry Andric // variant Read/Writes, but in practice detection of mutually exclusive
1609522600a2SDimitry Andric // predicates should result in linear growth in the total number variants.
1610522600a2SDimitry Andric //
1611522600a2SDimitry Andric // This is one step in a breadth-first search of nested variants.
substituteVariants(const PredTransition & Trans)1612b60736ecSDimitry Andric bool PredTransitions::substituteVariants(const PredTransition &Trans) {
1613522600a2SDimitry Andric   // Build up a set of partial results starting at the back of
1614522600a2SDimitry Andric   // PredTransitions. Remember the first new transition.
1615522600a2SDimitry Andric   unsigned StartIdx = TransVec.size();
1616b60736ecSDimitry Andric   bool Subst = false;
1617b60736ecSDimitry Andric   assert(Trans.ProcIndex != 0);
1618b60736ecSDimitry Andric   TransVec.emplace_back(Trans.PredTerm, Trans.ProcIndex);
1619522600a2SDimitry Andric 
1620522600a2SDimitry Andric   // Visit each original write sequence.
1621344a3780SDimitry Andric   for (const auto &WriteSequence : Trans.WriteSequences) {
1622522600a2SDimitry Andric     // Push a new (empty) write sequence onto all partial Transitions.
1623ac9a064cSDimitry Andric     for (std::vector<PredTransition>::iterator I = TransVec.begin() + StartIdx,
1624ac9a064cSDimitry Andric                                                E = TransVec.end();
1625ac9a064cSDimitry Andric          I != E; ++I) {
1626eb11fae6SDimitry Andric       I->WriteSequences.emplace_back();
1627522600a2SDimitry Andric     }
1628344a3780SDimitry Andric     Subst |=
1629344a3780SDimitry Andric         substituteVariantOperand(WriteSequence, /*IsRead=*/false, StartIdx);
1630522600a2SDimitry Andric   }
1631522600a2SDimitry Andric   // Visit each original read sequence.
1632344a3780SDimitry Andric   for (const auto &ReadSequence : Trans.ReadSequences) {
1633522600a2SDimitry Andric     // Push a new (empty) read sequence onto all partial Transitions.
1634ac9a064cSDimitry Andric     for (std::vector<PredTransition>::iterator I = TransVec.begin() + StartIdx,
1635ac9a064cSDimitry Andric                                                E = TransVec.end();
1636ac9a064cSDimitry Andric          I != E; ++I) {
1637eb11fae6SDimitry Andric       I->ReadSequences.emplace_back();
1638522600a2SDimitry Andric     }
1639344a3780SDimitry Andric     Subst |= substituteVariantOperand(ReadSequence, /*IsRead=*/true, StartIdx);
1640522600a2SDimitry Andric   }
1641b60736ecSDimitry Andric   return Subst;
1642522600a2SDimitry Andric }
1643522600a2SDimitry Andric 
addSequences(CodeGenSchedModels & SchedModels,const SmallVectorImpl<SmallVector<unsigned,4>> & Seqs,IdxVec & Result,bool IsRead)1644b60736ecSDimitry Andric static void addSequences(CodeGenSchedModels &SchedModels,
1645b60736ecSDimitry Andric                          const SmallVectorImpl<SmallVector<unsigned, 4>> &Seqs,
1646b60736ecSDimitry Andric                          IdxVec &Result, bool IsRead) {
1647b60736ecSDimitry Andric   for (const auto &S : Seqs)
1648b60736ecSDimitry Andric     if (!S.empty())
1649b60736ecSDimitry Andric       Result.push_back(SchedModels.findOrInsertRW(S, IsRead));
1650b60736ecSDimitry Andric }
1651b60736ecSDimitry Andric 
1652b60736ecSDimitry Andric #ifndef NDEBUG
dumpRecVec(const RecVec & RV)1653b60736ecSDimitry Andric static void dumpRecVec(const RecVec &RV) {
1654b60736ecSDimitry Andric   for (const Record *R : RV)
1655b60736ecSDimitry Andric     dbgs() << R->getName() << ", ";
1656b60736ecSDimitry Andric }
1657b60736ecSDimitry Andric #endif
1658b60736ecSDimitry Andric 
dumpTransition(const CodeGenSchedModels & SchedModels,const CodeGenSchedClass & FromSC,const CodeGenSchedTransition & SCTrans,const RecVec & Preds)1659b60736ecSDimitry Andric static void dumpTransition(const CodeGenSchedModels &SchedModels,
1660b60736ecSDimitry Andric                            const CodeGenSchedClass &FromSC,
1661b60736ecSDimitry Andric                            const CodeGenSchedTransition &SCTrans,
1662b60736ecSDimitry Andric                            const RecVec &Preds) {
1663b60736ecSDimitry Andric   LLVM_DEBUG(dbgs() << "Adding transition from " << FromSC.Name << "("
1664b60736ecSDimitry Andric                     << FromSC.Index << ") to "
1665b60736ecSDimitry Andric                     << SchedModels.getSchedClass(SCTrans.ToClassIdx).Name << "("
1666b60736ecSDimitry Andric                     << SCTrans.ToClassIdx << ") on pred term: (";
1667b60736ecSDimitry Andric              dumpRecVec(Preds);
1668b60736ecSDimitry Andric              dbgs() << ") on processor (" << SCTrans.ProcIndex << ")\n");
1669b60736ecSDimitry Andric }
1670522600a2SDimitry Andric // Create a new SchedClass for each variant found by inferFromRW. Pass
inferFromTransitions(ArrayRef<PredTransition> LastTransitions,unsigned FromClassIdx,CodeGenSchedModels & SchedModels)1671522600a2SDimitry Andric static void inferFromTransitions(ArrayRef<PredTransition> LastTransitions,
1672522600a2SDimitry Andric                                  unsigned FromClassIdx,
1673522600a2SDimitry Andric                                  CodeGenSchedModels &SchedModels) {
1674522600a2SDimitry Andric   // For each PredTransition, create a new CodeGenSchedTransition, which usually
1675522600a2SDimitry Andric   // requires creating a new SchedClass.
1676344a3780SDimitry Andric   for (const auto &LastTransition : LastTransitions) {
1677b60736ecSDimitry Andric     // Variant expansion (substituteVariants) may create unconditional
1678b60736ecSDimitry Andric     // transitions. We don't need to build sched classes for them.
1679344a3780SDimitry Andric     if (LastTransition.PredTerm.empty())
1680b60736ecSDimitry Andric       continue;
1681b60736ecSDimitry Andric     IdxVec OperWritesVariant, OperReadsVariant;
1682344a3780SDimitry Andric     addSequences(SchedModels, LastTransition.WriteSequences, OperWritesVariant,
1683344a3780SDimitry Andric                  false);
1684344a3780SDimitry Andric     addSequences(SchedModels, LastTransition.ReadSequences, OperReadsVariant,
1685344a3780SDimitry Andric                  true);
1686522600a2SDimitry Andric     CodeGenSchedTransition SCTrans;
1687b60736ecSDimitry Andric 
1688b60736ecSDimitry Andric     // Transition should not contain processor indices already assigned to
1689b60736ecSDimitry Andric     // InstRWs in this scheduling class.
1690b60736ecSDimitry Andric     const CodeGenSchedClass &FromSC = SchedModels.getSchedClass(FromClassIdx);
1691344a3780SDimitry Andric     if (FromSC.InstRWProcIndices.count(LastTransition.ProcIndex))
1692b60736ecSDimitry Andric       continue;
1693344a3780SDimitry Andric     SCTrans.ProcIndex = LastTransition.ProcIndex;
1694522600a2SDimitry Andric     SCTrans.ToClassIdx =
16955ca98fd9SDimitry Andric         SchedModels.addSchedClass(/*ItinClassDef=*/nullptr, OperWritesVariant,
1696344a3780SDimitry Andric                                   OperReadsVariant, LastTransition.ProcIndex);
1697b60736ecSDimitry Andric 
1698522600a2SDimitry Andric     // The final PredTerm is unique set of predicates guarding the transition.
1699522600a2SDimitry Andric     RecVec Preds;
1700344a3780SDimitry Andric     transform(LastTransition.PredTerm, std::back_inserter(Preds),
1701344a3780SDimitry Andric               [](const PredCheck &P) { return P.Predicate; });
1702ac9a064cSDimitry Andric     Preds.erase(llvm::unique(Preds), Preds.end());
1703b60736ecSDimitry Andric     dumpTransition(SchedModels, FromSC, SCTrans, Preds);
1704eb11fae6SDimitry Andric     SCTrans.PredTerm = std::move(Preds);
1705eb11fae6SDimitry Andric     SchedModels.getSchedClass(FromClassIdx)
1706eb11fae6SDimitry Andric         .Transitions.push_back(std::move(SCTrans));
1707522600a2SDimitry Andric   }
1708522600a2SDimitry Andric }
1709522600a2SDimitry Andric 
getAllProcIndices() const1710b60736ecSDimitry Andric std::vector<unsigned> CodeGenSchedModels::getAllProcIndices() const {
1711b60736ecSDimitry Andric   std::vector<unsigned> ProcIdVec;
1712b60736ecSDimitry Andric   for (const auto &PM : ProcModelMap)
1713b60736ecSDimitry Andric     if (PM.second != 0)
1714b60736ecSDimitry Andric       ProcIdVec.push_back(PM.second);
1715b60736ecSDimitry Andric   // The order of the keys (Record pointers) of ProcModelMap are not stable.
1716b60736ecSDimitry Andric   // Sort to stabalize the values.
1717b60736ecSDimitry Andric   llvm::sort(ProcIdVec);
1718b60736ecSDimitry Andric   return ProcIdVec;
1719b60736ecSDimitry Andric }
1720b60736ecSDimitry Andric 
1721b60736ecSDimitry Andric static std::vector<PredTransition>
makePerProcessorTransitions(const PredTransition & Trans,ArrayRef<unsigned> ProcIndices)1722b60736ecSDimitry Andric makePerProcessorTransitions(const PredTransition &Trans,
1723b60736ecSDimitry Andric                             ArrayRef<unsigned> ProcIndices) {
1724b60736ecSDimitry Andric   std::vector<PredTransition> PerCpuTransVec;
1725b60736ecSDimitry Andric   for (unsigned ProcId : ProcIndices) {
1726b60736ecSDimitry Andric     assert(ProcId != 0);
1727b60736ecSDimitry Andric     PerCpuTransVec.push_back(Trans);
1728b60736ecSDimitry Andric     PerCpuTransVec.back().ProcIndex = ProcId;
1729b60736ecSDimitry Andric   }
1730b60736ecSDimitry Andric   return PerCpuTransVec;
1731b60736ecSDimitry Andric }
1732b60736ecSDimitry Andric 
1733522600a2SDimitry Andric // Create new SchedClasses for the given ReadWrite list. If any of the
1734522600a2SDimitry Andric // ReadWrites refers to a SchedVariant, create a new SchedClass for each variant
1735522600a2SDimitry Andric // of the ReadWrite list, following Aliases if necessary.
inferFromRW(ArrayRef<unsigned> OperWrites,ArrayRef<unsigned> OperReads,unsigned FromClassIdx,ArrayRef<unsigned> ProcIndices)1736dd58ef01SDimitry Andric void CodeGenSchedModels::inferFromRW(ArrayRef<unsigned> OperWrites,
1737dd58ef01SDimitry Andric                                      ArrayRef<unsigned> OperReads,
1738522600a2SDimitry Andric                                      unsigned FromClassIdx,
1739dd58ef01SDimitry Andric                                      ArrayRef<unsigned> ProcIndices) {
1740eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "INFER RW proc("; dumpIdxVec(ProcIndices);
1741eb11fae6SDimitry Andric              dbgs() << ") ");
1742522600a2SDimitry Andric   // Create a seed transition with an empty PredTerm and the expanded sequences
1743522600a2SDimitry Andric   // of SchedWrites for the current SchedClass.
1744522600a2SDimitry Andric   std::vector<PredTransition> LastTransitions;
1745eb11fae6SDimitry Andric   LastTransitions.emplace_back();
1746522600a2SDimitry Andric 
1747dd58ef01SDimitry Andric   for (unsigned WriteIdx : OperWrites) {
1748522600a2SDimitry Andric     IdxVec WriteSeq;
1749dd58ef01SDimitry Andric     expandRWSequence(WriteIdx, WriteSeq, /*IsRead=*/false);
1750eb11fae6SDimitry Andric     LastTransitions[0].WriteSequences.emplace_back();
1751eb11fae6SDimitry Andric     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].WriteSequences.back();
1752eb11fae6SDimitry Andric     Seq.append(WriteSeq.begin(), WriteSeq.end());
1753eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
1754522600a2SDimitry Andric   }
1755eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << " Reads: ");
1756dd58ef01SDimitry Andric   for (unsigned ReadIdx : OperReads) {
1757522600a2SDimitry Andric     IdxVec ReadSeq;
1758dd58ef01SDimitry Andric     expandRWSequence(ReadIdx, ReadSeq, /*IsRead=*/true);
1759eb11fae6SDimitry Andric     LastTransitions[0].ReadSequences.emplace_back();
1760eb11fae6SDimitry Andric     SmallVectorImpl<unsigned> &Seq = LastTransitions[0].ReadSequences.back();
1761eb11fae6SDimitry Andric     Seq.append(ReadSeq.begin(), ReadSeq.end());
1762eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
1763522600a2SDimitry Andric   }
1764eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << '\n');
1765522600a2SDimitry Andric 
1766b60736ecSDimitry Andric   LastTransitions = makePerProcessorTransitions(
1767b60736ecSDimitry Andric       LastTransitions[0], llvm::is_contained(ProcIndices, 0)
1768b60736ecSDimitry Andric                               ? ArrayRef<unsigned>(getAllProcIndices())
1769b60736ecSDimitry Andric                               : ProcIndices);
1770522600a2SDimitry Andric   // Collect all PredTransitions for individual operands.
1771522600a2SDimitry Andric   // Iterate until no variant writes remain.
1772b60736ecSDimitry Andric   bool SubstitutedAny;
1773b60736ecSDimitry Andric   do {
1774b60736ecSDimitry Andric     SubstitutedAny = false;
1775522600a2SDimitry Andric     PredTransitions Transitions(*this);
1776eb11fae6SDimitry Andric     for (const PredTransition &Trans : LastTransitions)
1777b60736ecSDimitry Andric       SubstitutedAny |= Transitions.substituteVariants(Trans);
1778eb11fae6SDimitry Andric     LLVM_DEBUG(Transitions.dump());
1779ac9a064cSDimitry Andric     LastTransitions = std::move(Transitions.TransVec);
1780b60736ecSDimitry Andric   } while (SubstitutedAny);
1781522600a2SDimitry Andric 
1782522600a2SDimitry Andric   // WARNING: We are about to mutate the SchedClasses vector. Do not refer to
1783522600a2SDimitry Andric   // OperWrites, OperReads, or ProcIndices after calling inferFromTransitions.
1784522600a2SDimitry Andric   inferFromTransitions(LastTransitions, FromClassIdx, *this);
1785522600a2SDimitry Andric }
1786522600a2SDimitry Andric 
178759d6cff9SDimitry Andric // Check if any processor resource group contains all resource records in
178859d6cff9SDimitry Andric // SubUnits.
hasSuperGroup(RecVec & SubUnits,CodeGenProcModel & PM)178959d6cff9SDimitry Andric bool CodeGenSchedModels::hasSuperGroup(RecVec &SubUnits, CodeGenProcModel &PM) {
1790344a3780SDimitry Andric   for (Record *ProcResourceDef : PM.ProcResourceDefs) {
1791344a3780SDimitry Andric     if (!ProcResourceDef->isSubClassOf("ProcResGroup"))
179259d6cff9SDimitry Andric       continue;
1793344a3780SDimitry Andric     RecVec SuperUnits = ProcResourceDef->getValueAsListOfDefs("Resources");
179459d6cff9SDimitry Andric     RecIter RI = SubUnits.begin(), RE = SubUnits.end();
179559d6cff9SDimitry Andric     for (; RI != RE; ++RI) {
1796b915e9e0SDimitry Andric       if (!is_contained(SuperUnits, *RI)) {
179759d6cff9SDimitry Andric         break;
179859d6cff9SDimitry Andric       }
179959d6cff9SDimitry Andric     }
180059d6cff9SDimitry Andric     if (RI == RE)
180159d6cff9SDimitry Andric       return true;
180259d6cff9SDimitry Andric   }
180359d6cff9SDimitry Andric   return false;
180459d6cff9SDimitry Andric }
180559d6cff9SDimitry Andric 
180659d6cff9SDimitry Andric // Verify that overlapping groups have a common supergroup.
verifyProcResourceGroups(CodeGenProcModel & PM)180759d6cff9SDimitry Andric void CodeGenSchedModels::verifyProcResourceGroups(CodeGenProcModel &PM) {
180859d6cff9SDimitry Andric   for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
180959d6cff9SDimitry Andric     if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
181059d6cff9SDimitry Andric       continue;
181159d6cff9SDimitry Andric     RecVec CheckUnits =
181259d6cff9SDimitry Andric         PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
181359d6cff9SDimitry Andric     for (unsigned j = i + 1; j < e; ++j) {
181459d6cff9SDimitry Andric       if (!PM.ProcResourceDefs[j]->isSubClassOf("ProcResGroup"))
181559d6cff9SDimitry Andric         continue;
181659d6cff9SDimitry Andric       RecVec OtherUnits =
181759d6cff9SDimitry Andric           PM.ProcResourceDefs[j]->getValueAsListOfDefs("Resources");
181859d6cff9SDimitry Andric       if (std::find_first_of(CheckUnits.begin(), CheckUnits.end(),
1819ac9a064cSDimitry Andric                              OtherUnits.begin(),
1820ac9a064cSDimitry Andric                              OtherUnits.end()) != CheckUnits.end()) {
182159d6cff9SDimitry Andric         // CheckUnits and OtherUnits overlap
1822b60736ecSDimitry Andric         llvm::append_range(OtherUnits, CheckUnits);
182359d6cff9SDimitry Andric         if (!hasSuperGroup(OtherUnits, PM)) {
182459d6cff9SDimitry Andric           PrintFatalError((PM.ProcResourceDefs[i])->getLoc(),
1825ac9a064cSDimitry Andric                           "proc resource group overlaps with " +
1826ac9a064cSDimitry Andric                               PM.ProcResourceDefs[j]->getName() +
1827ac9a064cSDimitry Andric                               " but no supergroup contains both.");
182859d6cff9SDimitry Andric         }
182959d6cff9SDimitry Andric       }
183059d6cff9SDimitry Andric     }
183159d6cff9SDimitry Andric   }
183259d6cff9SDimitry Andric }
183359d6cff9SDimitry Andric 
1834eb11fae6SDimitry Andric // Collect all the RegisterFile definitions available in this target.
collectRegisterFiles()1835eb11fae6SDimitry Andric void CodeGenSchedModels::collectRegisterFiles() {
1836eb11fae6SDimitry Andric   RecVec RegisterFileDefs = Records.getAllDerivedDefinitions("RegisterFile");
1837eb11fae6SDimitry Andric 
1838eb11fae6SDimitry Andric   // RegisterFiles is the vector of CodeGenRegisterFile.
1839eb11fae6SDimitry Andric   for (Record *RF : RegisterFileDefs) {
1840eb11fae6SDimitry Andric     // For each register file definition, construct a CodeGenRegisterFile object
1841eb11fae6SDimitry Andric     // and add it to the appropriate scheduling model.
1842eb11fae6SDimitry Andric     CodeGenProcModel &PM = getProcModel(RF->getValueAsDef("SchedModel"));
1843eb11fae6SDimitry Andric     PM.RegisterFiles.emplace_back(CodeGenRegisterFile(RF->getName(), RF));
1844eb11fae6SDimitry Andric     CodeGenRegisterFile &CGRF = PM.RegisterFiles.back();
1845d8e91e46SDimitry Andric     CGRF.MaxMovesEliminatedPerCycle =
1846d8e91e46SDimitry Andric         RF->getValueAsInt("MaxMovesEliminatedPerCycle");
1847d8e91e46SDimitry Andric     CGRF.AllowZeroMoveEliminationOnly =
1848d8e91e46SDimitry Andric         RF->getValueAsBit("AllowZeroMoveEliminationOnly");
1849eb11fae6SDimitry Andric 
1850eb11fae6SDimitry Andric     // Now set the number of physical registers as well as the cost of registers
1851eb11fae6SDimitry Andric     // in each register class.
1852eb11fae6SDimitry Andric     CGRF.NumPhysRegs = RF->getValueAsInt("NumPhysRegs");
1853d8e91e46SDimitry Andric     if (!CGRF.NumPhysRegs) {
1854d8e91e46SDimitry Andric       PrintFatalError(RF->getLoc(),
1855d8e91e46SDimitry Andric                       "Invalid RegisterFile with zero physical registers");
1856eb11fae6SDimitry Andric     }
1857eb11fae6SDimitry Andric 
1858d8e91e46SDimitry Andric     RecVec RegisterClasses = RF->getValueAsListOfDefs("RegClasses");
1859d8e91e46SDimitry Andric     std::vector<int64_t> RegisterCosts = RF->getValueAsListOfInts("RegCosts");
1860d8e91e46SDimitry Andric     ListInit *MoveElimInfo = RF->getValueAsListInit("AllowMoveElimination");
1861d8e91e46SDimitry Andric     for (unsigned I = 0, E = RegisterClasses.size(); I < E; ++I) {
1862d8e91e46SDimitry Andric       int Cost = RegisterCosts.size() > I ? RegisterCosts[I] : 1;
1863d8e91e46SDimitry Andric 
1864d8e91e46SDimitry Andric       bool AllowMoveElim = false;
1865d8e91e46SDimitry Andric       if (MoveElimInfo->size() > I) {
1866d8e91e46SDimitry Andric         BitInit *Val = cast<BitInit>(MoveElimInfo->getElement(I));
1867d8e91e46SDimitry Andric         AllowMoveElim = Val->getValue();
1868eb11fae6SDimitry Andric       }
1869d8e91e46SDimitry Andric 
1870d8e91e46SDimitry Andric       CGRF.Costs.emplace_back(RegisterClasses[I], Cost, AllowMoveElim);
1871eb11fae6SDimitry Andric     }
1872eb11fae6SDimitry Andric   }
1873eb11fae6SDimitry Andric }
1874eb11fae6SDimitry Andric 
1875522600a2SDimitry Andric // Collect and sort WriteRes, ReadAdvance, and ProcResources.
collectProcResources()1876522600a2SDimitry Andric void CodeGenSchedModels::collectProcResources() {
187701095a5dSDimitry Andric   ProcResourceDefs = Records.getAllDerivedDefinitions("ProcResourceUnits");
187801095a5dSDimitry Andric   ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
187901095a5dSDimitry Andric 
1880522600a2SDimitry Andric   // Add any subtarget-specific SchedReadWrites that are directly associated
1881522600a2SDimitry Andric   // with processor resources. Refer to the parent SchedClass's ProcIndices to
1882522600a2SDimitry Andric   // determine which processors they apply to.
1883eb11fae6SDimitry Andric   for (const CodeGenSchedClass &SC :
1884eb11fae6SDimitry Andric        make_range(schedClassBegin(), schedClassEnd())) {
1885eb11fae6SDimitry Andric     if (SC.ItinClassDef) {
1886eb11fae6SDimitry Andric       collectItinProcResources(SC.ItinClassDef);
1887eb11fae6SDimitry Andric       continue;
1888eb11fae6SDimitry Andric     }
1889eb11fae6SDimitry Andric 
18904a16efa3SDimitry Andric     // This class may have a default ReadWrite list which can be overriden by
18914a16efa3SDimitry Andric     // InstRW definitions.
1892eb11fae6SDimitry Andric     for (Record *RW : SC.InstRWs) {
1893eb11fae6SDimitry Andric       Record *RWModelDef = RW->getValueAsDef("SchedModel");
1894eb11fae6SDimitry Andric       unsigned PIdx = getProcModel(RWModelDef).Index;
18954a16efa3SDimitry Andric       IdxVec Writes, Reads;
1896eb11fae6SDimitry Andric       findRWs(RW->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1897eb11fae6SDimitry Andric       collectRWResources(Writes, Reads, PIdx);
18984a16efa3SDimitry Andric     }
1899eb11fae6SDimitry Andric 
1900eb11fae6SDimitry Andric     collectRWResources(SC.Writes, SC.Reads, SC.ProcIndices);
19014a16efa3SDimitry Andric   }
1902522600a2SDimitry Andric   // Add resources separately defined by each subtarget.
1903522600a2SDimitry Andric   RecVec WRDefs = Records.getAllDerivedDefinitions("WriteRes");
1904044eb2f6SDimitry Andric   for (Record *WR : WRDefs) {
1905044eb2f6SDimitry Andric     Record *ModelDef = WR->getValueAsDef("SchedModel");
1906044eb2f6SDimitry Andric     addWriteRes(WR, getProcModel(ModelDef).Index);
1907522600a2SDimitry Andric   }
19085ca98fd9SDimitry Andric   RecVec SWRDefs = Records.getAllDerivedDefinitions("SchedWriteRes");
1909044eb2f6SDimitry Andric   for (Record *SWR : SWRDefs) {
1910044eb2f6SDimitry Andric     Record *ModelDef = SWR->getValueAsDef("SchedModel");
1911044eb2f6SDimitry Andric     addWriteRes(SWR, getProcModel(ModelDef).Index);
19125ca98fd9SDimitry Andric   }
1913522600a2SDimitry Andric   RecVec RADefs = Records.getAllDerivedDefinitions("ReadAdvance");
1914044eb2f6SDimitry Andric   for (Record *RA : RADefs) {
1915044eb2f6SDimitry Andric     Record *ModelDef = RA->getValueAsDef("SchedModel");
1916044eb2f6SDimitry Andric     addReadAdvance(RA, getProcModel(ModelDef).Index);
1917522600a2SDimitry Andric   }
19185ca98fd9SDimitry Andric   RecVec SRADefs = Records.getAllDerivedDefinitions("SchedReadAdvance");
1919044eb2f6SDimitry Andric   for (Record *SRA : SRADefs) {
1920044eb2f6SDimitry Andric     if (SRA->getValueInit("SchedModel")->isComplete()) {
1921044eb2f6SDimitry Andric       Record *ModelDef = SRA->getValueAsDef("SchedModel");
1922044eb2f6SDimitry Andric       addReadAdvance(SRA, getProcModel(ModelDef).Index);
19235ca98fd9SDimitry Andric     }
19245ca98fd9SDimitry Andric   }
1925f8af5cf6SDimitry Andric   // Add ProcResGroups that are defined within this processor model, which may
1926f8af5cf6SDimitry Andric   // not be directly referenced but may directly specify a buffer size.
1927f8af5cf6SDimitry Andric   RecVec ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
1928044eb2f6SDimitry Andric   for (Record *PRG : ProcResGroups) {
1929044eb2f6SDimitry Andric     if (!PRG->getValueInit("SchedModel")->isComplete())
1930f8af5cf6SDimitry Andric       continue;
1931044eb2f6SDimitry Andric     CodeGenProcModel &PM = getProcModel(PRG->getValueAsDef("SchedModel"));
1932044eb2f6SDimitry Andric     if (!is_contained(PM.ProcResourceDefs, PRG))
1933044eb2f6SDimitry Andric       PM.ProcResourceDefs.push_back(PRG);
1934f8af5cf6SDimitry Andric   }
1935eb11fae6SDimitry Andric   // Add ProcResourceUnits unconditionally.
1936eb11fae6SDimitry Andric   for (Record *PRU : Records.getAllDerivedDefinitions("ProcResourceUnits")) {
1937eb11fae6SDimitry Andric     if (!PRU->getValueInit("SchedModel")->isComplete())
1938eb11fae6SDimitry Andric       continue;
1939eb11fae6SDimitry Andric     CodeGenProcModel &PM = getProcModel(PRU->getValueAsDef("SchedModel"));
1940eb11fae6SDimitry Andric     if (!is_contained(PM.ProcResourceDefs, PRU))
1941eb11fae6SDimitry Andric       PM.ProcResourceDefs.push_back(PRU);
1942eb11fae6SDimitry Andric   }
1943522600a2SDimitry Andric   // Finalize each ProcModel by sorting the record arrays.
194467c32a98SDimitry Andric   for (CodeGenProcModel &PM : ProcModels) {
1945d8e91e46SDimitry Andric     llvm::sort(PM.WriteResDefs, LessRecord());
1946d8e91e46SDimitry Andric     llvm::sort(PM.ReadAdvanceDefs, LessRecord());
1947d8e91e46SDimitry Andric     llvm::sort(PM.ProcResourceDefs, LessRecord());
1948eb11fae6SDimitry Andric     LLVM_DEBUG(
1949344a3780SDimitry Andric         PM.dump(); dbgs() << "WriteResDefs: "; for (auto WriteResDef
1950344a3780SDimitry Andric                                                     : PM.WriteResDefs) {
1951344a3780SDimitry Andric           if (WriteResDef->isSubClassOf("WriteRes"))
1952344a3780SDimitry Andric             dbgs() << WriteResDef->getValueAsDef("WriteType")->getName() << " ";
1953522600a2SDimitry Andric           else
1954344a3780SDimitry Andric             dbgs() << WriteResDef->getName() << " ";
1955eb11fae6SDimitry Andric         } dbgs() << "\nReadAdvanceDefs: ";
1956344a3780SDimitry Andric         for (Record *ReadAdvanceDef
1957344a3780SDimitry Andric              : PM.ReadAdvanceDefs) {
1958344a3780SDimitry Andric           if (ReadAdvanceDef->isSubClassOf("ReadAdvance"))
1959344a3780SDimitry Andric             dbgs() << ReadAdvanceDef->getValueAsDef("ReadType")->getName()
1960344a3780SDimitry Andric                    << " ";
1961522600a2SDimitry Andric           else
1962344a3780SDimitry Andric             dbgs() << ReadAdvanceDef->getName() << " ";
1963eb11fae6SDimitry Andric         } dbgs()
1964eb11fae6SDimitry Andric         << "\nProcResourceDefs: ";
1965344a3780SDimitry Andric         for (Record *ProcResourceDef
1966344a3780SDimitry Andric              : PM.ProcResourceDefs) {
1967344a3780SDimitry Andric           dbgs() << ProcResourceDef->getName() << " ";
1968344a3780SDimitry Andric         } dbgs()
1969eb11fae6SDimitry Andric         << '\n');
197059d6cff9SDimitry Andric     verifyProcResourceGroups(PM);
1971522600a2SDimitry Andric   }
197201095a5dSDimitry Andric 
197301095a5dSDimitry Andric   ProcResourceDefs.clear();
197401095a5dSDimitry Andric   ProcResGroups.clear();
197501095a5dSDimitry Andric }
197601095a5dSDimitry Andric 
checkCompleteness()197701095a5dSDimitry Andric void CodeGenSchedModels::checkCompleteness() {
197801095a5dSDimitry Andric   bool Complete = true;
197901095a5dSDimitry Andric   for (const CodeGenProcModel &ProcModel : procModels()) {
1980eb11fae6SDimitry Andric     const bool HasItineraries = ProcModel.hasItineraries();
198101095a5dSDimitry Andric     if (!ProcModel.ModelDef->getValueAsBit("CompleteModel"))
198201095a5dSDimitry Andric       continue;
198301095a5dSDimitry Andric     for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
198401095a5dSDimitry Andric       if (Inst->hasNoSchedulingInfo)
198501095a5dSDimitry Andric         continue;
198601095a5dSDimitry Andric       if (ProcModel.isUnsupported(*Inst))
198701095a5dSDimitry Andric         continue;
198801095a5dSDimitry Andric       unsigned SCIdx = getSchedClassIdx(*Inst);
198901095a5dSDimitry Andric       if (!SCIdx) {
1990ecbca9f5SDimitry Andric         if (Inst->TheDef->isValueUnset("SchedRW")) {
1991e6d15924SDimitry Andric           PrintError(Inst->TheDef->getLoc(),
1992e6d15924SDimitry Andric                      "No schedule information for instruction '" +
1993e6d15924SDimitry Andric                          Inst->TheDef->getName() + "' in SchedMachineModel '" +
1994e6d15924SDimitry Andric                          ProcModel.ModelDef->getName() + "'");
199501095a5dSDimitry Andric           Complete = false;
199601095a5dSDimitry Andric         }
199701095a5dSDimitry Andric         continue;
199801095a5dSDimitry Andric       }
199901095a5dSDimitry Andric 
200001095a5dSDimitry Andric       const CodeGenSchedClass &SC = getSchedClass(SCIdx);
200101095a5dSDimitry Andric       if (!SC.Writes.empty())
200201095a5dSDimitry Andric         continue;
2003eb11fae6SDimitry Andric       if (HasItineraries && SC.ItinClassDef != nullptr &&
2004b915e9e0SDimitry Andric           SC.ItinClassDef->getName() != "NoItinerary")
200501095a5dSDimitry Andric         continue;
200601095a5dSDimitry Andric 
200701095a5dSDimitry Andric       const RecVec &InstRWs = SC.InstRWs;
2008b915e9e0SDimitry Andric       auto I = find_if(InstRWs, [&ProcModel](const Record *R) {
2009b915e9e0SDimitry Andric         return R->getValueAsDef("SchedModel") == ProcModel.ModelDef;
201001095a5dSDimitry Andric       });
201101095a5dSDimitry Andric       if (I == InstRWs.end()) {
2012e6d15924SDimitry Andric         PrintError(Inst->TheDef->getLoc(), "'" + ProcModel.ModelName +
2013e6d15924SDimitry Andric                                                "' lacks information for '" +
201401095a5dSDimitry Andric                                                Inst->TheDef->getName() + "'");
201501095a5dSDimitry Andric         Complete = false;
201601095a5dSDimitry Andric       }
201701095a5dSDimitry Andric     }
201801095a5dSDimitry Andric   }
201901095a5dSDimitry Andric   if (!Complete) {
2020ac9a064cSDimitry Andric     errs()
2021ac9a064cSDimitry Andric         << "\n\nIncomplete schedule models found.\n"
2022ac9a064cSDimitry Andric         << "- Consider setting 'CompleteModel = 0' while developing new "
2023ac9a064cSDimitry Andric            "models.\n"
2024ac9a064cSDimitry Andric         << "- Pseudo instructions can be marked with 'hasNoSchedulingInfo = "
2025ac9a064cSDimitry Andric            "1'.\n"
202601095a5dSDimitry Andric         << "- Instructions should usually have Sched<[...]> as a superclass, "
202701095a5dSDimitry Andric            "you may temporarily use an empty list.\n"
2028ac9a064cSDimitry Andric         << "- Instructions related to unsupported features can be excluded "
2029ac9a064cSDimitry Andric            "with "
203001095a5dSDimitry Andric            "list<Predicate> UnsupportedFeatures = [HasA,..,HasY]; in the "
203101095a5dSDimitry Andric            "processor model.\n\n";
203201095a5dSDimitry Andric     PrintFatalError("Incomplete schedule model");
203301095a5dSDimitry Andric   }
2034522600a2SDimitry Andric }
2035522600a2SDimitry Andric 
2036522600a2SDimitry Andric // Collect itinerary class resources for each processor.
collectItinProcResources(Record * ItinClassDef)2037522600a2SDimitry Andric void CodeGenSchedModels::collectItinProcResources(Record *ItinClassDef) {
2038522600a2SDimitry Andric   for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
2039522600a2SDimitry Andric     const CodeGenProcModel &PM = ProcModels[PIdx];
2040522600a2SDimitry Andric     // For all ItinRW entries.
2041522600a2SDimitry Andric     bool HasMatch = false;
2042ac9a064cSDimitry Andric     for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end(); II != IE;
2043ac9a064cSDimitry Andric          ++II) {
2044522600a2SDimitry Andric       RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
2045b60736ecSDimitry Andric       if (!llvm::is_contained(Matched, ItinClassDef))
2046522600a2SDimitry Andric         continue;
2047522600a2SDimitry Andric       if (HasMatch)
2048ac9a064cSDimitry Andric         PrintFatalError((*II)->getLoc(),
2049ac9a064cSDimitry Andric                         "Duplicate itinerary class " + ItinClassDef->getName() +
2050ac9a064cSDimitry Andric                             " in ItinResources for " + PM.ModelName);
2051522600a2SDimitry Andric       HasMatch = true;
2052522600a2SDimitry Andric       IdxVec Writes, Reads;
2053522600a2SDimitry Andric       findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
2054eb11fae6SDimitry Andric       collectRWResources(Writes, Reads, PIdx);
2055522600a2SDimitry Andric     }
2056522600a2SDimitry Andric   }
2057522600a2SDimitry Andric }
2058522600a2SDimitry Andric 
collectRWResources(unsigned RWIdx,bool IsRead,ArrayRef<unsigned> ProcIndices)2059522600a2SDimitry Andric void CodeGenSchedModels::collectRWResources(unsigned RWIdx, bool IsRead,
2060dd58ef01SDimitry Andric                                             ArrayRef<unsigned> ProcIndices) {
2061522600a2SDimitry Andric   const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
2062522600a2SDimitry Andric   if (SchedRW.TheDef) {
2063522600a2SDimitry Andric     if (!IsRead && SchedRW.TheDef->isSubClassOf("SchedWriteRes")) {
2064dd58ef01SDimitry Andric       for (unsigned Idx : ProcIndices)
2065dd58ef01SDimitry Andric         addWriteRes(SchedRW.TheDef, Idx);
2066ac9a064cSDimitry Andric     } else if (IsRead && SchedRW.TheDef->isSubClassOf("SchedReadAdvance")) {
2067dd58ef01SDimitry Andric       for (unsigned Idx : ProcIndices)
2068dd58ef01SDimitry Andric         addReadAdvance(SchedRW.TheDef, Idx);
2069522600a2SDimitry Andric     }
2070522600a2SDimitry Andric   }
2071344a3780SDimitry Andric   for (auto *Alias : SchedRW.Aliases) {
2072522600a2SDimitry Andric     IdxVec AliasProcIndices;
2073344a3780SDimitry Andric     if (Alias->getValueInit("SchedModel")->isComplete()) {
2074522600a2SDimitry Andric       AliasProcIndices.push_back(
2075344a3780SDimitry Andric           getProcModel(Alias->getValueAsDef("SchedModel")).Index);
2076344a3780SDimitry Andric     } else
2077522600a2SDimitry Andric       AliasProcIndices = ProcIndices;
2078344a3780SDimitry Andric     const CodeGenSchedRW &AliasRW = getSchedRW(Alias->getValueAsDef("AliasRW"));
2079522600a2SDimitry Andric     assert(AliasRW.IsRead == IsRead && "cannot alias reads to writes");
2080522600a2SDimitry Andric 
2081522600a2SDimitry Andric     IdxVec ExpandedRWs;
2082522600a2SDimitry Andric     expandRWSequence(AliasRW.Index, ExpandedRWs, IsRead);
2083344a3780SDimitry Andric     for (unsigned int ExpandedRW : ExpandedRWs) {
2084344a3780SDimitry Andric       collectRWResources(ExpandedRW, IsRead, AliasProcIndices);
2085522600a2SDimitry Andric     }
2086522600a2SDimitry Andric   }
2087522600a2SDimitry Andric }
2088522600a2SDimitry Andric 
2089522600a2SDimitry Andric // Collect resources for a set of read/write types and processor indices.
collectRWResources(ArrayRef<unsigned> Writes,ArrayRef<unsigned> Reads,ArrayRef<unsigned> ProcIndices)2090dd58ef01SDimitry Andric void CodeGenSchedModels::collectRWResources(ArrayRef<unsigned> Writes,
2091dd58ef01SDimitry Andric                                             ArrayRef<unsigned> Reads,
2092dd58ef01SDimitry Andric                                             ArrayRef<unsigned> ProcIndices) {
2093dd58ef01SDimitry Andric   for (unsigned Idx : Writes)
2094dd58ef01SDimitry Andric     collectRWResources(Idx, /*IsRead=*/false, ProcIndices);
2095522600a2SDimitry Andric 
2096dd58ef01SDimitry Andric   for (unsigned Idx : Reads)
2097dd58ef01SDimitry Andric     collectRWResources(Idx, /*IsRead=*/true, ProcIndices);
2098522600a2SDimitry Andric }
2099522600a2SDimitry Andric 
2100522600a2SDimitry Andric // Find the processor's resource units for this kind of resource.
findProcResUnits(Record * ProcResKind,const CodeGenProcModel & PM,ArrayRef<SMLoc> Loc) const2101522600a2SDimitry Andric Record *CodeGenSchedModels::findProcResUnits(Record *ProcResKind,
2102044eb2f6SDimitry Andric                                              const CodeGenProcModel &PM,
2103044eb2f6SDimitry Andric                                              ArrayRef<SMLoc> Loc) const {
2104522600a2SDimitry Andric   if (ProcResKind->isSubClassOf("ProcResourceUnits"))
2105522600a2SDimitry Andric     return ProcResKind;
2106522600a2SDimitry Andric 
21075ca98fd9SDimitry Andric   Record *ProcUnitDef = nullptr;
210801095a5dSDimitry Andric   assert(!ProcResourceDefs.empty());
210901095a5dSDimitry Andric   assert(!ProcResGroups.empty());
2110522600a2SDimitry Andric 
2111044eb2f6SDimitry Andric   for (Record *ProcResDef : ProcResourceDefs) {
2112ac9a064cSDimitry Andric     if (ProcResDef->getValueAsDef("Kind") == ProcResKind &&
2113ac9a064cSDimitry Andric         ProcResDef->getValueAsDef("SchedModel") == PM.ModelDef) {
2114522600a2SDimitry Andric       if (ProcUnitDef) {
2115044eb2f6SDimitry Andric         PrintFatalError(Loc,
2116ac9a064cSDimitry Andric                         "Multiple ProcessorResourceUnits associated with " +
2117ac9a064cSDimitry Andric                             ProcResKind->getName());
2118522600a2SDimitry Andric       }
2119044eb2f6SDimitry Andric       ProcUnitDef = ProcResDef;
2120522600a2SDimitry Andric     }
2121522600a2SDimitry Andric   }
2122044eb2f6SDimitry Andric   for (Record *ProcResGroup : ProcResGroups) {
2123ac9a064cSDimitry Andric     if (ProcResGroup == ProcResKind &&
2124ac9a064cSDimitry Andric         ProcResGroup->getValueAsDef("SchedModel") == PM.ModelDef) {
21254a16efa3SDimitry Andric       if (ProcUnitDef) {
2126044eb2f6SDimitry Andric         PrintFatalError(Loc,
2127ac9a064cSDimitry Andric                         "Multiple ProcessorResourceUnits associated with " +
2128ac9a064cSDimitry Andric                             ProcResKind->getName());
21294a16efa3SDimitry Andric       }
2130044eb2f6SDimitry Andric       ProcUnitDef = ProcResGroup;
21314a16efa3SDimitry Andric     }
21324a16efa3SDimitry Andric   }
2133522600a2SDimitry Andric   if (!ProcUnitDef) {
2134ac9a064cSDimitry Andric     PrintFatalError(Loc, "No ProcessorResources associated with " +
2135ac9a064cSDimitry Andric                              ProcResKind->getName());
2136522600a2SDimitry Andric   }
2137522600a2SDimitry Andric   return ProcUnitDef;
2138522600a2SDimitry Andric }
2139522600a2SDimitry Andric 
2140522600a2SDimitry Andric // Iteratively add a resource and its super resources.
addProcResource(Record * ProcResKind,CodeGenProcModel & PM,ArrayRef<SMLoc> Loc)2141522600a2SDimitry Andric void CodeGenSchedModels::addProcResource(Record *ProcResKind,
2142044eb2f6SDimitry Andric                                          CodeGenProcModel &PM,
2143044eb2f6SDimitry Andric                                          ArrayRef<SMLoc> Loc) {
2144b915e9e0SDimitry Andric   while (true) {
2145044eb2f6SDimitry Andric     Record *ProcResUnits = findProcResUnits(ProcResKind, PM, Loc);
2146522600a2SDimitry Andric 
2147522600a2SDimitry Andric     // See if this ProcResource is already associated with this processor.
2148b915e9e0SDimitry Andric     if (is_contained(PM.ProcResourceDefs, ProcResUnits))
2149522600a2SDimitry Andric       return;
2150522600a2SDimitry Andric 
2151522600a2SDimitry Andric     PM.ProcResourceDefs.push_back(ProcResUnits);
21524a16efa3SDimitry Andric     if (ProcResUnits->isSubClassOf("ProcResGroup"))
21534a16efa3SDimitry Andric       return;
21544a16efa3SDimitry Andric 
2155522600a2SDimitry Andric     if (!ProcResUnits->getValueInit("Super")->isComplete())
2156522600a2SDimitry Andric       return;
2157522600a2SDimitry Andric 
2158522600a2SDimitry Andric     ProcResKind = ProcResUnits->getValueAsDef("Super");
2159522600a2SDimitry Andric   }
2160522600a2SDimitry Andric }
2161522600a2SDimitry Andric 
2162522600a2SDimitry Andric // Add resources for a SchedWrite to this processor if they don't exist.
addWriteRes(Record * ProcWriteResDef,unsigned PIdx)2163522600a2SDimitry Andric void CodeGenSchedModels::addWriteRes(Record *ProcWriteResDef, unsigned PIdx) {
2164522600a2SDimitry Andric   assert(PIdx && "don't add resources to an invalid Processor model");
2165522600a2SDimitry Andric 
2166522600a2SDimitry Andric   RecVec &WRDefs = ProcModels[PIdx].WriteResDefs;
2167b915e9e0SDimitry Andric   if (is_contained(WRDefs, ProcWriteResDef))
2168522600a2SDimitry Andric     return;
2169522600a2SDimitry Andric   WRDefs.push_back(ProcWriteResDef);
2170522600a2SDimitry Andric 
2171522600a2SDimitry Andric   // Visit ProcResourceKinds referenced by the newly discovered WriteRes.
2172522600a2SDimitry Andric   RecVec ProcResDefs = ProcWriteResDef->getValueAsListOfDefs("ProcResources");
2173344a3780SDimitry Andric   for (auto *ProcResDef : ProcResDefs) {
2174344a3780SDimitry Andric     addProcResource(ProcResDef, ProcModels[PIdx], ProcWriteResDef->getLoc());
2175522600a2SDimitry Andric   }
2176522600a2SDimitry Andric }
2177522600a2SDimitry Andric 
2178522600a2SDimitry Andric // Add resources for a ReadAdvance to this processor if they don't exist.
addReadAdvance(Record * ProcReadAdvanceDef,unsigned PIdx)2179522600a2SDimitry Andric void CodeGenSchedModels::addReadAdvance(Record *ProcReadAdvanceDef,
2180522600a2SDimitry Andric                                         unsigned PIdx) {
2181ac9a064cSDimitry Andric   for (const Record *ValidWrite :
2182ac9a064cSDimitry Andric        ProcReadAdvanceDef->getValueAsListOfDefs("ValidWrites"))
2183ac9a064cSDimitry Andric     if (getSchedRWIdx(ValidWrite, /*IsRead=*/false) == 0)
2184ac9a064cSDimitry Andric       PrintFatalError(
2185ac9a064cSDimitry Andric           ProcReadAdvanceDef->getLoc(),
2186ac9a064cSDimitry Andric           "ReadAdvance referencing a ValidWrite that is not used by "
2187ac9a064cSDimitry Andric           "any instruction (" +
2188ac9a064cSDimitry Andric               ValidWrite->getName() + ")");
2189ac9a064cSDimitry Andric 
2190522600a2SDimitry Andric   RecVec &RADefs = ProcModels[PIdx].ReadAdvanceDefs;
2191b915e9e0SDimitry Andric   if (is_contained(RADefs, ProcReadAdvanceDef))
2192522600a2SDimitry Andric     return;
2193522600a2SDimitry Andric   RADefs.push_back(ProcReadAdvanceDef);
2194522600a2SDimitry Andric }
2195522600a2SDimitry Andric 
getProcResourceIdx(Record * PRDef) const2196522600a2SDimitry Andric unsigned CodeGenProcModel::getProcResourceIdx(Record *PRDef) const {
2197b915e9e0SDimitry Andric   RecIter PRPos = find(ProcResourceDefs, PRDef);
2198522600a2SDimitry Andric   if (PRPos == ProcResourceDefs.end())
2199522600a2SDimitry Andric     PrintFatalError(PRDef->getLoc(), "ProcResource def is not included in "
2200ac9a064cSDimitry Andric                                      "the ProcResources list for " +
2201ac9a064cSDimitry Andric                                          ModelName);
2202522600a2SDimitry Andric   // Idx=0 is reserved for invalid.
2203522600a2SDimitry Andric   return 1 + (PRPos - ProcResourceDefs.begin());
2204522600a2SDimitry Andric }
2205522600a2SDimitry Andric 
isUnsupported(const CodeGenInstruction & Inst) const220601095a5dSDimitry Andric bool CodeGenProcModel::isUnsupported(const CodeGenInstruction &Inst) const {
220701095a5dSDimitry Andric   for (const Record *TheDef : UnsupportedFeaturesDefs) {
2208ac9a064cSDimitry Andric     for (const Record *PredDef :
2209ac9a064cSDimitry Andric          Inst.TheDef->getValueAsListOfDefs("Predicates")) {
221001095a5dSDimitry Andric       if (TheDef->getName() == PredDef->getName())
221101095a5dSDimitry Andric         return true;
221201095a5dSDimitry Andric     }
221301095a5dSDimitry Andric   }
221401095a5dSDimitry Andric   return false;
221501095a5dSDimitry Andric }
221601095a5dSDimitry Andric 
hasReadOfWrite(Record * WriteDef) const2217ac9a064cSDimitry Andric bool CodeGenProcModel::hasReadOfWrite(Record *WriteDef) const {
2218ac9a064cSDimitry Andric   for (auto &RADef : ReadAdvanceDefs) {
2219ac9a064cSDimitry Andric     RecVec ValidWrites = RADef->getValueAsListOfDefs("ValidWrites");
2220ac9a064cSDimitry Andric     if (is_contained(ValidWrites, WriteDef))
2221ac9a064cSDimitry Andric       return true;
2222ac9a064cSDimitry Andric   }
2223ac9a064cSDimitry Andric   return false;
2224ac9a064cSDimitry Andric }
2225ac9a064cSDimitry Andric 
2226522600a2SDimitry Andric #ifndef NDEBUG
dump() const2227522600a2SDimitry Andric void CodeGenProcModel::dump() const {
2228522600a2SDimitry Andric   dbgs() << Index << ": " << ModelName << " "
2229522600a2SDimitry Andric          << (ModelDef ? ModelDef->getName() : "inferred") << " "
2230522600a2SDimitry Andric          << (ItinsDef ? ItinsDef->getName() : "no itinerary") << '\n';
2231522600a2SDimitry Andric }
2232522600a2SDimitry Andric 
dump() const2233522600a2SDimitry Andric void CodeGenSchedRW::dump() const {
2234522600a2SDimitry Andric   dbgs() << Name << (IsVariadic ? " (V) " : " ");
2235522600a2SDimitry Andric   if (IsSequence) {
2236522600a2SDimitry Andric     dbgs() << "(";
2237522600a2SDimitry Andric     dumpIdxVec(Sequence);
2238522600a2SDimitry Andric     dbgs() << ")";
2239522600a2SDimitry Andric   }
2240522600a2SDimitry Andric }
2241522600a2SDimitry Andric 
dump(const CodeGenSchedModels * SchedModels) const2242522600a2SDimitry Andric void CodeGenSchedClass::dump(const CodeGenSchedModels *SchedModels) const {
2243ac9a064cSDimitry Andric   dbgs() << "SCHEDCLASS " << Index << ":" << Name << '\n' << "  Writes: ";
2244522600a2SDimitry Andric   for (unsigned i = 0, N = Writes.size(); i < N; ++i) {
2245522600a2SDimitry Andric     SchedModels->getSchedWrite(Writes[i]).dump();
2246522600a2SDimitry Andric     if (i < N - 1) {
2247522600a2SDimitry Andric       dbgs() << '\n';
2248522600a2SDimitry Andric       dbgs().indent(10);
2249522600a2SDimitry Andric     }
2250522600a2SDimitry Andric   }
2251522600a2SDimitry Andric   dbgs() << "\n  Reads: ";
2252522600a2SDimitry Andric   for (unsigned i = 0, N = Reads.size(); i < N; ++i) {
2253522600a2SDimitry Andric     SchedModels->getSchedRead(Reads[i]).dump();
2254522600a2SDimitry Andric     if (i < N - 1) {
2255522600a2SDimitry Andric       dbgs() << '\n';
2256522600a2SDimitry Andric       dbgs().indent(10);
2257522600a2SDimitry Andric     }
2258522600a2SDimitry Andric   }
2259ac9a064cSDimitry Andric   dbgs() << "\n  ProcIdx: ";
2260ac9a064cSDimitry Andric   dumpIdxVec(ProcIndices);
22614a16efa3SDimitry Andric   if (!Transitions.empty()) {
22624a16efa3SDimitry Andric     dbgs() << "\n Transitions for Proc ";
2263044eb2f6SDimitry Andric     for (const CodeGenSchedTransition &Transition : Transitions) {
2264b60736ecSDimitry Andric       dbgs() << Transition.ProcIndex << ", ";
22654a16efa3SDimitry Andric     }
22664a16efa3SDimitry Andric   }
2267b60736ecSDimitry Andric   dbgs() << '\n';
2268522600a2SDimitry Andric }
2269522600a2SDimitry Andric 
dump() const2270522600a2SDimitry Andric void PredTransitions::dump() const {
2271522600a2SDimitry Andric   dbgs() << "Expanded Variants:\n";
2272344a3780SDimitry Andric   for (const auto &TI : TransVec) {
2273522600a2SDimitry Andric     dbgs() << "{";
2274344a3780SDimitry Andric     ListSeparator LS;
2275344a3780SDimitry Andric     for (const PredCheck &PC : TI.PredTerm)
2276344a3780SDimitry Andric       dbgs() << LS << SchedModels.getSchedRW(PC.RWIdx, PC.IsRead).Name << ":"
2277344a3780SDimitry Andric              << PC.Predicate->getName();
2278522600a2SDimitry Andric     dbgs() << "},\n  => {";
2279522600a2SDimitry Andric     for (SmallVectorImpl<SmallVector<unsigned, 4>>::const_iterator
2280344a3780SDimitry Andric              WSI = TI.WriteSequences.begin(),
2281344a3780SDimitry Andric              WSE = TI.WriteSequences.end();
2282522600a2SDimitry Andric          WSI != WSE; ++WSI) {
2283522600a2SDimitry Andric       dbgs() << "(";
2284344a3780SDimitry Andric       ListSeparator LS;
2285344a3780SDimitry Andric       for (unsigned N : *WSI)
2286344a3780SDimitry Andric         dbgs() << LS << SchedModels.getSchedWrite(N).Name;
2287522600a2SDimitry Andric       dbgs() << "),";
2288522600a2SDimitry Andric     }
2289522600a2SDimitry Andric     dbgs() << "}\n";
2290522600a2SDimitry Andric   }
2291522600a2SDimitry Andric }
2292522600a2SDimitry Andric #endif // NDEBUG
2293