blob: a520afb13827d3e58d073bd219ec3ae1402661c3 [file] [log] [blame]
Andrew Trick87255e32012-07-07 04:00:00 +00001//===- CodeGenSchedule.cpp - Scheduling MachineModels ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Alp Tokercb402912014-01-24 17:20:08 +000010// This file defines structures to encapsulate the machine model as described in
Andrew Trick87255e32012-07-07 04:00:00 +000011// the target description.
12//
13//===----------------------------------------------------------------------===//
14
Andrew Trick87255e32012-07-07 04:00:00 +000015#include "CodeGenSchedule.h"
Benjamin Kramercbce2f02018-01-23 23:05:04 +000016#include "CodeGenInstruction.h"
Andrew Trick87255e32012-07-07 04:00:00 +000017#include "CodeGenTarget.h"
Craig Topperf19eacf2018-03-21 02:48:34 +000018#include "llvm/ADT/MapVector.h"
Benjamin Kramercbce2f02018-01-23 23:05:04 +000019#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000020#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallVector.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000023#include "llvm/Support/Casting.h"
Andrew Trick87255e32012-07-07 04:00:00 +000024#include "llvm/Support/Debug.h"
Andrew Trick9e1deb62012-10-03 23:06:32 +000025#include "llvm/Support/Regex.h"
Benjamin Kramercbce2f02018-01-23 23:05:04 +000026#include "llvm/Support/raw_ostream.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000027#include "llvm/TableGen/Error.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000028#include <algorithm>
29#include <iterator>
30#include <utility>
Andrew Trick87255e32012-07-07 04:00:00 +000031
32using namespace llvm;
33
Chandler Carruth97acce22014-04-22 03:06:00 +000034#define DEBUG_TYPE "subtarget-emitter"
35
Andrew Trick76686492012-09-15 00:19:57 +000036#ifndef NDEBUG
Benjamin Kramere1761952015-10-24 12:46:49 +000037static void dumpIdxVec(ArrayRef<unsigned> V) {
38 for (unsigned Idx : V)
39 dbgs() << Idx << ", ";
Andrew Trick33401e82012-09-15 00:19:59 +000040}
Andrew Trick76686492012-09-15 00:19:57 +000041#endif
42
Juergen Ributzka05c5a932013-11-19 03:08:35 +000043namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000044
Andrew Trick9e1deb62012-10-03 23:06:32 +000045// (instrs a, b, ...) Evaluate and union all arguments. Identical to AddOp.
46struct InstrsOp : public SetTheory::Operator {
Craig Topper716b0732014-03-05 05:17:42 +000047 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
48 ArrayRef<SMLoc> Loc) override {
Juergen Ributzka05c5a932013-11-19 03:08:35 +000049 ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts, Loc);
50 }
51};
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000052
Andrew Trick9e1deb62012-10-03 23:06:32 +000053// (instregex "OpcPat",...) Find all instructions matching an opcode pattern.
Andrew Trick9e1deb62012-10-03 23:06:32 +000054struct InstRegexOp : public SetTheory::Operator {
55 const CodeGenTarget &Target;
56 InstRegexOp(const CodeGenTarget &t): Target(t) {}
57
Benjamin Kramercbce2f02018-01-23 23:05:04 +000058 /// Remove any text inside of parentheses from S.
59 static std::string removeParens(llvm::StringRef S) {
60 std::string Result;
61 unsigned Paren = 0;
62 // NB: We don't care about escaped parens here.
63 for (char C : S) {
64 switch (C) {
65 case '(':
66 ++Paren;
67 break;
68 case ')':
69 --Paren;
70 break;
71 default:
72 if (Paren == 0)
73 Result += C;
74 }
75 }
76 return Result;
77 }
78
Juergen Ributzka05c5a932013-11-19 03:08:35 +000079 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
Craig Topper716b0732014-03-05 05:17:42 +000080 ArrayRef<SMLoc> Loc) override {
Javed Absarfc500042017-10-05 13:27:43 +000081 for (Init *Arg : make_range(Expr->arg_begin(), Expr->arg_end())) {
82 StringInit *SI = dyn_cast<StringInit>(Arg);
Juergen Ributzka05c5a932013-11-19 03:08:35 +000083 if (!SI)
Benjamin Kramercbce2f02018-01-23 23:05:04 +000084 PrintFatalError(Loc, "instregex requires pattern string: " +
85 Expr->getAsString());
Simon Pilgrim75cc2f92018-03-20 22:20:28 +000086 StringRef Original = SI->getValue();
87
Benjamin Kramercbce2f02018-01-23 23:05:04 +000088 // Extract a prefix that we can binary search on.
89 static const char RegexMetachars[] = "()^$|*+?.[]\\{}";
Simon Pilgrim75cc2f92018-03-20 22:20:28 +000090 auto FirstMeta = Original.find_first_of(RegexMetachars);
91
Benjamin Kramercbce2f02018-01-23 23:05:04 +000092 // Look for top-level | or ?. We cannot optimize them to binary search.
Simon Pilgrim75cc2f92018-03-20 22:20:28 +000093 if (removeParens(Original).find_first_of("|?") != std::string::npos)
Benjamin Kramercbce2f02018-01-23 23:05:04 +000094 FirstMeta = 0;
Simon Pilgrim75cc2f92018-03-20 22:20:28 +000095
96 Optional<Regex> Regexpr = None;
97 StringRef Prefix = Original.substr(0, FirstMeta);
Simon Pilgrim34d512e2018-03-24 21:04:20 +000098 StringRef PatStr = Original.substr(FirstMeta);
99 if (!PatStr.empty()) {
Simon Pilgrim75cc2f92018-03-20 22:20:28 +0000100 // For the rest use a python-style prefix match.
Simon Pilgrim34d512e2018-03-24 21:04:20 +0000101 std::string pat = PatStr;
Simon Pilgrim75cc2f92018-03-20 22:20:28 +0000102 if (pat[0] != '^') {
103 pat.insert(0, "^(");
104 pat.insert(pat.end(), ')');
105 }
106 Regexpr = Regex(pat);
Benjamin Kramercbce2f02018-01-23 23:05:04 +0000107 }
Simon Pilgrim75cc2f92018-03-20 22:20:28 +0000108
Simon Pilgrimd044f9c2018-03-25 19:20:08 +0000109 int NumMatches = 0;
110
Benjamin Kramer4890a712018-01-24 22:35:11 +0000111 unsigned NumGeneric = Target.getNumFixedInstructions();
Simon Pilgrim75cc2f92018-03-20 22:20:28 +0000112 ArrayRef<const CodeGenInstruction *> Generics =
113 Target.getInstructionsByEnumValue().slice(0, NumGeneric + 1);
114
Benjamin Kramercbce2f02018-01-23 23:05:04 +0000115 // The generic opcodes are unsorted, handle them manually.
Simon Pilgrim75cc2f92018-03-20 22:20:28 +0000116 for (auto *Inst : Generics) {
117 StringRef InstName = Inst->TheDef->getName();
118 if (InstName.startswith(Prefix) &&
Simon Pilgrimd044f9c2018-03-25 19:20:08 +0000119 (!Regexpr || Regexpr->match(InstName.substr(Prefix.size())))) {
Benjamin Kramercbce2f02018-01-23 23:05:04 +0000120 Elts.insert(Inst->TheDef);
Simon Pilgrimd044f9c2018-03-25 19:20:08 +0000121 NumMatches++;
122 }
Benjamin Kramercbce2f02018-01-23 23:05:04 +0000123 }
124
125 ArrayRef<const CodeGenInstruction *> Instructions =
Benjamin Kramer4890a712018-01-24 22:35:11 +0000126 Target.getInstructionsByEnumValue().slice(NumGeneric + 1);
Benjamin Kramercbce2f02018-01-23 23:05:04 +0000127
128 // Target instructions are sorted. Find the range that starts with our
129 // prefix.
130 struct Comp {
131 bool operator()(const CodeGenInstruction *LHS, StringRef RHS) {
132 return LHS->TheDef->getName() < RHS;
133 }
134 bool operator()(StringRef LHS, const CodeGenInstruction *RHS) {
135 return LHS < RHS->TheDef->getName() &&
136 !RHS->TheDef->getName().startswith(LHS);
137 }
138 };
139 auto Range = std::equal_range(Instructions.begin(), Instructions.end(),
Simon Pilgrim75cc2f92018-03-20 22:20:28 +0000140 Prefix, Comp());
Benjamin Kramercbce2f02018-01-23 23:05:04 +0000141
142 // For this range we know that it starts with the prefix. Check if there's
143 // a regex that needs to be checked.
144 for (auto *Inst : make_range(Range)) {
Simon Pilgrim75cc2f92018-03-20 22:20:28 +0000145 StringRef InstName = Inst->TheDef->getName();
Simon Pilgrimd044f9c2018-03-25 19:20:08 +0000146 if (!Regexpr || Regexpr->match(InstName.substr(Prefix.size()))) {
Craig Topper8a417c12014-12-09 08:05:51 +0000147 Elts.insert(Inst->TheDef);
Simon Pilgrimd044f9c2018-03-25 19:20:08 +0000148 NumMatches++;
149 }
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000150 }
Simon Pilgrimd044f9c2018-03-25 19:20:08 +0000151
152 if (0 == NumMatches)
153 PrintFatalError(Loc, "instregex has no matches: " + Original);
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000154 }
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000155 }
Andrew Trick9e1deb62012-10-03 23:06:32 +0000156};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000157
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000158} // end anonymous namespace
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000159
Andrew Trick76686492012-09-15 00:19:57 +0000160/// CodeGenModels ctor interprets machine model records and populates maps.
Andrew Trick87255e32012-07-07 04:00:00 +0000161CodeGenSchedModels::CodeGenSchedModels(RecordKeeper &RK,
162 const CodeGenTarget &TGT):
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000163 Records(RK), Target(TGT) {
Andrew Trick87255e32012-07-07 04:00:00 +0000164
Andrew Trick9e1deb62012-10-03 23:06:32 +0000165 Sets.addFieldExpander("InstRW", "Instrs");
166
167 // Allow Set evaluation to recognize the dags used in InstRW records:
168 // (instrs Op1, Op1...)
Craig Topperba6057d2015-04-24 06:49:44 +0000169 Sets.addOperator("instrs", llvm::make_unique<InstrsOp>());
170 Sets.addOperator("instregex", llvm::make_unique<InstRegexOp>(Target));
Andrew Trick9e1deb62012-10-03 23:06:32 +0000171
Andrew Trick76686492012-09-15 00:19:57 +0000172 // Instantiate a CodeGenProcModel for each SchedMachineModel with the values
173 // that are explicitly referenced in tablegen records. Resources associated
174 // with each processor will be derived later. Populate ProcModelMap with the
175 // CodeGenProcModel instances.
176 collectProcModels();
Andrew Trick87255e32012-07-07 04:00:00 +0000177
Andrew Trick76686492012-09-15 00:19:57 +0000178 // Instantiate a CodeGenSchedRW for each SchedReadWrite record explicitly
179 // defined, and populate SchedReads and SchedWrites vectors. Implicit
180 // SchedReadWrites that represent sequences derived from expanded variant will
181 // be inferred later.
182 collectSchedRW();
183
184 // Instantiate a CodeGenSchedClass for each unique SchedRW signature directly
185 // required by an instruction definition, and populate SchedClassIdxMap. Set
186 // NumItineraryClasses to the number of explicit itinerary classes referenced
187 // by instructions. Set NumInstrSchedClasses to the number of itinerary
188 // classes plus any classes implied by instructions that derive from class
189 // Sched and provide SchedRW list. This does not infer any new classes from
190 // SchedVariant.
191 collectSchedClasses();
192
193 // Find instruction itineraries for each processor. Sort and populate
Andrew Trick9257b8f2012-09-22 02:24:21 +0000194 // CodeGenProcModel::ItinDefList. (Cycle-to-cycle itineraries). This requires
Andrew Trick76686492012-09-15 00:19:57 +0000195 // all itinerary classes to be discovered.
196 collectProcItins();
197
198 // Find ItinRW records for each processor and itinerary class.
199 // (For per-operand resources mapped to itinerary classes).
200 collectProcItinRW();
Andrew Trick33401e82012-09-15 00:19:59 +0000201
Simon Dardis5f95c9a2016-06-24 08:43:27 +0000202 // Find UnsupportedFeatures records for each processor.
203 // (For per-operand resources mapped to itinerary classes).
204 collectProcUnsupportedFeatures();
205
Andrew Trick33401e82012-09-15 00:19:59 +0000206 // Infer new SchedClasses from SchedVariant.
207 inferSchedClasses();
208
Andrew Trick1e46d482012-09-15 00:20:02 +0000209 // Populate each CodeGenProcModel's WriteResDefs, ReadAdvanceDefs, and
210 // ProcResourceDefs.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000211 LLVM_DEBUG(
212 dbgs() << "\n+++ RESOURCE DEFINITIONS (collectProcResources) +++\n");
Andrew Trick1e46d482012-09-15 00:20:02 +0000213 collectProcResources();
Matthias Braun17cb5792016-03-01 20:03:21 +0000214
Andrea Di Biagioc74ad502018-04-05 15:41:41 +0000215 // Collect optional processor description.
216 collectOptionalProcessorInfo();
217
218 checkCompleteness();
219}
220
221void CodeGenSchedModels::collectRetireControlUnits() {
222 RecVec Units = Records.getAllDerivedDefinitions("RetireControlUnit");
223
224 for (Record *RCU : Units) {
225 CodeGenProcModel &PM = getProcModel(RCU->getValueAsDef("SchedModel"));
226 if (PM.RetireControlUnit) {
227 PrintError(RCU->getLoc(),
228 "Expected a single RetireControlUnit definition");
229 PrintNote(PM.RetireControlUnit->getLoc(),
230 "Previous definition of RetireControlUnit was here");
231 }
232 PM.RetireControlUnit = RCU;
233 }
234}
235
236/// Collect optional processor information.
237void CodeGenSchedModels::collectOptionalProcessorInfo() {
Andrea Di Biagio9da4d6d2018-04-03 13:36:24 +0000238 // Find register file definitions for each processor.
239 collectRegisterFiles();
240
Andrea Di Biagioc74ad502018-04-05 15:41:41 +0000241 // Collect processor RetireControlUnit descriptors if available.
242 collectRetireControlUnits();
Clement Courbetb4493792018-04-10 08:16:37 +0000243
244 // Find pfm counter definitions for each processor.
245 collectPfmCounters();
246
247 checkCompleteness();
Andrew Trick87255e32012-07-07 04:00:00 +0000248}
249
Andrew Trick76686492012-09-15 00:19:57 +0000250/// Gather all processor models.
251void CodeGenSchedModels::collectProcModels() {
252 RecVec ProcRecords = Records.getAllDerivedDefinitions("Processor");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000253 llvm::sort(ProcRecords.begin(), ProcRecords.end(), LessRecordFieldName());
Andrew Trick87255e32012-07-07 04:00:00 +0000254
Andrew Trick76686492012-09-15 00:19:57 +0000255 // Reserve space because we can. Reallocation would be ok.
256 ProcModels.reserve(ProcRecords.size()+1);
257
258 // Use idx=0 for NoModel/NoItineraries.
259 Record *NoModelDef = Records.getDef("NoSchedModel");
260 Record *NoItinsDef = Records.getDef("NoItineraries");
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000261 ProcModels.emplace_back(0, "NoSchedModel", NoModelDef, NoItinsDef);
Andrew Trick76686492012-09-15 00:19:57 +0000262 ProcModelMap[NoModelDef] = 0;
263
264 // For each processor, find a unique machine model.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000265 LLVM_DEBUG(dbgs() << "+++ PROCESSOR MODELs (addProcModel) +++\n");
Javed Absar67b042c2017-09-13 10:31:10 +0000266 for (Record *ProcRecord : ProcRecords)
267 addProcModel(ProcRecord);
Andrew Trick76686492012-09-15 00:19:57 +0000268}
269
270/// Get a unique processor model based on the defined MachineModel and
271/// ProcessorItineraries.
272void CodeGenSchedModels::addProcModel(Record *ProcDef) {
273 Record *ModelKey = getModelOrItinDef(ProcDef);
274 if (!ProcModelMap.insert(std::make_pair(ModelKey, ProcModels.size())).second)
275 return;
276
277 std::string Name = ModelKey->getName();
278 if (ModelKey->isSubClassOf("SchedMachineModel")) {
279 Record *ItinsDef = ModelKey->getValueAsDef("Itineraries");
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000280 ProcModels.emplace_back(ProcModels.size(), Name, ModelKey, ItinsDef);
Andrew Trick76686492012-09-15 00:19:57 +0000281 }
282 else {
283 // An itinerary is defined without a machine model. Infer a new model.
284 if (!ModelKey->getValueAsListOfDefs("IID").empty())
285 Name = Name + "Model";
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000286 ProcModels.emplace_back(ProcModels.size(), Name,
287 ProcDef->getValueAsDef("SchedModel"), ModelKey);
Andrew Trick76686492012-09-15 00:19:57 +0000288 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000289 LLVM_DEBUG(ProcModels.back().dump());
Andrew Trick76686492012-09-15 00:19:57 +0000290}
291
292// Recursively find all reachable SchedReadWrite records.
293static void scanSchedRW(Record *RWDef, RecVec &RWDefs,
294 SmallPtrSet<Record*, 16> &RWSet) {
David Blaikie70573dc2014-11-19 07:49:26 +0000295 if (!RWSet.insert(RWDef).second)
Andrew Trick76686492012-09-15 00:19:57 +0000296 return;
297 RWDefs.push_back(RWDef);
Javed Absar67b042c2017-09-13 10:31:10 +0000298 // Reads don't currently have sequence records, but it can be added later.
Andrew Trick76686492012-09-15 00:19:57 +0000299 if (RWDef->isSubClassOf("WriteSequence")) {
300 RecVec Seq = RWDef->getValueAsListOfDefs("Writes");
Javed Absar67b042c2017-09-13 10:31:10 +0000301 for (Record *WSRec : Seq)
302 scanSchedRW(WSRec, RWDefs, RWSet);
Andrew Trick76686492012-09-15 00:19:57 +0000303 }
304 else if (RWDef->isSubClassOf("SchedVariant")) {
305 // Visit each variant (guarded by a different predicate).
306 RecVec Vars = RWDef->getValueAsListOfDefs("Variants");
Javed Absar67b042c2017-09-13 10:31:10 +0000307 for (Record *Variant : Vars) {
Andrew Trick76686492012-09-15 00:19:57 +0000308 // Visit each RW in the sequence selected by the current variant.
Javed Absar67b042c2017-09-13 10:31:10 +0000309 RecVec Selected = Variant->getValueAsListOfDefs("Selected");
310 for (Record *SelDef : Selected)
311 scanSchedRW(SelDef, RWDefs, RWSet);
Andrew Trick76686492012-09-15 00:19:57 +0000312 }
313 }
314}
315
316// Collect and sort all SchedReadWrites reachable via tablegen records.
317// More may be inferred later when inferring new SchedClasses from variants.
318void CodeGenSchedModels::collectSchedRW() {
319 // Reserve idx=0 for invalid writes/reads.
320 SchedWrites.resize(1);
321 SchedReads.resize(1);
322
323 SmallPtrSet<Record*, 16> RWSet;
324
325 // Find all SchedReadWrites referenced by instruction defs.
326 RecVec SWDefs, SRDefs;
Craig Topper8cc904d2016-01-17 20:38:18 +0000327 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
Craig Topper8a417c12014-12-09 08:05:51 +0000328 Record *SchedDef = Inst->TheDef;
Jakob Stoklund Olesena4a361d2013-03-15 22:51:13 +0000329 if (SchedDef->isValueUnset("SchedRW"))
Andrew Trick76686492012-09-15 00:19:57 +0000330 continue;
331 RecVec RWs = SchedDef->getValueAsListOfDefs("SchedRW");
Javed Absar67b042c2017-09-13 10:31:10 +0000332 for (Record *RW : RWs) {
333 if (RW->isSubClassOf("SchedWrite"))
334 scanSchedRW(RW, SWDefs, RWSet);
Andrew Trick76686492012-09-15 00:19:57 +0000335 else {
Javed Absar67b042c2017-09-13 10:31:10 +0000336 assert(RW->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
337 scanSchedRW(RW, SRDefs, RWSet);
Andrew Trick76686492012-09-15 00:19:57 +0000338 }
339 }
340 }
341 // Find all ReadWrites referenced by InstRW.
342 RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
Javed Absar67b042c2017-09-13 10:31:10 +0000343 for (Record *InstRWDef : InstRWDefs) {
Andrew Trick76686492012-09-15 00:19:57 +0000344 // For all OperandReadWrites.
Javed Absar67b042c2017-09-13 10:31:10 +0000345 RecVec RWDefs = InstRWDef->getValueAsListOfDefs("OperandReadWrites");
346 for (Record *RWDef : RWDefs) {
347 if (RWDef->isSubClassOf("SchedWrite"))
348 scanSchedRW(RWDef, SWDefs, RWSet);
Andrew Trick76686492012-09-15 00:19:57 +0000349 else {
Javed Absar67b042c2017-09-13 10:31:10 +0000350 assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
351 scanSchedRW(RWDef, SRDefs, RWSet);
Andrew Trick76686492012-09-15 00:19:57 +0000352 }
353 }
354 }
355 // Find all ReadWrites referenced by ItinRW.
356 RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
Javed Absar67b042c2017-09-13 10:31:10 +0000357 for (Record *ItinRWDef : ItinRWDefs) {
Andrew Trick76686492012-09-15 00:19:57 +0000358 // For all OperandReadWrites.
Javed Absar67b042c2017-09-13 10:31:10 +0000359 RecVec RWDefs = ItinRWDef->getValueAsListOfDefs("OperandReadWrites");
360 for (Record *RWDef : RWDefs) {
361 if (RWDef->isSubClassOf("SchedWrite"))
362 scanSchedRW(RWDef, SWDefs, RWSet);
Andrew Trick76686492012-09-15 00:19:57 +0000363 else {
Javed Absar67b042c2017-09-13 10:31:10 +0000364 assert(RWDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
365 scanSchedRW(RWDef, SRDefs, RWSet);
Andrew Trick76686492012-09-15 00:19:57 +0000366 }
367 }
368 }
Andrew Trick9257b8f2012-09-22 02:24:21 +0000369 // Find all ReadWrites referenced by SchedAlias. AliasDefs needs to be sorted
370 // for the loop below that initializes Alias vectors.
371 RecVec AliasDefs = Records.getAllDerivedDefinitions("SchedAlias");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000372 llvm::sort(AliasDefs.begin(), AliasDefs.end(), LessRecord());
Javed Absar67b042c2017-09-13 10:31:10 +0000373 for (Record *ADef : AliasDefs) {
374 Record *MatchDef = ADef->getValueAsDef("MatchRW");
375 Record *AliasDef = ADef->getValueAsDef("AliasRW");
Andrew Trick9257b8f2012-09-22 02:24:21 +0000376 if (MatchDef->isSubClassOf("SchedWrite")) {
377 if (!AliasDef->isSubClassOf("SchedWrite"))
Javed Absar67b042c2017-09-13 10:31:10 +0000378 PrintFatalError(ADef->getLoc(), "SchedWrite Alias must be SchedWrite");
Andrew Trick9257b8f2012-09-22 02:24:21 +0000379 scanSchedRW(AliasDef, SWDefs, RWSet);
380 }
381 else {
382 assert(MatchDef->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
383 if (!AliasDef->isSubClassOf("SchedRead"))
Javed Absar67b042c2017-09-13 10:31:10 +0000384 PrintFatalError(ADef->getLoc(), "SchedRead Alias must be SchedRead");
Andrew Trick9257b8f2012-09-22 02:24:21 +0000385 scanSchedRW(AliasDef, SRDefs, RWSet);
386 }
387 }
Andrew Trick76686492012-09-15 00:19:57 +0000388 // Sort and add the SchedReadWrites directly referenced by instructions or
389 // itinerary resources. Index reads and writes in separate domains.
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000390 llvm::sort(SWDefs.begin(), SWDefs.end(), LessRecord());
Javed Absar67b042c2017-09-13 10:31:10 +0000391 for (Record *SWDef : SWDefs) {
392 assert(!getSchedRWIdx(SWDef, /*IsRead=*/false) && "duplicate SchedWrite");
393 SchedWrites.emplace_back(SchedWrites.size(), SWDef);
Andrew Trick76686492012-09-15 00:19:57 +0000394 }
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000395 llvm::sort(SRDefs.begin(), SRDefs.end(), LessRecord());
Javed Absar67b042c2017-09-13 10:31:10 +0000396 for (Record *SRDef : SRDefs) {
397 assert(!getSchedRWIdx(SRDef, /*IsRead-*/true) && "duplicate SchedWrite");
398 SchedReads.emplace_back(SchedReads.size(), SRDef);
Andrew Trick76686492012-09-15 00:19:57 +0000399 }
400 // Initialize WriteSequence vectors.
Javed Absar67b042c2017-09-13 10:31:10 +0000401 for (CodeGenSchedRW &CGRW : SchedWrites) {
402 if (!CGRW.IsSequence)
Andrew Trick76686492012-09-15 00:19:57 +0000403 continue;
Javed Absar67b042c2017-09-13 10:31:10 +0000404 findRWs(CGRW.TheDef->getValueAsListOfDefs("Writes"), CGRW.Sequence,
Andrew Trick76686492012-09-15 00:19:57 +0000405 /*IsRead=*/false);
406 }
Andrew Trick9257b8f2012-09-22 02:24:21 +0000407 // Initialize Aliases vectors.
Javed Absar67b042c2017-09-13 10:31:10 +0000408 for (Record *ADef : AliasDefs) {
409 Record *AliasDef = ADef->getValueAsDef("AliasRW");
Andrew Trick9257b8f2012-09-22 02:24:21 +0000410 getSchedRW(AliasDef).IsAlias = true;
Javed Absar67b042c2017-09-13 10:31:10 +0000411 Record *MatchDef = ADef->getValueAsDef("MatchRW");
Andrew Trick9257b8f2012-09-22 02:24:21 +0000412 CodeGenSchedRW &RW = getSchedRW(MatchDef);
413 if (RW.IsAlias)
Javed Absar67b042c2017-09-13 10:31:10 +0000414 PrintFatalError(ADef->getLoc(), "Cannot Alias an Alias");
415 RW.Aliases.push_back(ADef);
Andrew Trick9257b8f2012-09-22 02:24:21 +0000416 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000417 LLVM_DEBUG(
418 dbgs() << "\n+++ SCHED READS and WRITES (collectSchedRW) +++\n";
419 for (unsigned WIdx = 0, WEnd = SchedWrites.size(); WIdx != WEnd; ++WIdx) {
420 dbgs() << WIdx << ": ";
421 SchedWrites[WIdx].dump();
422 dbgs() << '\n';
423 } for (unsigned RIdx = 0, REnd = SchedReads.size(); RIdx != REnd;
424 ++RIdx) {
425 dbgs() << RIdx << ": ";
426 SchedReads[RIdx].dump();
427 dbgs() << '\n';
428 } RecVec RWDefs = Records.getAllDerivedDefinitions("SchedReadWrite");
429 for (Record *RWDef
430 : RWDefs) {
431 if (!getSchedRWIdx(RWDef, RWDef->isSubClassOf("SchedRead"))) {
432 StringRef Name = RWDef->getName();
433 if (Name != "NoWrite" && Name != "ReadDefault")
434 dbgs() << "Unused SchedReadWrite " << Name << '\n';
435 }
436 });
Andrew Trick76686492012-09-15 00:19:57 +0000437}
438
439/// Compute a SchedWrite name from a sequence of writes.
Benjamin Kramere1761952015-10-24 12:46:49 +0000440std::string CodeGenSchedModels::genRWName(ArrayRef<unsigned> Seq, bool IsRead) {
Andrew Trick76686492012-09-15 00:19:57 +0000441 std::string Name("(");
Benjamin Kramere1761952015-10-24 12:46:49 +0000442 for (auto I = Seq.begin(), E = Seq.end(); I != E; ++I) {
Andrew Trick76686492012-09-15 00:19:57 +0000443 if (I != Seq.begin())
444 Name += '_';
445 Name += getSchedRW(*I, IsRead).Name;
446 }
447 Name += ')';
448 return Name;
449}
450
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000451unsigned CodeGenSchedModels::getSchedRWIdx(const Record *Def,
452 bool IsRead) const {
Andrew Trick76686492012-09-15 00:19:57 +0000453 const std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000454 const auto I = find_if(
455 RWVec, [Def](const CodeGenSchedRW &RW) { return RW.TheDef == Def; });
456 return I == RWVec.end() ? 0 : std::distance(RWVec.begin(), I);
Andrew Trick76686492012-09-15 00:19:57 +0000457}
458
Andrew Trickcfe222c2012-09-19 04:43:19 +0000459bool CodeGenSchedModels::hasReadOfWrite(Record *WriteDef) const {
Javed Absar67b042c2017-09-13 10:31:10 +0000460 for (const CodeGenSchedRW &Read : SchedReads) {
461 Record *ReadDef = Read.TheDef;
Andrew Trickcfe222c2012-09-19 04:43:19 +0000462 if (!ReadDef || !ReadDef->isSubClassOf("ProcReadAdvance"))
463 continue;
464
465 RecVec ValidWrites = ReadDef->getValueAsListOfDefs("ValidWrites");
David Majnemer0d955d02016-08-11 22:21:41 +0000466 if (is_contained(ValidWrites, WriteDef)) {
Andrew Trickcfe222c2012-09-19 04:43:19 +0000467 return true;
468 }
469 }
470 return false;
471}
472
Craig Topper6f2cc9b2018-03-21 05:13:01 +0000473static void splitSchedReadWrites(const RecVec &RWDefs,
474 RecVec &WriteDefs, RecVec &ReadDefs) {
Javed Absar67b042c2017-09-13 10:31:10 +0000475 for (Record *RWDef : RWDefs) {
476 if (RWDef->isSubClassOf("SchedWrite"))
477 WriteDefs.push_back(RWDef);
Andrew Trick76686492012-09-15 00:19:57 +0000478 else {
Javed Absar67b042c2017-09-13 10:31:10 +0000479 assert(RWDef->isSubClassOf("SchedRead") && "unknown SchedReadWrite");
480 ReadDefs.push_back(RWDef);
Andrew Trick76686492012-09-15 00:19:57 +0000481 }
482 }
483}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000484
Andrew Trick76686492012-09-15 00:19:57 +0000485// Split the SchedReadWrites defs and call findRWs for each list.
486void CodeGenSchedModels::findRWs(const RecVec &RWDefs,
487 IdxVec &Writes, IdxVec &Reads) const {
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000488 RecVec WriteDefs;
489 RecVec ReadDefs;
490 splitSchedReadWrites(RWDefs, WriteDefs, ReadDefs);
491 findRWs(WriteDefs, Writes, false);
492 findRWs(ReadDefs, Reads, true);
Andrew Trick76686492012-09-15 00:19:57 +0000493}
494
495// Call getSchedRWIdx for all elements in a sequence of SchedRW defs.
496void CodeGenSchedModels::findRWs(const RecVec &RWDefs, IdxVec &RWs,
497 bool IsRead) const {
Javed Absar67b042c2017-09-13 10:31:10 +0000498 for (Record *RWDef : RWDefs) {
499 unsigned Idx = getSchedRWIdx(RWDef, IsRead);
Andrew Trick76686492012-09-15 00:19:57 +0000500 assert(Idx && "failed to collect SchedReadWrite");
501 RWs.push_back(Idx);
502 }
503}
504
Andrew Trick33401e82012-09-15 00:19:59 +0000505void CodeGenSchedModels::expandRWSequence(unsigned RWIdx, IdxVec &RWSeq,
506 bool IsRead) const {
507 const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
508 if (!SchedRW.IsSequence) {
509 RWSeq.push_back(RWIdx);
510 return;
511 }
512 int Repeat =
513 SchedRW.TheDef ? SchedRW.TheDef->getValueAsInt("Repeat") : 1;
514 for (int i = 0; i < Repeat; ++i) {
Javed Absar67b042c2017-09-13 10:31:10 +0000515 for (unsigned I : SchedRW.Sequence) {
516 expandRWSequence(I, RWSeq, IsRead);
Andrew Trick33401e82012-09-15 00:19:59 +0000517 }
518 }
519}
520
Andrew Trickda984b12012-10-03 23:06:28 +0000521// Expand a SchedWrite as a sequence following any aliases that coincide with
522// the given processor model.
523void CodeGenSchedModels::expandRWSeqForProc(
524 unsigned RWIdx, IdxVec &RWSeq, bool IsRead,
525 const CodeGenProcModel &ProcModel) const {
526
527 const CodeGenSchedRW &SchedWrite = getSchedRW(RWIdx, IsRead);
Craig Topper24064772014-04-15 07:20:03 +0000528 Record *AliasDef = nullptr;
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000529 for (const Record *Rec : SchedWrite.Aliases) {
530 const CodeGenSchedRW &AliasRW = getSchedRW(Rec->getValueAsDef("AliasRW"));
531 if (Rec->getValueInit("SchedModel")->isComplete()) {
532 Record *ModelDef = Rec->getValueAsDef("SchedModel");
Andrew Trickda984b12012-10-03 23:06:28 +0000533 if (&getProcModel(ModelDef) != &ProcModel)
534 continue;
535 }
536 if (AliasDef)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000537 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
538 "defined for processor " + ProcModel.ModelName +
539 " Ensure only one SchedAlias exists per RW.");
Andrew Trickda984b12012-10-03 23:06:28 +0000540 AliasDef = AliasRW.TheDef;
541 }
542 if (AliasDef) {
543 expandRWSeqForProc(getSchedRWIdx(AliasDef, IsRead),
544 RWSeq, IsRead,ProcModel);
545 return;
546 }
547 if (!SchedWrite.IsSequence) {
548 RWSeq.push_back(RWIdx);
549 return;
550 }
551 int Repeat =
552 SchedWrite.TheDef ? SchedWrite.TheDef->getValueAsInt("Repeat") : 1;
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000553 for (int I = 0, E = Repeat; I < E; ++I) {
554 for (unsigned Idx : SchedWrite.Sequence) {
555 expandRWSeqForProc(Idx, RWSeq, IsRead, ProcModel);
Andrew Trickda984b12012-10-03 23:06:28 +0000556 }
557 }
558}
559
Andrew Trick33401e82012-09-15 00:19:59 +0000560// Find the existing SchedWrite that models this sequence of writes.
Benjamin Kramere1761952015-10-24 12:46:49 +0000561unsigned CodeGenSchedModels::findRWForSequence(ArrayRef<unsigned> Seq,
Andrew Trick33401e82012-09-15 00:19:59 +0000562 bool IsRead) {
563 std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
564
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000565 auto I = find_if(RWVec, [Seq](CodeGenSchedRW &RW) {
566 return makeArrayRef(RW.Sequence) == Seq;
567 });
Andrew Trick33401e82012-09-15 00:19:59 +0000568 // Index zero reserved for invalid RW.
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000569 return I == RWVec.end() ? 0 : std::distance(RWVec.begin(), I);
Andrew Trick33401e82012-09-15 00:19:59 +0000570}
571
572/// Add this ReadWrite if it doesn't already exist.
573unsigned CodeGenSchedModels::findOrInsertRW(ArrayRef<unsigned> Seq,
574 bool IsRead) {
575 assert(!Seq.empty() && "cannot insert empty sequence");
576 if (Seq.size() == 1)
577 return Seq.back();
578
579 unsigned Idx = findRWForSequence(Seq, IsRead);
580 if (Idx)
581 return Idx;
582
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000583 std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
584 unsigned RWIdx = RWVec.size();
Andrew Trickda984b12012-10-03 23:06:28 +0000585 CodeGenSchedRW SchedRW(RWIdx, IsRead, Seq, genRWName(Seq, IsRead));
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000586 RWVec.push_back(SchedRW);
Andrew Trickda984b12012-10-03 23:06:28 +0000587 return RWIdx;
Andrew Trick33401e82012-09-15 00:19:59 +0000588}
589
Andrew Trick76686492012-09-15 00:19:57 +0000590/// Visit all the instruction definitions for this target to gather and
591/// enumerate the itinerary classes. These are the explicitly specified
592/// SchedClasses. More SchedClasses may be inferred.
593void CodeGenSchedModels::collectSchedClasses() {
594
595 // NoItinerary is always the first class at Idx=0
Craig Topper281a19c2018-03-22 06:15:08 +0000596 assert(SchedClasses.empty() && "Expected empty sched class");
597 SchedClasses.emplace_back(0, "NoInstrModel",
598 Records.getDef("NoItinerary"));
Andrew Trick76686492012-09-15 00:19:57 +0000599 SchedClasses.back().ProcIndices.push_back(0);
Andrew Trick87255e32012-07-07 04:00:00 +0000600
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000601 // Create a SchedClass for each unique combination of itinerary class and
602 // SchedRW list.
Craig Topper8cc904d2016-01-17 20:38:18 +0000603 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
Craig Topper8a417c12014-12-09 08:05:51 +0000604 Record *ItinDef = Inst->TheDef->getValueAsDef("Itinerary");
Andrew Trick76686492012-09-15 00:19:57 +0000605 IdxVec Writes, Reads;
Craig Topper8a417c12014-12-09 08:05:51 +0000606 if (!Inst->TheDef->isValueUnset("SchedRW"))
607 findRWs(Inst->TheDef->getValueAsListOfDefs("SchedRW"), Writes, Reads);
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000608
Andrew Trick76686492012-09-15 00:19:57 +0000609 // ProcIdx == 0 indicates the class applies to all processors.
Craig Topper281a19c2018-03-22 06:15:08 +0000610 unsigned SCIdx = addSchedClass(ItinDef, Writes, Reads, /*ProcIndices*/{0});
Craig Topper8a417c12014-12-09 08:05:51 +0000611 InstrClassMap[Inst->TheDef] = SCIdx;
Andrew Trick76686492012-09-15 00:19:57 +0000612 }
Andrew Trick9257b8f2012-09-22 02:24:21 +0000613 // Create classes for InstRW defs.
Andrew Trick76686492012-09-15 00:19:57 +0000614 RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000615 llvm::sort(InstRWDefs.begin(), InstRWDefs.end(), LessRecord());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000616 LLVM_DEBUG(dbgs() << "\n+++ SCHED CLASSES (createInstRWClass) +++\n");
Javed Absar67b042c2017-09-13 10:31:10 +0000617 for (Record *RWDef : InstRWDefs)
618 createInstRWClass(RWDef);
Andrew Trick87255e32012-07-07 04:00:00 +0000619
Andrew Trick76686492012-09-15 00:19:57 +0000620 NumInstrSchedClasses = SchedClasses.size();
Andrew Trick87255e32012-07-07 04:00:00 +0000621
Andrew Trick76686492012-09-15 00:19:57 +0000622 bool EnableDump = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000623 LLVM_DEBUG(EnableDump = true);
Andrew Trick76686492012-09-15 00:19:57 +0000624 if (!EnableDump)
Andrew Trick87255e32012-07-07 04:00:00 +0000625 return;
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000626
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000627 LLVM_DEBUG(
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000628 dbgs()
629 << "\n+++ ITINERARIES and/or MACHINE MODELS (collectSchedClasses) +++\n");
Craig Topper8cc904d2016-01-17 20:38:18 +0000630 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
Craig Topperbcd3c372017-05-31 21:12:46 +0000631 StringRef InstName = Inst->TheDef->getName();
Simon Pilgrim949437e2018-03-21 18:09:34 +0000632 unsigned SCIdx = getSchedClassIdx(*Inst);
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000633 if (!SCIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000634 LLVM_DEBUG({
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000635 if (!Inst->hasNoSchedulingInfo)
636 dbgs() << "No machine model for " << Inst->TheDef->getName() << '\n';
637 });
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000638 continue;
639 }
640 CodeGenSchedClass &SC = getSchedClass(SCIdx);
641 if (SC.ProcIndices[0] != 0)
Craig Topper8a417c12014-12-09 08:05:51 +0000642 PrintFatalError(Inst->TheDef->getLoc(), "Instruction's sched class "
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000643 "must not be subtarget specific.");
644
645 IdxVec ProcIndices;
646 if (SC.ItinClassDef->getName() != "NoItinerary") {
647 ProcIndices.push_back(0);
648 dbgs() << "Itinerary for " << InstName << ": "
649 << SC.ItinClassDef->getName() << '\n';
650 }
651 if (!SC.Writes.empty()) {
652 ProcIndices.push_back(0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000653 LLVM_DEBUG({
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000654 dbgs() << "SchedRW machine model for " << InstName;
655 for (IdxIter WI = SC.Writes.begin(), WE = SC.Writes.end(); WI != WE;
656 ++WI)
657 dbgs() << " " << SchedWrites[*WI].Name;
658 for (IdxIter RI = SC.Reads.begin(), RE = SC.Reads.end(); RI != RE; ++RI)
659 dbgs() << " " << SchedReads[*RI].Name;
660 dbgs() << '\n';
661 });
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000662 }
663 const RecVec &RWDefs = SchedClasses[SCIdx].InstRWs;
Javed Absar67b042c2017-09-13 10:31:10 +0000664 for (Record *RWDef : RWDefs) {
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000665 const CodeGenProcModel &ProcModel =
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000666 getProcModel(RWDef->getValueAsDef("SchedModel"));
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000667 ProcIndices.push_back(ProcModel.Index);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000668 LLVM_DEBUG(dbgs() << "InstRW on " << ProcModel.ModelName << " for "
669 << InstName);
Andrew Trick76686492012-09-15 00:19:57 +0000670 IdxVec Writes;
671 IdxVec Reads;
Javed Absar67b042c2017-09-13 10:31:10 +0000672 findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000673 Writes, Reads);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000674 LLVM_DEBUG({
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000675 for (unsigned WIdx : Writes)
676 dbgs() << " " << SchedWrites[WIdx].Name;
677 for (unsigned RIdx : Reads)
678 dbgs() << " " << SchedReads[RIdx].Name;
679 dbgs() << '\n';
680 });
Andrew Trick76686492012-09-15 00:19:57 +0000681 }
Andrew Trickf9df92c92016-10-18 04:17:44 +0000682 // If ProcIndices contains zero, the class applies to all processors.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000683 LLVM_DEBUG({
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000684 if (!std::count(ProcIndices.begin(), ProcIndices.end(), 0)) {
685 for (const CodeGenProcModel &PM : ProcModels) {
686 if (!std::count(ProcIndices.begin(), ProcIndices.end(), PM.Index))
687 dbgs() << "No machine model for " << Inst->TheDef->getName()
688 << " on processor " << PM.ModelName << '\n';
689 }
Andrew Trickf9df92c92016-10-18 04:17:44 +0000690 }
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000691 });
Andrew Trick87255e32012-07-07 04:00:00 +0000692 }
Andrew Trick76686492012-09-15 00:19:57 +0000693}
694
Andrew Trick76686492012-09-15 00:19:57 +0000695// Get the SchedClass index for an instruction.
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000696unsigned
697CodeGenSchedModels::getSchedClassIdx(const CodeGenInstruction &Inst) const {
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000698 return InstrClassMap.lookup(Inst.TheDef);
Andrew Trick76686492012-09-15 00:19:57 +0000699}
700
Benjamin Kramere1761952015-10-24 12:46:49 +0000701std::string
702CodeGenSchedModels::createSchedClassName(Record *ItinClassDef,
703 ArrayRef<unsigned> OperWrites,
704 ArrayRef<unsigned> OperReads) {
Andrew Trick76686492012-09-15 00:19:57 +0000705
706 std::string Name;
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000707 if (ItinClassDef && ItinClassDef->getName() != "NoItinerary")
708 Name = ItinClassDef->getName();
Benjamin Kramere1761952015-10-24 12:46:49 +0000709 for (unsigned Idx : OperWrites) {
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000710 if (!Name.empty())
Andrew Trick76686492012-09-15 00:19:57 +0000711 Name += '_';
Benjamin Kramere1761952015-10-24 12:46:49 +0000712 Name += SchedWrites[Idx].Name;
Andrew Trick76686492012-09-15 00:19:57 +0000713 }
Benjamin Kramere1761952015-10-24 12:46:49 +0000714 for (unsigned Idx : OperReads) {
Andrew Trick76686492012-09-15 00:19:57 +0000715 Name += '_';
Benjamin Kramere1761952015-10-24 12:46:49 +0000716 Name += SchedReads[Idx].Name;
Andrew Trick76686492012-09-15 00:19:57 +0000717 }
718 return Name;
719}
720
721std::string CodeGenSchedModels::createSchedClassName(const RecVec &InstDefs) {
722
723 std::string Name;
724 for (RecIter I = InstDefs.begin(), E = InstDefs.end(); I != E; ++I) {
725 if (I != InstDefs.begin())
726 Name += '_';
727 Name += (*I)->getName();
728 }
729 return Name;
730}
731
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000732/// Add an inferred sched class from an itinerary class and per-operand list of
733/// SchedWrites and SchedReads. ProcIndices contains the set of IDs of
734/// processors that may utilize this class.
735unsigned CodeGenSchedModels::addSchedClass(Record *ItinClassDef,
Benjamin Kramere1761952015-10-24 12:46:49 +0000736 ArrayRef<unsigned> OperWrites,
737 ArrayRef<unsigned> OperReads,
738 ArrayRef<unsigned> ProcIndices) {
Andrew Trick76686492012-09-15 00:19:57 +0000739 assert(!ProcIndices.empty() && "expect at least one ProcIdx");
740
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000741 auto IsKeyEqual = [=](const CodeGenSchedClass &SC) {
742 return SC.isKeyEqual(ItinClassDef, OperWrites, OperReads);
743 };
744
745 auto I = find_if(make_range(schedClassBegin(), schedClassEnd()), IsKeyEqual);
746 unsigned Idx = I == schedClassEnd() ? 0 : std::distance(schedClassBegin(), I);
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000747 if (Idx || SchedClasses[0].isKeyEqual(ItinClassDef, OperWrites, OperReads)) {
Andrew Trick76686492012-09-15 00:19:57 +0000748 IdxVec PI;
749 std::set_union(SchedClasses[Idx].ProcIndices.begin(),
750 SchedClasses[Idx].ProcIndices.end(),
751 ProcIndices.begin(), ProcIndices.end(),
752 std::back_inserter(PI));
Craig Topper59d13772018-03-24 22:58:00 +0000753 SchedClasses[Idx].ProcIndices = std::move(PI);
Andrew Trick76686492012-09-15 00:19:57 +0000754 return Idx;
755 }
756 Idx = SchedClasses.size();
Craig Topper281a19c2018-03-22 06:15:08 +0000757 SchedClasses.emplace_back(Idx,
758 createSchedClassName(ItinClassDef, OperWrites,
759 OperReads),
760 ItinClassDef);
Andrew Trick76686492012-09-15 00:19:57 +0000761 CodeGenSchedClass &SC = SchedClasses.back();
Andrew Trick76686492012-09-15 00:19:57 +0000762 SC.Writes = OperWrites;
763 SC.Reads = OperReads;
764 SC.ProcIndices = ProcIndices;
765
766 return Idx;
767}
768
769// Create classes for each set of opcodes that are in the same InstReadWrite
770// definition across all processors.
771void CodeGenSchedModels::createInstRWClass(Record *InstRWDef) {
772 // ClassInstrs will hold an entry for each subset of Instrs in InstRWDef that
773 // intersects with an existing class via a previous InstRWDef. Instrs that do
774 // not intersect with an existing class refer back to their former class as
775 // determined from ItinDef or SchedRW.
Craig Topperf19eacf2018-03-21 02:48:34 +0000776 SmallMapVector<unsigned, SmallVector<Record *, 8>, 4> ClassInstrs;
Andrew Trick76686492012-09-15 00:19:57 +0000777 // Sort Instrs into sets.
Andrew Trick9e1deb62012-10-03 23:06:32 +0000778 const RecVec *InstDefs = Sets.expand(InstRWDef);
779 if (InstDefs->empty())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000780 PrintFatalError(InstRWDef->getLoc(), "No matching instruction opcodes");
Andrew Trick9e1deb62012-10-03 23:06:32 +0000781
Craig Topper93dd77d2018-03-18 08:38:03 +0000782 for (Record *InstDef : *InstDefs) {
Javed Absarfc500042017-10-05 13:27:43 +0000783 InstClassMapTy::const_iterator Pos = InstrClassMap.find(InstDef);
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000784 if (Pos == InstrClassMap.end())
Javed Absarfc500042017-10-05 13:27:43 +0000785 PrintFatalError(InstDef->getLoc(), "No sched class for instruction.");
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000786 unsigned SCIdx = Pos->second;
Craig Topperf19eacf2018-03-21 02:48:34 +0000787 ClassInstrs[SCIdx].push_back(InstDef);
Andrew Trick76686492012-09-15 00:19:57 +0000788 }
789 // For each set of Instrs, create a new class if necessary, and map or remap
790 // the Instrs to it.
Craig Topperf19eacf2018-03-21 02:48:34 +0000791 for (auto &Entry : ClassInstrs) {
792 unsigned OldSCIdx = Entry.first;
793 ArrayRef<Record*> InstDefs = Entry.second;
Andrew Trick76686492012-09-15 00:19:57 +0000794 // If the all instrs in the current class are accounted for, then leave
795 // them mapped to their old class.
Andrew Trick78a08512013-06-05 06:55:20 +0000796 if (OldSCIdx) {
797 const RecVec &RWDefs = SchedClasses[OldSCIdx].InstRWs;
798 if (!RWDefs.empty()) {
799 const RecVec *OrigInstDefs = Sets.expand(RWDefs[0]);
Craig Topper06d78372018-03-21 19:30:30 +0000800 unsigned OrigNumInstrs =
801 count_if(*OrigInstDefs, [&](Record *OIDef) {
802 return InstrClassMap[OIDef] == OldSCIdx;
803 });
Andrew Trick78a08512013-06-05 06:55:20 +0000804 if (OrigNumInstrs == InstDefs.size()) {
805 assert(SchedClasses[OldSCIdx].ProcIndices[0] == 0 &&
806 "expected a generic SchedClass");
Craig Toppere1d6a4d2018-03-18 19:56:15 +0000807 Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
808 // Make sure we didn't already have a InstRW containing this
809 // instruction on this model.
810 for (Record *RWD : RWDefs) {
811 if (RWD->getValueAsDef("SchedModel") == RWModelDef &&
812 RWModelDef->getValueAsBit("FullInstRWOverlapCheck")) {
813 for (Record *Inst : InstDefs) {
814 PrintFatalError(InstRWDef->getLoc(), "Overlapping InstRW def " +
815 Inst->getName() + " also matches " +
816 RWD->getValue("Instrs")->getValue()->getAsString());
817 }
818 }
819 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000820 LLVM_DEBUG(dbgs() << "InstRW: Reuse SC " << OldSCIdx << ":"
821 << SchedClasses[OldSCIdx].Name << " on "
822 << RWModelDef->getName() << "\n");
Andrew Trick78a08512013-06-05 06:55:20 +0000823 SchedClasses[OldSCIdx].InstRWs.push_back(InstRWDef);
824 continue;
825 }
826 }
Andrew Trick76686492012-09-15 00:19:57 +0000827 }
828 unsigned SCIdx = SchedClasses.size();
Craig Topper281a19c2018-03-22 06:15:08 +0000829 SchedClasses.emplace_back(SCIdx, createSchedClassName(InstDefs), nullptr);
Andrew Trick76686492012-09-15 00:19:57 +0000830 CodeGenSchedClass &SC = SchedClasses.back();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000831 LLVM_DEBUG(dbgs() << "InstRW: New SC " << SCIdx << ":" << SC.Name << " on "
832 << InstRWDef->getValueAsDef("SchedModel")->getName()
833 << "\n");
Andrew Trick78a08512013-06-05 06:55:20 +0000834
Andrew Trick76686492012-09-15 00:19:57 +0000835 // Preserve ItinDef and Writes/Reads for processors without an InstRW entry.
836 SC.ItinClassDef = SchedClasses[OldSCIdx].ItinClassDef;
837 SC.Writes = SchedClasses[OldSCIdx].Writes;
838 SC.Reads = SchedClasses[OldSCIdx].Reads;
839 SC.ProcIndices.push_back(0);
Craig Topper989d94d2018-03-21 19:52:13 +0000840 // If we had an old class, copy it's InstRWs to this new class.
841 if (OldSCIdx) {
842 Record *RWModelDef = InstRWDef->getValueAsDef("SchedModel");
843 for (Record *OldRWDef : SchedClasses[OldSCIdx].InstRWs) {
844 if (OldRWDef->getValueAsDef("SchedModel") == RWModelDef) {
845 for (Record *InstDef : InstDefs) {
Craig Topper9fbbe5d2018-03-21 19:30:31 +0000846 PrintFatalError(OldRWDef->getLoc(), "Overlapping InstRW def " +
847 InstDef->getName() + " also matches " +
848 OldRWDef->getValue("Instrs")->getValue()->getAsString());
Andrew Trick9e1deb62012-10-03 23:06:32 +0000849 }
Andrew Trick9e1deb62012-10-03 23:06:32 +0000850 }
Craig Topper989d94d2018-03-21 19:52:13 +0000851 assert(OldRWDef != InstRWDef &&
852 "SchedClass has duplicate InstRW def");
853 SC.InstRWs.push_back(OldRWDef);
Andrew Trick76686492012-09-15 00:19:57 +0000854 }
Andrew Trick76686492012-09-15 00:19:57 +0000855 }
Craig Topper989d94d2018-03-21 19:52:13 +0000856 // Map each Instr to this new class.
857 for (Record *InstDef : InstDefs)
858 InstrClassMap[InstDef] = SCIdx;
Andrew Trick76686492012-09-15 00:19:57 +0000859 SC.InstRWs.push_back(InstRWDef);
860 }
Andrew Trick87255e32012-07-07 04:00:00 +0000861}
862
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000863// True if collectProcItins found anything.
864bool CodeGenSchedModels::hasItineraries() const {
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000865 for (const CodeGenProcModel &PM : make_range(procModelBegin(),procModelEnd()))
Javed Absar67b042c2017-09-13 10:31:10 +0000866 if (PM.hasItineraries())
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000867 return true;
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000868 return false;
869}
870
Andrew Trick87255e32012-07-07 04:00:00 +0000871// Gather the processor itineraries.
Andrew Trick76686492012-09-15 00:19:57 +0000872void CodeGenSchedModels::collectProcItins() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000873 LLVM_DEBUG(dbgs() << "\n+++ PROBLEM ITINERARIES (collectProcItins) +++\n");
Craig Topper8a417c12014-12-09 08:05:51 +0000874 for (CodeGenProcModel &ProcModel : ProcModels) {
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000875 if (!ProcModel.hasItineraries())
Andrew Trick87255e32012-07-07 04:00:00 +0000876 continue;
Andrew Trick76686492012-09-15 00:19:57 +0000877
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000878 RecVec ItinRecords = ProcModel.ItinsDef->getValueAsListOfDefs("IID");
879 assert(!ItinRecords.empty() && "ProcModel.hasItineraries is incorrect");
880
881 // Populate ItinDefList with Itinerary records.
882 ProcModel.ItinDefList.resize(NumInstrSchedClasses);
Andrew Trick76686492012-09-15 00:19:57 +0000883
884 // Insert each itinerary data record in the correct position within
885 // the processor model's ItinDefList.
Javed Absarfc500042017-10-05 13:27:43 +0000886 for (Record *ItinData : ItinRecords) {
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000887 const Record *ItinDef = ItinData->getValueAsDef("TheClass");
Andrew Tricke7bac5f2013-03-18 20:42:25 +0000888 bool FoundClass = false;
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000889
890 for (const CodeGenSchedClass &SC :
891 make_range(schedClassBegin(), schedClassEnd())) {
Andrew Tricke7bac5f2013-03-18 20:42:25 +0000892 // Multiple SchedClasses may share an itinerary. Update all of them.
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000893 if (SC.ItinClassDef == ItinDef) {
894 ProcModel.ItinDefList[SC.Index] = ItinData;
Andrew Tricke7bac5f2013-03-18 20:42:25 +0000895 FoundClass = true;
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000896 }
Andrew Trick76686492012-09-15 00:19:57 +0000897 }
Andrew Tricke7bac5f2013-03-18 20:42:25 +0000898 if (!FoundClass) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000899 LLVM_DEBUG(dbgs() << ProcModel.ItinsDef->getName()
900 << " missing class for itinerary "
901 << ItinDef->getName() << '\n');
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000902 }
Andrew Trick87255e32012-07-07 04:00:00 +0000903 }
Andrew Trick76686492012-09-15 00:19:57 +0000904 // Check for missing itinerary entries.
905 assert(!ProcModel.ItinDefList[0] && "NoItinerary class can't have rec");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000906 LLVM_DEBUG(
907 for (unsigned i = 1, N = ProcModel.ItinDefList.size(); i < N; ++i) {
908 if (!ProcModel.ItinDefList[i])
909 dbgs() << ProcModel.ItinsDef->getName()
910 << " missing itinerary for class " << SchedClasses[i].Name
911 << '\n';
912 });
Andrew Trick87255e32012-07-07 04:00:00 +0000913 }
Andrew Trick87255e32012-07-07 04:00:00 +0000914}
Andrew Trick76686492012-09-15 00:19:57 +0000915
916// Gather the read/write types for each itinerary class.
917void CodeGenSchedModels::collectProcItinRW() {
918 RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000919 llvm::sort(ItinRWDefs.begin(), ItinRWDefs.end(), LessRecord());
Javed Absar21c75912017-10-09 16:21:25 +0000920 for (Record *RWDef : ItinRWDefs) {
Javed Absarf45d0b92017-10-08 17:23:30 +0000921 if (!RWDef->getValueInit("SchedModel")->isComplete())
922 PrintFatalError(RWDef->getLoc(), "SchedModel is undefined");
923 Record *ModelDef = RWDef->getValueAsDef("SchedModel");
Andrew Trick76686492012-09-15 00:19:57 +0000924 ProcModelMapTy::const_iterator I = ProcModelMap.find(ModelDef);
925 if (I == ProcModelMap.end()) {
Javed Absarf45d0b92017-10-08 17:23:30 +0000926 PrintFatalError(RWDef->getLoc(), "Undefined SchedMachineModel "
Andrew Trick76686492012-09-15 00:19:57 +0000927 + ModelDef->getName());
928 }
Javed Absarf45d0b92017-10-08 17:23:30 +0000929 ProcModels[I->second].ItinRWDefs.push_back(RWDef);
Andrew Trick76686492012-09-15 00:19:57 +0000930 }
931}
932
Simon Dardis5f95c9a2016-06-24 08:43:27 +0000933// Gather the unsupported features for processor models.
934void CodeGenSchedModels::collectProcUnsupportedFeatures() {
935 for (CodeGenProcModel &ProcModel : ProcModels) {
936 for (Record *Pred : ProcModel.ModelDef->getValueAsListOfDefs("UnsupportedFeatures")) {
937 ProcModel.UnsupportedFeaturesDefs.push_back(Pred);
938 }
939 }
940}
941
Andrew Trick33401e82012-09-15 00:19:59 +0000942/// Infer new classes from existing classes. In the process, this may create new
943/// SchedWrites from sequences of existing SchedWrites.
944void CodeGenSchedModels::inferSchedClasses() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000945 LLVM_DEBUG(
946 dbgs() << "\n+++ INFERRING SCHED CLASSES (inferSchedClasses) +++\n");
947 LLVM_DEBUG(dbgs() << NumInstrSchedClasses << " instr sched classes.\n");
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000948
Andrew Trick33401e82012-09-15 00:19:59 +0000949 // Visit all existing classes and newly created classes.
950 for (unsigned Idx = 0; Idx != SchedClasses.size(); ++Idx) {
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000951 assert(SchedClasses[Idx].Index == Idx && "bad SCIdx");
952
Andrew Trick33401e82012-09-15 00:19:59 +0000953 if (SchedClasses[Idx].ItinClassDef)
954 inferFromItinClass(SchedClasses[Idx].ItinClassDef, Idx);
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000955 if (!SchedClasses[Idx].InstRWs.empty())
Andrew Trick33401e82012-09-15 00:19:59 +0000956 inferFromInstRWs(Idx);
Andrew Trickbf8a28d2013-03-16 18:58:55 +0000957 if (!SchedClasses[Idx].Writes.empty()) {
Andrew Trick33401e82012-09-15 00:19:59 +0000958 inferFromRW(SchedClasses[Idx].Writes, SchedClasses[Idx].Reads,
959 Idx, SchedClasses[Idx].ProcIndices);
960 }
961 assert(SchedClasses.size() < (NumInstrSchedClasses*6) &&
962 "too many SchedVariants");
963 }
964}
965
966/// Infer classes from per-processor itinerary resources.
967void CodeGenSchedModels::inferFromItinClass(Record *ItinClassDef,
968 unsigned FromClassIdx) {
969 for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
970 const CodeGenProcModel &PM = ProcModels[PIdx];
971 // For all ItinRW entries.
972 bool HasMatch = false;
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000973 for (const Record *Rec : PM.ItinRWDefs) {
974 RecVec Matched = Rec->getValueAsListOfDefs("MatchedItinClasses");
Andrew Trick33401e82012-09-15 00:19:59 +0000975 if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
976 continue;
977 if (HasMatch)
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000978 PrintFatalError(Rec->getLoc(), "Duplicate itinerary class "
Andrew Trick33401e82012-09-15 00:19:59 +0000979 + ItinClassDef->getName()
980 + " in ItinResources for " + PM.ModelName);
981 HasMatch = true;
982 IdxVec Writes, Reads;
Andrea Di Biagio38fe2272018-04-26 12:56:26 +0000983 findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
Craig Topper9f3293a2018-03-24 21:57:35 +0000984 inferFromRW(Writes, Reads, FromClassIdx, PIdx);
Andrew Trick33401e82012-09-15 00:19:59 +0000985 }
986 }
987}
988
989/// Infer classes from per-processor InstReadWrite definitions.
990void CodeGenSchedModels::inferFromInstRWs(unsigned SCIdx) {
Benjamin Kramer58bd79c2013-06-09 15:20:23 +0000991 for (unsigned I = 0, E = SchedClasses[SCIdx].InstRWs.size(); I != E; ++I) {
Benjamin Kramerb22643a2013-06-10 20:19:35 +0000992 assert(SchedClasses[SCIdx].InstRWs.size() == E && "InstrRWs was mutated!");
Benjamin Kramer58bd79c2013-06-09 15:20:23 +0000993 Record *Rec = SchedClasses[SCIdx].InstRWs[I];
994 const RecVec *InstDefs = Sets.expand(Rec);
Andrew Trick9e1deb62012-10-03 23:06:32 +0000995 RecIter II = InstDefs->begin(), IE = InstDefs->end();
Andrew Trick33401e82012-09-15 00:19:59 +0000996 for (; II != IE; ++II) {
997 if (InstrClassMap[*II] == SCIdx)
998 break;
999 }
1000 // If this class no longer has any instructions mapped to it, it has become
1001 // irrelevant.
1002 if (II == IE)
1003 continue;
1004 IdxVec Writes, Reads;
Benjamin Kramer58bd79c2013-06-09 15:20:23 +00001005 findRWs(Rec->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1006 unsigned PIdx = getProcModel(Rec->getValueAsDef("SchedModel")).Index;
Craig Topper9f3293a2018-03-24 21:57:35 +00001007 inferFromRW(Writes, Reads, SCIdx, PIdx); // May mutate SchedClasses.
Andrew Trick33401e82012-09-15 00:19:59 +00001008 }
1009}
1010
1011namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001012
Andrew Trick9257b8f2012-09-22 02:24:21 +00001013// Helper for substituteVariantOperand.
1014struct TransVariant {
Andrew Trickda984b12012-10-03 23:06:28 +00001015 Record *VarOrSeqDef; // Variant or sequence.
1016 unsigned RWIdx; // Index of this variant or sequence's matched type.
Andrew Trick9257b8f2012-09-22 02:24:21 +00001017 unsigned ProcIdx; // Processor model index or zero for any.
1018 unsigned TransVecIdx; // Index into PredTransitions::TransVec.
1019
1020 TransVariant(Record *def, unsigned rwi, unsigned pi, unsigned ti):
Andrew Trickda984b12012-10-03 23:06:28 +00001021 VarOrSeqDef(def), RWIdx(rwi), ProcIdx(pi), TransVecIdx(ti) {}
Andrew Trick9257b8f2012-09-22 02:24:21 +00001022};
1023
Andrew Trick33401e82012-09-15 00:19:59 +00001024// Associate a predicate with the SchedReadWrite that it guards.
1025// RWIdx is the index of the read/write variant.
1026struct PredCheck {
1027 bool IsRead;
1028 unsigned RWIdx;
1029 Record *Predicate;
1030
1031 PredCheck(bool r, unsigned w, Record *p): IsRead(r), RWIdx(w), Predicate(p) {}
1032};
1033
1034// A Predicate transition is a list of RW sequences guarded by a PredTerm.
1035struct PredTransition {
1036 // A predicate term is a conjunction of PredChecks.
1037 SmallVector<PredCheck, 4> PredTerm;
1038 SmallVector<SmallVector<unsigned,4>, 16> WriteSequences;
1039 SmallVector<SmallVector<unsigned,4>, 16> ReadSequences;
Andrew Trick9257b8f2012-09-22 02:24:21 +00001040 SmallVector<unsigned, 4> ProcIndices;
Andrew Trick33401e82012-09-15 00:19:59 +00001041};
1042
1043// Encapsulate a set of partially constructed transitions.
1044// The results are built by repeated calls to substituteVariants.
1045class PredTransitions {
1046 CodeGenSchedModels &SchedModels;
1047
1048public:
1049 std::vector<PredTransition> TransVec;
1050
1051 PredTransitions(CodeGenSchedModels &sm): SchedModels(sm) {}
1052
1053 void substituteVariantOperand(const SmallVectorImpl<unsigned> &RWSeq,
1054 bool IsRead, unsigned StartIdx);
1055
1056 void substituteVariants(const PredTransition &Trans);
1057
1058#ifndef NDEBUG
1059 void dump() const;
1060#endif
1061
1062private:
1063 bool mutuallyExclusive(Record *PredDef, ArrayRef<PredCheck> Term);
Andrew Trickda984b12012-10-03 23:06:28 +00001064 void getIntersectingVariants(
1065 const CodeGenSchedRW &SchedRW, unsigned TransIdx,
1066 std::vector<TransVariant> &IntersectingVariants);
Andrew Trick9257b8f2012-09-22 02:24:21 +00001067 void pushVariant(const TransVariant &VInfo, bool IsRead);
Andrew Trick33401e82012-09-15 00:19:59 +00001068};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001069
1070} // end anonymous namespace
Andrew Trick33401e82012-09-15 00:19:59 +00001071
1072// Return true if this predicate is mutually exclusive with a PredTerm. This
1073// degenerates into checking if the predicate is mutually exclusive with any
1074// predicate in the Term's conjunction.
1075//
1076// All predicates associated with a given SchedRW are considered mutually
1077// exclusive. This should work even if the conditions expressed by the
1078// predicates are not exclusive because the predicates for a given SchedWrite
1079// are always checked in the order they are defined in the .td file. Later
1080// conditions implicitly negate any prior condition.
1081bool PredTransitions::mutuallyExclusive(Record *PredDef,
1082 ArrayRef<PredCheck> Term) {
Javed Absar21c75912017-10-09 16:21:25 +00001083 for (const PredCheck &PC: Term) {
Javed Absarfc500042017-10-05 13:27:43 +00001084 if (PC.Predicate == PredDef)
Andrew Trick33401e82012-09-15 00:19:59 +00001085 return false;
1086
Javed Absarfc500042017-10-05 13:27:43 +00001087 const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(PC.RWIdx, PC.IsRead);
Andrew Trick33401e82012-09-15 00:19:59 +00001088 assert(SchedRW.HasVariants && "PredCheck must refer to a SchedVariant");
1089 RecVec Variants = SchedRW.TheDef->getValueAsListOfDefs("Variants");
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001090 if (any_of(Variants, [PredDef](const Record *R) {
1091 return R->getValueAsDef("Predicate") == PredDef;
1092 }))
1093 return true;
Andrew Trick33401e82012-09-15 00:19:59 +00001094 }
1095 return false;
1096}
1097
Andrew Trickda984b12012-10-03 23:06:28 +00001098static bool hasAliasedVariants(const CodeGenSchedRW &RW,
1099 CodeGenSchedModels &SchedModels) {
1100 if (RW.HasVariants)
1101 return true;
1102
Javed Absar21c75912017-10-09 16:21:25 +00001103 for (Record *Alias : RW.Aliases) {
Andrew Trickda984b12012-10-03 23:06:28 +00001104 const CodeGenSchedRW &AliasRW =
Javed Absarfc500042017-10-05 13:27:43 +00001105 SchedModels.getSchedRW(Alias->getValueAsDef("AliasRW"));
Andrew Trickda984b12012-10-03 23:06:28 +00001106 if (AliasRW.HasVariants)
1107 return true;
1108 if (AliasRW.IsSequence) {
1109 IdxVec ExpandedRWs;
1110 SchedModels.expandRWSequence(AliasRW.Index, ExpandedRWs, AliasRW.IsRead);
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001111 for (unsigned SI : ExpandedRWs) {
1112 if (hasAliasedVariants(SchedModels.getSchedRW(SI, AliasRW.IsRead),
1113 SchedModels))
Andrew Trickda984b12012-10-03 23:06:28 +00001114 return true;
Andrew Trickda984b12012-10-03 23:06:28 +00001115 }
1116 }
1117 }
1118 return false;
1119}
1120
1121static bool hasVariant(ArrayRef<PredTransition> Transitions,
1122 CodeGenSchedModels &SchedModels) {
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001123 for (const PredTransition &PTI : Transitions) {
1124 for (const SmallVectorImpl<unsigned> &WSI : PTI.WriteSequences)
1125 for (unsigned WI : WSI)
1126 if (hasAliasedVariants(SchedModels.getSchedWrite(WI), SchedModels))
Andrew Trickda984b12012-10-03 23:06:28 +00001127 return true;
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001128
1129 for (const SmallVectorImpl<unsigned> &RSI : PTI.ReadSequences)
1130 for (unsigned RI : RSI)
1131 if (hasAliasedVariants(SchedModels.getSchedRead(RI), SchedModels))
Andrew Trickda984b12012-10-03 23:06:28 +00001132 return true;
Andrew Trickda984b12012-10-03 23:06:28 +00001133 }
1134 return false;
1135}
1136
1137// Populate IntersectingVariants with any variants or aliased sequences of the
1138// given SchedRW whose processor indices and predicates are not mutually
Andrew Trickd97ff1f2013-03-29 19:08:31 +00001139// exclusive with the given transition.
Andrew Trickda984b12012-10-03 23:06:28 +00001140void PredTransitions::getIntersectingVariants(
1141 const CodeGenSchedRW &SchedRW, unsigned TransIdx,
1142 std::vector<TransVariant> &IntersectingVariants) {
1143
Andrew Trickd97ff1f2013-03-29 19:08:31 +00001144 bool GenericRW = false;
1145
Andrew Trickda984b12012-10-03 23:06:28 +00001146 std::vector<TransVariant> Variants;
1147 if (SchedRW.HasVariants) {
1148 unsigned VarProcIdx = 0;
1149 if (SchedRW.TheDef->getValueInit("SchedModel")->isComplete()) {
1150 Record *ModelDef = SchedRW.TheDef->getValueAsDef("SchedModel");
1151 VarProcIdx = SchedModels.getProcModel(ModelDef).Index;
1152 }
1153 // Push each variant. Assign TransVecIdx later.
1154 const RecVec VarDefs = SchedRW.TheDef->getValueAsListOfDefs("Variants");
Javed Absarf45d0b92017-10-08 17:23:30 +00001155 for (Record *VarDef : VarDefs)
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001156 Variants.emplace_back(VarDef, SchedRW.Index, VarProcIdx, 0);
Andrew Trickd97ff1f2013-03-29 19:08:31 +00001157 if (VarProcIdx == 0)
1158 GenericRW = true;
Andrew Trickda984b12012-10-03 23:06:28 +00001159 }
1160 for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
1161 AI != AE; ++AI) {
1162 // If either the SchedAlias itself or the SchedReadWrite that it aliases
1163 // to is defined within a processor model, constrain all variants to
1164 // that processor.
1165 unsigned AliasProcIdx = 0;
1166 if ((*AI)->getValueInit("SchedModel")->isComplete()) {
1167 Record *ModelDef = (*AI)->getValueAsDef("SchedModel");
1168 AliasProcIdx = SchedModels.getProcModel(ModelDef).Index;
1169 }
1170 const CodeGenSchedRW &AliasRW =
1171 SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
1172
1173 if (AliasRW.HasVariants) {
1174 const RecVec VarDefs = AliasRW.TheDef->getValueAsListOfDefs("Variants");
Javed Absar9003dd72017-10-10 15:58:45 +00001175 for (Record *VD : VarDefs)
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001176 Variants.emplace_back(VD, AliasRW.Index, AliasProcIdx, 0);
Andrew Trickda984b12012-10-03 23:06:28 +00001177 }
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001178 if (AliasRW.IsSequence)
1179 Variants.emplace_back(AliasRW.TheDef, SchedRW.Index, AliasProcIdx, 0);
Andrew Trickd97ff1f2013-03-29 19:08:31 +00001180 if (AliasProcIdx == 0)
1181 GenericRW = true;
Andrew Trickda984b12012-10-03 23:06:28 +00001182 }
Javed Absarf45d0b92017-10-08 17:23:30 +00001183 for (TransVariant &Variant : Variants) {
Andrew Trickda984b12012-10-03 23:06:28 +00001184 // Don't expand variants if the processor models don't intersect.
1185 // A zero processor index means any processor.
Craig Topperb94011f2013-07-14 04:42:23 +00001186 SmallVectorImpl<unsigned> &ProcIndices = TransVec[TransIdx].ProcIndices;
Javed Absarf45d0b92017-10-08 17:23:30 +00001187 if (ProcIndices[0] && Variant.ProcIdx) {
Andrew Trickda984b12012-10-03 23:06:28 +00001188 unsigned Cnt = std::count(ProcIndices.begin(), ProcIndices.end(),
1189 Variant.ProcIdx);
1190 if (!Cnt)
1191 continue;
1192 if (Cnt > 1) {
1193 const CodeGenProcModel &PM =
1194 *(SchedModels.procModelBegin() + Variant.ProcIdx);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001195 PrintFatalError(Variant.VarOrSeqDef->getLoc(),
1196 "Multiple variants defined for processor " +
1197 PM.ModelName +
1198 " Ensure only one SchedAlias exists per RW.");
Andrew Trickda984b12012-10-03 23:06:28 +00001199 }
1200 }
1201 if (Variant.VarOrSeqDef->isSubClassOf("SchedVar")) {
1202 Record *PredDef = Variant.VarOrSeqDef->getValueAsDef("Predicate");
1203 if (mutuallyExclusive(PredDef, TransVec[TransIdx].PredTerm))
1204 continue;
1205 }
1206 if (IntersectingVariants.empty()) {
1207 // The first variant builds on the existing transition.
1208 Variant.TransVecIdx = TransIdx;
1209 IntersectingVariants.push_back(Variant);
1210 }
1211 else {
1212 // Push another copy of the current transition for more variants.
1213 Variant.TransVecIdx = TransVec.size();
1214 IntersectingVariants.push_back(Variant);
Dan Gohmanf6169d02013-03-29 00:13:08 +00001215 TransVec.push_back(TransVec[TransIdx]);
Andrew Trickda984b12012-10-03 23:06:28 +00001216 }
1217 }
Andrew Trickd97ff1f2013-03-29 19:08:31 +00001218 if (GenericRW && IntersectingVariants.empty()) {
1219 PrintFatalError(SchedRW.TheDef->getLoc(), "No variant of this type has "
1220 "a matching predicate on any processor");
1221 }
Andrew Trickda984b12012-10-03 23:06:28 +00001222}
1223
Andrew Trick9257b8f2012-09-22 02:24:21 +00001224// Push the Reads/Writes selected by this variant onto the PredTransition
1225// specified by VInfo.
1226void PredTransitions::
1227pushVariant(const TransVariant &VInfo, bool IsRead) {
Andrew Trick9257b8f2012-09-22 02:24:21 +00001228 PredTransition &Trans = TransVec[VInfo.TransVecIdx];
1229
Andrew Trick9257b8f2012-09-22 02:24:21 +00001230 // If this operand transition is reached through a processor-specific alias,
1231 // then the whole transition is specific to this processor.
1232 if (VInfo.ProcIdx != 0)
1233 Trans.ProcIndices.assign(1, VInfo.ProcIdx);
1234
Andrew Trick33401e82012-09-15 00:19:59 +00001235 IdxVec SelectedRWs;
Andrew Trickda984b12012-10-03 23:06:28 +00001236 if (VInfo.VarOrSeqDef->isSubClassOf("SchedVar")) {
1237 Record *PredDef = VInfo.VarOrSeqDef->getValueAsDef("Predicate");
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001238 Trans.PredTerm.emplace_back(IsRead, VInfo.RWIdx,PredDef);
Andrew Trickda984b12012-10-03 23:06:28 +00001239 RecVec SelectedDefs = VInfo.VarOrSeqDef->getValueAsListOfDefs("Selected");
1240 SchedModels.findRWs(SelectedDefs, SelectedRWs, IsRead);
1241 }
1242 else {
1243 assert(VInfo.VarOrSeqDef->isSubClassOf("WriteSequence") &&
1244 "variant must be a SchedVariant or aliased WriteSequence");
1245 SelectedRWs.push_back(SchedModels.getSchedRWIdx(VInfo.VarOrSeqDef, IsRead));
1246 }
Andrew Trick33401e82012-09-15 00:19:59 +00001247
Andrew Trick9257b8f2012-09-22 02:24:21 +00001248 const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(VInfo.RWIdx, IsRead);
Andrew Trick33401e82012-09-15 00:19:59 +00001249
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001250 SmallVectorImpl<SmallVector<unsigned,4>> &RWSequences = IsRead
Andrew Trick33401e82012-09-15 00:19:59 +00001251 ? Trans.ReadSequences : Trans.WriteSequences;
1252 if (SchedRW.IsVariadic) {
1253 unsigned OperIdx = RWSequences.size()-1;
1254 // Make N-1 copies of this transition's last sequence.
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001255 RWSequences.insert(RWSequences.end(), SelectedRWs.size() - 1,
1256 RWSequences[OperIdx]);
Andrew Trick33401e82012-09-15 00:19:59 +00001257 // Push each of the N elements of the SelectedRWs onto a copy of the last
1258 // sequence (split the current operand into N operands).
1259 // Note that write sequences should be expanded within this loop--the entire
1260 // sequence belongs to a single operand.
1261 for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
1262 RWI != RWE; ++RWI, ++OperIdx) {
1263 IdxVec ExpandedRWs;
1264 if (IsRead)
1265 ExpandedRWs.push_back(*RWI);
1266 else
1267 SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
1268 RWSequences[OperIdx].insert(RWSequences[OperIdx].end(),
1269 ExpandedRWs.begin(), ExpandedRWs.end());
1270 }
1271 assert(OperIdx == RWSequences.size() && "missed a sequence");
1272 }
1273 else {
1274 // Push this transition's expanded sequence onto this transition's last
1275 // sequence (add to the current operand's sequence).
1276 SmallVectorImpl<unsigned> &Seq = RWSequences.back();
1277 IdxVec ExpandedRWs;
1278 for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
1279 RWI != RWE; ++RWI) {
1280 if (IsRead)
1281 ExpandedRWs.push_back(*RWI);
1282 else
1283 SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
1284 }
1285 Seq.insert(Seq.end(), ExpandedRWs.begin(), ExpandedRWs.end());
1286 }
1287}
1288
1289// RWSeq is a sequence of all Reads or all Writes for the next read or write
1290// operand. StartIdx is an index into TransVec where partial results
Andrew Trick9257b8f2012-09-22 02:24:21 +00001291// starts. RWSeq must be applied to all transitions between StartIdx and the end
Andrew Trick33401e82012-09-15 00:19:59 +00001292// of TransVec.
1293void PredTransitions::substituteVariantOperand(
1294 const SmallVectorImpl<unsigned> &RWSeq, bool IsRead, unsigned StartIdx) {
1295
1296 // Visit each original RW within the current sequence.
1297 for (SmallVectorImpl<unsigned>::const_iterator
1298 RWI = RWSeq.begin(), RWE = RWSeq.end(); RWI != RWE; ++RWI) {
1299 const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(*RWI, IsRead);
1300 // Push this RW on all partial PredTransitions or distribute variants.
1301 // New PredTransitions may be pushed within this loop which should not be
1302 // revisited (TransEnd must be loop invariant).
1303 for (unsigned TransIdx = StartIdx, TransEnd = TransVec.size();
1304 TransIdx != TransEnd; ++TransIdx) {
1305 // In the common case, push RW onto the current operand's sequence.
Andrew Trick9257b8f2012-09-22 02:24:21 +00001306 if (!hasAliasedVariants(SchedRW, SchedModels)) {
Andrew Trick33401e82012-09-15 00:19:59 +00001307 if (IsRead)
1308 TransVec[TransIdx].ReadSequences.back().push_back(*RWI);
1309 else
1310 TransVec[TransIdx].WriteSequences.back().push_back(*RWI);
1311 continue;
1312 }
1313 // Distribute this partial PredTransition across intersecting variants.
Andrew Trickda984b12012-10-03 23:06:28 +00001314 // This will push a copies of TransVec[TransIdx] on the back of TransVec.
Andrew Trick9257b8f2012-09-22 02:24:21 +00001315 std::vector<TransVariant> IntersectingVariants;
Andrew Trickda984b12012-10-03 23:06:28 +00001316 getIntersectingVariants(SchedRW, TransIdx, IntersectingVariants);
Andrew Trick33401e82012-09-15 00:19:59 +00001317 // Now expand each variant on top of its copy of the transition.
Andrew Trick9257b8f2012-09-22 02:24:21 +00001318 for (std::vector<TransVariant>::const_iterator
Andrew Trick33401e82012-09-15 00:19:59 +00001319 IVI = IntersectingVariants.begin(),
1320 IVE = IntersectingVariants.end();
Andrew Trick9257b8f2012-09-22 02:24:21 +00001321 IVI != IVE; ++IVI) {
1322 pushVariant(*IVI, IsRead);
1323 }
Andrew Trick33401e82012-09-15 00:19:59 +00001324 }
1325 }
1326}
1327
1328// For each variant of a Read/Write in Trans, substitute the sequence of
1329// Read/Writes guarded by the variant. This is exponential in the number of
1330// variant Read/Writes, but in practice detection of mutually exclusive
1331// predicates should result in linear growth in the total number variants.
1332//
1333// This is one step in a breadth-first search of nested variants.
1334void PredTransitions::substituteVariants(const PredTransition &Trans) {
1335 // Build up a set of partial results starting at the back of
1336 // PredTransitions. Remember the first new transition.
1337 unsigned StartIdx = TransVec.size();
Craig Topper195aaaf2018-03-22 06:15:10 +00001338 TransVec.emplace_back();
Andrew Trick33401e82012-09-15 00:19:59 +00001339 TransVec.back().PredTerm = Trans.PredTerm;
Andrew Trick9257b8f2012-09-22 02:24:21 +00001340 TransVec.back().ProcIndices = Trans.ProcIndices;
Andrew Trick33401e82012-09-15 00:19:59 +00001341
1342 // Visit each original write sequence.
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001343 for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
Andrew Trick33401e82012-09-15 00:19:59 +00001344 WSI = Trans.WriteSequences.begin(), WSE = Trans.WriteSequences.end();
1345 WSI != WSE; ++WSI) {
1346 // Push a new (empty) write sequence onto all partial Transitions.
1347 for (std::vector<PredTransition>::iterator I =
1348 TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
Craig Topper195aaaf2018-03-22 06:15:10 +00001349 I->WriteSequences.emplace_back();
Andrew Trick33401e82012-09-15 00:19:59 +00001350 }
1351 substituteVariantOperand(*WSI, /*IsRead=*/false, StartIdx);
1352 }
1353 // Visit each original read sequence.
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001354 for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
Andrew Trick33401e82012-09-15 00:19:59 +00001355 RSI = Trans.ReadSequences.begin(), RSE = Trans.ReadSequences.end();
1356 RSI != RSE; ++RSI) {
1357 // Push a new (empty) read sequence onto all partial Transitions.
1358 for (std::vector<PredTransition>::iterator I =
1359 TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
Craig Topper195aaaf2018-03-22 06:15:10 +00001360 I->ReadSequences.emplace_back();
Andrew Trick33401e82012-09-15 00:19:59 +00001361 }
1362 substituteVariantOperand(*RSI, /*IsRead=*/true, StartIdx);
1363 }
1364}
1365
Andrew Trick33401e82012-09-15 00:19:59 +00001366// Create a new SchedClass for each variant found by inferFromRW. Pass
Andrew Trick33401e82012-09-15 00:19:59 +00001367static void inferFromTransitions(ArrayRef<PredTransition> LastTransitions,
Andrew Trick9257b8f2012-09-22 02:24:21 +00001368 unsigned FromClassIdx,
Andrew Trick33401e82012-09-15 00:19:59 +00001369 CodeGenSchedModels &SchedModels) {
1370 // For each PredTransition, create a new CodeGenSchedTransition, which usually
1371 // requires creating a new SchedClass.
1372 for (ArrayRef<PredTransition>::iterator
1373 I = LastTransitions.begin(), E = LastTransitions.end(); I != E; ++I) {
1374 IdxVec OperWritesVariant;
Craig Topper1970e952018-03-20 20:24:12 +00001375 transform(I->WriteSequences, std::back_inserter(OperWritesVariant),
1376 [&SchedModels](ArrayRef<unsigned> WS) {
1377 return SchedModels.findOrInsertRW(WS, /*IsRead=*/false);
1378 });
Andrew Trick33401e82012-09-15 00:19:59 +00001379 IdxVec OperReadsVariant;
Craig Topper1970e952018-03-20 20:24:12 +00001380 transform(I->ReadSequences, std::back_inserter(OperReadsVariant),
1381 [&SchedModels](ArrayRef<unsigned> RS) {
1382 return SchedModels.findOrInsertRW(RS, /*IsRead=*/true);
1383 });
Andrew Trick33401e82012-09-15 00:19:59 +00001384 CodeGenSchedTransition SCTrans;
1385 SCTrans.ToClassIdx =
Craig Topper24064772014-04-15 07:20:03 +00001386 SchedModels.addSchedClass(/*ItinClassDef=*/nullptr, OperWritesVariant,
Craig Topper2ed54072018-03-24 22:58:03 +00001387 OperReadsVariant, I->ProcIndices);
1388 SCTrans.ProcIndices.assign(I->ProcIndices.begin(), I->ProcIndices.end());
Andrew Trick33401e82012-09-15 00:19:59 +00001389 // The final PredTerm is unique set of predicates guarding the transition.
1390 RecVec Preds;
Craig Topper1970e952018-03-20 20:24:12 +00001391 transform(I->PredTerm, std::back_inserter(Preds),
1392 [](const PredCheck &P) {
1393 return P.Predicate;
1394 });
Craig Topperb5ed2752018-03-20 20:24:10 +00001395 Preds.erase(std::unique(Preds.begin(), Preds.end()), Preds.end());
Craig Topper18cfa2c2018-03-24 22:58:02 +00001396 SCTrans.PredTerm = std::move(Preds);
1397 SchedModels.getSchedClass(FromClassIdx)
1398 .Transitions.push_back(std::move(SCTrans));
Andrew Trick33401e82012-09-15 00:19:59 +00001399 }
1400}
1401
Andrew Trick9257b8f2012-09-22 02:24:21 +00001402// Create new SchedClasses for the given ReadWrite list. If any of the
1403// ReadWrites refers to a SchedVariant, create a new SchedClass for each variant
1404// of the ReadWrite list, following Aliases if necessary.
Benjamin Kramere1761952015-10-24 12:46:49 +00001405void CodeGenSchedModels::inferFromRW(ArrayRef<unsigned> OperWrites,
1406 ArrayRef<unsigned> OperReads,
Andrew Trick33401e82012-09-15 00:19:59 +00001407 unsigned FromClassIdx,
Benjamin Kramere1761952015-10-24 12:46:49 +00001408 ArrayRef<unsigned> ProcIndices) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001409 LLVM_DEBUG(dbgs() << "INFER RW proc("; dumpIdxVec(ProcIndices);
1410 dbgs() << ") ");
Andrew Trick33401e82012-09-15 00:19:59 +00001411
1412 // Create a seed transition with an empty PredTerm and the expanded sequences
1413 // of SchedWrites for the current SchedClass.
1414 std::vector<PredTransition> LastTransitions;
Craig Topper195aaaf2018-03-22 06:15:10 +00001415 LastTransitions.emplace_back();
Andrew Trick9257b8f2012-09-22 02:24:21 +00001416 LastTransitions.back().ProcIndices.append(ProcIndices.begin(),
1417 ProcIndices.end());
1418
Benjamin Kramere1761952015-10-24 12:46:49 +00001419 for (unsigned WriteIdx : OperWrites) {
Andrew Trick33401e82012-09-15 00:19:59 +00001420 IdxVec WriteSeq;
Benjamin Kramere1761952015-10-24 12:46:49 +00001421 expandRWSequence(WriteIdx, WriteSeq, /*IsRead=*/false);
Craig Topper195aaaf2018-03-22 06:15:10 +00001422 LastTransitions[0].WriteSequences.emplace_back();
1423 SmallVectorImpl<unsigned> &Seq = LastTransitions[0].WriteSequences.back();
Craig Topper1f57456c2018-03-20 20:24:14 +00001424 Seq.append(WriteSeq.begin(), WriteSeq.end());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001425 LLVM_DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
Andrew Trick33401e82012-09-15 00:19:59 +00001426 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001427 LLVM_DEBUG(dbgs() << " Reads: ");
Benjamin Kramere1761952015-10-24 12:46:49 +00001428 for (unsigned ReadIdx : OperReads) {
Andrew Trick33401e82012-09-15 00:19:59 +00001429 IdxVec ReadSeq;
Benjamin Kramere1761952015-10-24 12:46:49 +00001430 expandRWSequence(ReadIdx, ReadSeq, /*IsRead=*/true);
Craig Topper195aaaf2018-03-22 06:15:10 +00001431 LastTransitions[0].ReadSequences.emplace_back();
1432 SmallVectorImpl<unsigned> &Seq = LastTransitions[0].ReadSequences.back();
Craig Topper1f57456c2018-03-20 20:24:14 +00001433 Seq.append(ReadSeq.begin(), ReadSeq.end());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001434 LLVM_DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
Andrew Trick33401e82012-09-15 00:19:59 +00001435 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001436 LLVM_DEBUG(dbgs() << '\n');
Andrew Trick33401e82012-09-15 00:19:59 +00001437
1438 // Collect all PredTransitions for individual operands.
1439 // Iterate until no variant writes remain.
1440 while (hasVariant(LastTransitions, *this)) {
1441 PredTransitions Transitions(*this);
Craig Topperf6114252018-03-20 20:24:16 +00001442 for (const PredTransition &Trans : LastTransitions)
1443 Transitions.substituteVariants(Trans);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001444 LLVM_DEBUG(Transitions.dump());
Andrew Trick33401e82012-09-15 00:19:59 +00001445 LastTransitions.swap(Transitions.TransVec);
1446 }
1447 // If the first transition has no variants, nothing to do.
1448 if (LastTransitions[0].PredTerm.empty())
1449 return;
1450
1451 // WARNING: We are about to mutate the SchedClasses vector. Do not refer to
1452 // OperWrites, OperReads, or ProcIndices after calling inferFromTransitions.
Andrew Trick9257b8f2012-09-22 02:24:21 +00001453 inferFromTransitions(LastTransitions, FromClassIdx, *this);
Andrew Trick33401e82012-09-15 00:19:59 +00001454}
1455
Andrew Trickcf398b22013-04-23 23:45:14 +00001456// Check if any processor resource group contains all resource records in
1457// SubUnits.
1458bool CodeGenSchedModels::hasSuperGroup(RecVec &SubUnits, CodeGenProcModel &PM) {
1459 for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
1460 if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
1461 continue;
1462 RecVec SuperUnits =
1463 PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
1464 RecIter RI = SubUnits.begin(), RE = SubUnits.end();
1465 for ( ; RI != RE; ++RI) {
David Majnemer0d955d02016-08-11 22:21:41 +00001466 if (!is_contained(SuperUnits, *RI)) {
Andrew Trickcf398b22013-04-23 23:45:14 +00001467 break;
1468 }
1469 }
1470 if (RI == RE)
1471 return true;
1472 }
1473 return false;
1474}
1475
1476// Verify that overlapping groups have a common supergroup.
1477void CodeGenSchedModels::verifyProcResourceGroups(CodeGenProcModel &PM) {
1478 for (unsigned i = 0, e = PM.ProcResourceDefs.size(); i < e; ++i) {
1479 if (!PM.ProcResourceDefs[i]->isSubClassOf("ProcResGroup"))
1480 continue;
1481 RecVec CheckUnits =
1482 PM.ProcResourceDefs[i]->getValueAsListOfDefs("Resources");
1483 for (unsigned j = i+1; j < e; ++j) {
1484 if (!PM.ProcResourceDefs[j]->isSubClassOf("ProcResGroup"))
1485 continue;
1486 RecVec OtherUnits =
1487 PM.ProcResourceDefs[j]->getValueAsListOfDefs("Resources");
1488 if (std::find_first_of(CheckUnits.begin(), CheckUnits.end(),
1489 OtherUnits.begin(), OtherUnits.end())
1490 != CheckUnits.end()) {
1491 // CheckUnits and OtherUnits overlap
1492 OtherUnits.insert(OtherUnits.end(), CheckUnits.begin(),
1493 CheckUnits.end());
1494 if (!hasSuperGroup(OtherUnits, PM)) {
1495 PrintFatalError((PM.ProcResourceDefs[i])->getLoc(),
1496 "proc resource group overlaps with "
1497 + PM.ProcResourceDefs[j]->getName()
1498 + " but no supergroup contains both.");
1499 }
1500 }
1501 }
1502 }
1503}
1504
Andrea Di Biagio9da4d6d2018-04-03 13:36:24 +00001505// Collect all the RegisterFile definitions available in this target.
1506void CodeGenSchedModels::collectRegisterFiles() {
1507 RecVec RegisterFileDefs = Records.getAllDerivedDefinitions("RegisterFile");
1508
1509 // RegisterFiles is the vector of CodeGenRegisterFile.
1510 for (Record *RF : RegisterFileDefs) {
1511 // For each register file definition, construct a CodeGenRegisterFile object
1512 // and add it to the appropriate scheduling model.
1513 CodeGenProcModel &PM = getProcModel(RF->getValueAsDef("SchedModel"));
1514 PM.RegisterFiles.emplace_back(CodeGenRegisterFile(RF->getName(),RF));
1515 CodeGenRegisterFile &CGRF = PM.RegisterFiles.back();
1516
1517 // Now set the number of physical registers as well as the cost of registers
1518 // in each register class.
1519 CGRF.NumPhysRegs = RF->getValueAsInt("NumPhysRegs");
1520 RecVec RegisterClasses = RF->getValueAsListOfDefs("RegClasses");
1521 std::vector<int64_t> RegisterCosts = RF->getValueAsListOfInts("RegCosts");
1522 for (unsigned I = 0, E = RegisterClasses.size(); I < E; ++I) {
1523 int Cost = RegisterCosts.size() > I ? RegisterCosts[I] : 1;
1524 CGRF.Costs.emplace_back(RegisterClasses[I], Cost);
1525 }
1526 }
1527}
1528
Clement Courbetb4493792018-04-10 08:16:37 +00001529// Collect all the RegisterFile definitions available in this target.
1530void CodeGenSchedModels::collectPfmCounters() {
1531 for (Record *Def : Records.getAllDerivedDefinitions("PfmIssueCounter")) {
1532 CodeGenProcModel &PM = getProcModel(Def->getValueAsDef("SchedModel"));
1533 PM.PfmIssueCounterDefs.emplace_back(Def);
1534 }
1535 for (Record *Def : Records.getAllDerivedDefinitions("PfmCycleCounter")) {
1536 CodeGenProcModel &PM = getProcModel(Def->getValueAsDef("SchedModel"));
1537 if (PM.PfmCycleCounterDef) {
1538 PrintFatalError(Def->getLoc(),
1539 "multiple cycle counters for " +
1540 Def->getValueAsDef("SchedModel")->getName());
1541 }
1542 PM.PfmCycleCounterDef = Def;
1543 }
1544}
1545
Andrew Trick1e46d482012-09-15 00:20:02 +00001546// Collect and sort WriteRes, ReadAdvance, and ProcResources.
1547void CodeGenSchedModels::collectProcResources() {
Matthias Braun6b1fd9a2016-06-21 03:24:03 +00001548 ProcResourceDefs = Records.getAllDerivedDefinitions("ProcResourceUnits");
1549 ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
1550
Andrew Trick1e46d482012-09-15 00:20:02 +00001551 // Add any subtarget-specific SchedReadWrites that are directly associated
1552 // with processor resources. Refer to the parent SchedClass's ProcIndices to
1553 // determine which processors they apply to.
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001554 for (const CodeGenSchedClass &SC :
1555 make_range(schedClassBegin(), schedClassEnd())) {
1556 if (SC.ItinClassDef) {
1557 collectItinProcResources(SC.ItinClassDef);
1558 continue;
Andrew Trick4fe440d2013-02-01 03:19:54 +00001559 }
Andrea Di Biagio38fe2272018-04-26 12:56:26 +00001560
1561 // This class may have a default ReadWrite list which can be overriden by
1562 // InstRW definitions.
1563 for (Record *RW : SC.InstRWs) {
1564 Record *RWModelDef = RW->getValueAsDef("SchedModel");
1565 unsigned PIdx = getProcModel(RWModelDef).Index;
1566 IdxVec Writes, Reads;
1567 findRWs(RW->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1568 collectRWResources(Writes, Reads, PIdx);
1569 }
1570
1571 collectRWResources(SC.Writes, SC.Reads, SC.ProcIndices);
Andrew Trick1e46d482012-09-15 00:20:02 +00001572 }
1573 // Add resources separately defined by each subtarget.
1574 RecVec WRDefs = Records.getAllDerivedDefinitions("WriteRes");
Javed Absar2c9570c2017-10-11 09:33:23 +00001575 for (Record *WR : WRDefs) {
1576 Record *ModelDef = WR->getValueAsDef("SchedModel");
1577 addWriteRes(WR, getProcModel(ModelDef).Index);
Andrew Trick1e46d482012-09-15 00:20:02 +00001578 }
Andrew Trickdca870b2014-03-13 03:49:20 +00001579 RecVec SWRDefs = Records.getAllDerivedDefinitions("SchedWriteRes");
Javed Absar2c9570c2017-10-11 09:33:23 +00001580 for (Record *SWR : SWRDefs) {
1581 Record *ModelDef = SWR->getValueAsDef("SchedModel");
1582 addWriteRes(SWR, getProcModel(ModelDef).Index);
Andrew Trickdca870b2014-03-13 03:49:20 +00001583 }
Andrew Trick1e46d482012-09-15 00:20:02 +00001584 RecVec RADefs = Records.getAllDerivedDefinitions("ReadAdvance");
Javed Absar2c9570c2017-10-11 09:33:23 +00001585 for (Record *RA : RADefs) {
1586 Record *ModelDef = RA->getValueAsDef("SchedModel");
1587 addReadAdvance(RA, getProcModel(ModelDef).Index);
Andrew Trick1e46d482012-09-15 00:20:02 +00001588 }
Andrew Trickdca870b2014-03-13 03:49:20 +00001589 RecVec SRADefs = Records.getAllDerivedDefinitions("SchedReadAdvance");
Javed Absar2c9570c2017-10-11 09:33:23 +00001590 for (Record *SRA : SRADefs) {
1591 if (SRA->getValueInit("SchedModel")->isComplete()) {
1592 Record *ModelDef = SRA->getValueAsDef("SchedModel");
1593 addReadAdvance(SRA, getProcModel(ModelDef).Index);
Andrew Trickdca870b2014-03-13 03:49:20 +00001594 }
1595 }
Andrew Trick40c4f382013-06-15 04:50:06 +00001596 // Add ProcResGroups that are defined within this processor model, which may
1597 // not be directly referenced but may directly specify a buffer size.
1598 RecVec ProcResGroups = Records.getAllDerivedDefinitions("ProcResGroup");
Javed Absar21c75912017-10-09 16:21:25 +00001599 for (Record *PRG : ProcResGroups) {
Javed Absarfc500042017-10-05 13:27:43 +00001600 if (!PRG->getValueInit("SchedModel")->isComplete())
Andrew Trick40c4f382013-06-15 04:50:06 +00001601 continue;
Javed Absarfc500042017-10-05 13:27:43 +00001602 CodeGenProcModel &PM = getProcModel(PRG->getValueAsDef("SchedModel"));
1603 if (!is_contained(PM.ProcResourceDefs, PRG))
1604 PM.ProcResourceDefs.push_back(PRG);
Andrew Trick40c4f382013-06-15 04:50:06 +00001605 }
Clement Courbeteb4f5d22018-02-05 12:23:51 +00001606 // Add ProcResourceUnits unconditionally.
1607 for (Record *PRU : Records.getAllDerivedDefinitions("ProcResourceUnits")) {
1608 if (!PRU->getValueInit("SchedModel")->isComplete())
1609 continue;
1610 CodeGenProcModel &PM = getProcModel(PRU->getValueAsDef("SchedModel"));
1611 if (!is_contained(PM.ProcResourceDefs, PRU))
1612 PM.ProcResourceDefs.push_back(PRU);
1613 }
Andrew Trick1e46d482012-09-15 00:20:02 +00001614 // Finalize each ProcModel by sorting the record arrays.
Craig Topper8a417c12014-12-09 08:05:51 +00001615 for (CodeGenProcModel &PM : ProcModels) {
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00001616 llvm::sort(PM.WriteResDefs.begin(), PM.WriteResDefs.end(),
1617 LessRecord());
1618 llvm::sort(PM.ReadAdvanceDefs.begin(), PM.ReadAdvanceDefs.end(),
1619 LessRecord());
1620 llvm::sort(PM.ProcResourceDefs.begin(), PM.ProcResourceDefs.end(),
1621 LessRecord());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001622 LLVM_DEBUG(
1623 PM.dump();
1624 dbgs() << "WriteResDefs: "; for (RecIter RI = PM.WriteResDefs.begin(),
1625 RE = PM.WriteResDefs.end();
1626 RI != RE; ++RI) {
1627 if ((*RI)->isSubClassOf("WriteRes"))
1628 dbgs() << (*RI)->getValueAsDef("WriteType")->getName() << " ";
1629 else
1630 dbgs() << (*RI)->getName() << " ";
1631 } dbgs() << "\nReadAdvanceDefs: ";
1632 for (RecIter RI = PM.ReadAdvanceDefs.begin(),
1633 RE = PM.ReadAdvanceDefs.end();
1634 RI != RE; ++RI) {
1635 if ((*RI)->isSubClassOf("ReadAdvance"))
1636 dbgs() << (*RI)->getValueAsDef("ReadType")->getName() << " ";
1637 else
1638 dbgs() << (*RI)->getName() << " ";
1639 } dbgs()
1640 << "\nProcResourceDefs: ";
1641 for (RecIter RI = PM.ProcResourceDefs.begin(),
1642 RE = PM.ProcResourceDefs.end();
1643 RI != RE; ++RI) { dbgs() << (*RI)->getName() << " "; } dbgs()
1644 << '\n');
Andrew Trickcf398b22013-04-23 23:45:14 +00001645 verifyProcResourceGroups(PM);
Andrew Trick1e46d482012-09-15 00:20:02 +00001646 }
Matthias Braun6b1fd9a2016-06-21 03:24:03 +00001647
1648 ProcResourceDefs.clear();
1649 ProcResGroups.clear();
Andrew Trick1e46d482012-09-15 00:20:02 +00001650}
1651
Matthias Braun17cb5792016-03-01 20:03:21 +00001652void CodeGenSchedModels::checkCompleteness() {
1653 bool Complete = true;
1654 bool HadCompleteModel = false;
1655 for (const CodeGenProcModel &ProcModel : procModels()) {
Simon Pilgrim1d793b82018-04-05 13:11:36 +00001656 const bool HasItineraries = ProcModel.hasItineraries();
Matthias Braun17cb5792016-03-01 20:03:21 +00001657 if (!ProcModel.ModelDef->getValueAsBit("CompleteModel"))
1658 continue;
1659 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
1660 if (Inst->hasNoSchedulingInfo)
1661 continue;
Simon Dardis5f95c9a2016-06-24 08:43:27 +00001662 if (ProcModel.isUnsupported(*Inst))
1663 continue;
Matthias Braun17cb5792016-03-01 20:03:21 +00001664 unsigned SCIdx = getSchedClassIdx(*Inst);
1665 if (!SCIdx) {
1666 if (Inst->TheDef->isValueUnset("SchedRW") && !HadCompleteModel) {
1667 PrintError("No schedule information for instruction '"
1668 + Inst->TheDef->getName() + "'");
1669 Complete = false;
1670 }
1671 continue;
1672 }
1673
1674 const CodeGenSchedClass &SC = getSchedClass(SCIdx);
1675 if (!SC.Writes.empty())
1676 continue;
Simon Pilgrim1d793b82018-04-05 13:11:36 +00001677 if (HasItineraries && SC.ItinClassDef != nullptr &&
Ulrich Weigand75cda2f2016-10-31 18:59:52 +00001678 SC.ItinClassDef->getName() != "NoItinerary")
Matthias Braun42d9ad92016-03-03 00:04:59 +00001679 continue;
Matthias Braun17cb5792016-03-01 20:03:21 +00001680
1681 const RecVec &InstRWs = SC.InstRWs;
David Majnemer562e8292016-08-12 00:18:03 +00001682 auto I = find_if(InstRWs, [&ProcModel](const Record *R) {
1683 return R->getValueAsDef("SchedModel") == ProcModel.ModelDef;
1684 });
Matthias Braun17cb5792016-03-01 20:03:21 +00001685 if (I == InstRWs.end()) {
1686 PrintError("'" + ProcModel.ModelName + "' lacks information for '" +
1687 Inst->TheDef->getName() + "'");
1688 Complete = false;
1689 }
1690 }
1691 HadCompleteModel = true;
1692 }
Matthias Brauna939bd02016-03-01 21:36:12 +00001693 if (!Complete) {
1694 errs() << "\n\nIncomplete schedule models found.\n"
1695 << "- Consider setting 'CompleteModel = 0' while developing new models.\n"
1696 << "- Pseudo instructions can be marked with 'hasNoSchedulingInfo = 1'.\n"
1697 << "- Instructions should usually have Sched<[...]> as a superclass, "
Simon Dardis5f95c9a2016-06-24 08:43:27 +00001698 "you may temporarily use an empty list.\n"
1699 << "- Instructions related to unsupported features can be excluded with "
1700 "list<Predicate> UnsupportedFeatures = [HasA,..,HasY]; in the "
1701 "processor model.\n\n";
Matthias Braun17cb5792016-03-01 20:03:21 +00001702 PrintFatalError("Incomplete schedule model");
Matthias Brauna939bd02016-03-01 21:36:12 +00001703 }
Matthias Braun17cb5792016-03-01 20:03:21 +00001704}
1705
Andrew Trick1e46d482012-09-15 00:20:02 +00001706// Collect itinerary class resources for each processor.
1707void CodeGenSchedModels::collectItinProcResources(Record *ItinClassDef) {
1708 for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
1709 const CodeGenProcModel &PM = ProcModels[PIdx];
1710 // For all ItinRW entries.
1711 bool HasMatch = false;
1712 for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
1713 II != IE; ++II) {
1714 RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
1715 if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
1716 continue;
1717 if (HasMatch)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001718 PrintFatalError((*II)->getLoc(), "Duplicate itinerary class "
1719 + ItinClassDef->getName()
1720 + " in ItinResources for " + PM.ModelName);
Andrew Trick1e46d482012-09-15 00:20:02 +00001721 HasMatch = true;
1722 IdxVec Writes, Reads;
1723 findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
Craig Topper9f3293a2018-03-24 21:57:35 +00001724 collectRWResources(Writes, Reads, PIdx);
Andrew Trick1e46d482012-09-15 00:20:02 +00001725 }
1726 }
1727}
1728
Andrew Trickd0b9c442012-10-10 05:43:13 +00001729void CodeGenSchedModels::collectRWResources(unsigned RWIdx, bool IsRead,
Benjamin Kramere1761952015-10-24 12:46:49 +00001730 ArrayRef<unsigned> ProcIndices) {
Andrew Trickd0b9c442012-10-10 05:43:13 +00001731 const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
1732 if (SchedRW.TheDef) {
1733 if (!IsRead && SchedRW.TheDef->isSubClassOf("SchedWriteRes")) {
Benjamin Kramere1761952015-10-24 12:46:49 +00001734 for (unsigned Idx : ProcIndices)
1735 addWriteRes(SchedRW.TheDef, Idx);
Andrew Trickd0b9c442012-10-10 05:43:13 +00001736 }
1737 else if (IsRead && SchedRW.TheDef->isSubClassOf("SchedReadAdvance")) {
Benjamin Kramere1761952015-10-24 12:46:49 +00001738 for (unsigned Idx : ProcIndices)
1739 addReadAdvance(SchedRW.TheDef, Idx);
Andrew Trickd0b9c442012-10-10 05:43:13 +00001740 }
1741 }
1742 for (RecIter AI = SchedRW.Aliases.begin(), AE = SchedRW.Aliases.end();
1743 AI != AE; ++AI) {
1744 IdxVec AliasProcIndices;
1745 if ((*AI)->getValueInit("SchedModel")->isComplete()) {
1746 AliasProcIndices.push_back(
1747 getProcModel((*AI)->getValueAsDef("SchedModel")).Index);
1748 }
1749 else
1750 AliasProcIndices = ProcIndices;
1751 const CodeGenSchedRW &AliasRW = getSchedRW((*AI)->getValueAsDef("AliasRW"));
1752 assert(AliasRW.IsRead == IsRead && "cannot alias reads to writes");
1753
1754 IdxVec ExpandedRWs;
1755 expandRWSequence(AliasRW.Index, ExpandedRWs, IsRead);
1756 for (IdxIter SI = ExpandedRWs.begin(), SE = ExpandedRWs.end();
1757 SI != SE; ++SI) {
1758 collectRWResources(*SI, IsRead, AliasProcIndices);
1759 }
1760 }
1761}
Andrew Trick1e46d482012-09-15 00:20:02 +00001762
1763// Collect resources for a set of read/write types and processor indices.
Benjamin Kramere1761952015-10-24 12:46:49 +00001764void CodeGenSchedModels::collectRWResources(ArrayRef<unsigned> Writes,
1765 ArrayRef<unsigned> Reads,
1766 ArrayRef<unsigned> ProcIndices) {
Benjamin Kramere1761952015-10-24 12:46:49 +00001767 for (unsigned Idx : Writes)
1768 collectRWResources(Idx, /*IsRead=*/false, ProcIndices);
Andrew Trickd0b9c442012-10-10 05:43:13 +00001769
Benjamin Kramere1761952015-10-24 12:46:49 +00001770 for (unsigned Idx : Reads)
1771 collectRWResources(Idx, /*IsRead=*/true, ProcIndices);
Andrew Trick1e46d482012-09-15 00:20:02 +00001772}
1773
1774// Find the processor's resource units for this kind of resource.
1775Record *CodeGenSchedModels::findProcResUnits(Record *ProcResKind,
Evandro Menezes9dc54e22017-11-21 21:33:52 +00001776 const CodeGenProcModel &PM,
1777 ArrayRef<SMLoc> Loc) const {
Andrew Trick1e46d482012-09-15 00:20:02 +00001778 if (ProcResKind->isSubClassOf("ProcResourceUnits"))
1779 return ProcResKind;
1780
Craig Topper24064772014-04-15 07:20:03 +00001781 Record *ProcUnitDef = nullptr;
Matthias Braun6b1fd9a2016-06-21 03:24:03 +00001782 assert(!ProcResourceDefs.empty());
1783 assert(!ProcResGroups.empty());
Andrew Trick1e46d482012-09-15 00:20:02 +00001784
Javed Absar67b042c2017-09-13 10:31:10 +00001785 for (Record *ProcResDef : ProcResourceDefs) {
1786 if (ProcResDef->getValueAsDef("Kind") == ProcResKind
1787 && ProcResDef->getValueAsDef("SchedModel") == PM.ModelDef) {
Andrew Trick1e46d482012-09-15 00:20:02 +00001788 if (ProcUnitDef) {
Evandro Menezes9dc54e22017-11-21 21:33:52 +00001789 PrintFatalError(Loc,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001790 "Multiple ProcessorResourceUnits associated with "
1791 + ProcResKind->getName());
Andrew Trick1e46d482012-09-15 00:20:02 +00001792 }
Javed Absar67b042c2017-09-13 10:31:10 +00001793 ProcUnitDef = ProcResDef;
Andrew Trick1e46d482012-09-15 00:20:02 +00001794 }
1795 }
Javed Absar67b042c2017-09-13 10:31:10 +00001796 for (Record *ProcResGroup : ProcResGroups) {
1797 if (ProcResGroup == ProcResKind
1798 && ProcResGroup->getValueAsDef("SchedModel") == PM.ModelDef) {
Andrew Trick4e67cba2013-03-14 21:21:50 +00001799 if (ProcUnitDef) {
Evandro Menezes9dc54e22017-11-21 21:33:52 +00001800 PrintFatalError(Loc,
Andrew Trick4e67cba2013-03-14 21:21:50 +00001801 "Multiple ProcessorResourceUnits associated with "
1802 + ProcResKind->getName());
1803 }
Javed Absar67b042c2017-09-13 10:31:10 +00001804 ProcUnitDef = ProcResGroup;
Andrew Trick4e67cba2013-03-14 21:21:50 +00001805 }
1806 }
Andrew Trick1e46d482012-09-15 00:20:02 +00001807 if (!ProcUnitDef) {
Evandro Menezes9dc54e22017-11-21 21:33:52 +00001808 PrintFatalError(Loc,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001809 "No ProcessorResources associated with "
1810 + ProcResKind->getName());
Andrew Trick1e46d482012-09-15 00:20:02 +00001811 }
1812 return ProcUnitDef;
1813}
1814
1815// Iteratively add a resource and its super resources.
1816void CodeGenSchedModels::addProcResource(Record *ProcResKind,
Evandro Menezes9dc54e22017-11-21 21:33:52 +00001817 CodeGenProcModel &PM,
1818 ArrayRef<SMLoc> Loc) {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001819 while (true) {
Evandro Menezes9dc54e22017-11-21 21:33:52 +00001820 Record *ProcResUnits = findProcResUnits(ProcResKind, PM, Loc);
Andrew Trick1e46d482012-09-15 00:20:02 +00001821
1822 // See if this ProcResource is already associated with this processor.
David Majnemer42531262016-08-12 03:55:06 +00001823 if (is_contained(PM.ProcResourceDefs, ProcResUnits))
Andrew Trick1e46d482012-09-15 00:20:02 +00001824 return;
1825
1826 PM.ProcResourceDefs.push_back(ProcResUnits);
Andrew Trick4e67cba2013-03-14 21:21:50 +00001827 if (ProcResUnits->isSubClassOf("ProcResGroup"))
1828 return;
1829
Andrew Trick1e46d482012-09-15 00:20:02 +00001830 if (!ProcResUnits->getValueInit("Super")->isComplete())
1831 return;
1832
1833 ProcResKind = ProcResUnits->getValueAsDef("Super");
1834 }
1835}
1836
1837// Add resources for a SchedWrite to this processor if they don't exist.
1838void CodeGenSchedModels::addWriteRes(Record *ProcWriteResDef, unsigned PIdx) {
Andrew Trick9257b8f2012-09-22 02:24:21 +00001839 assert(PIdx && "don't add resources to an invalid Processor model");
1840
Andrew Trick1e46d482012-09-15 00:20:02 +00001841 RecVec &WRDefs = ProcModels[PIdx].WriteResDefs;
David Majnemer42531262016-08-12 03:55:06 +00001842 if (is_contained(WRDefs, ProcWriteResDef))
Andrew Trick1e46d482012-09-15 00:20:02 +00001843 return;
1844 WRDefs.push_back(ProcWriteResDef);
1845
1846 // Visit ProcResourceKinds referenced by the newly discovered WriteRes.
1847 RecVec ProcResDefs = ProcWriteResDef->getValueAsListOfDefs("ProcResources");
1848 for (RecIter WritePRI = ProcResDefs.begin(), WritePRE = ProcResDefs.end();
1849 WritePRI != WritePRE; ++WritePRI) {
Evandro Menezes9dc54e22017-11-21 21:33:52 +00001850 addProcResource(*WritePRI, ProcModels[PIdx], ProcWriteResDef->getLoc());
Andrew Trick1e46d482012-09-15 00:20:02 +00001851 }
1852}
1853
1854// Add resources for a ReadAdvance to this processor if they don't exist.
1855void CodeGenSchedModels::addReadAdvance(Record *ProcReadAdvanceDef,
1856 unsigned PIdx) {
1857 RecVec &RADefs = ProcModels[PIdx].ReadAdvanceDefs;
David Majnemer42531262016-08-12 03:55:06 +00001858 if (is_contained(RADefs, ProcReadAdvanceDef))
Andrew Trick1e46d482012-09-15 00:20:02 +00001859 return;
1860 RADefs.push_back(ProcReadAdvanceDef);
1861}
1862
Andrew Trick8fa00f52012-09-17 22:18:43 +00001863unsigned CodeGenProcModel::getProcResourceIdx(Record *PRDef) const {
David Majnemer0d955d02016-08-11 22:21:41 +00001864 RecIter PRPos = find(ProcResourceDefs, PRDef);
Andrew Trick8fa00f52012-09-17 22:18:43 +00001865 if (PRPos == ProcResourceDefs.end())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001866 PrintFatalError(PRDef->getLoc(), "ProcResource def is not included in "
1867 "the ProcResources list for " + ModelName);
Andrew Trick8fa00f52012-09-17 22:18:43 +00001868 // Idx=0 is reserved for invalid.
Rafael Espindola72961392012-11-02 20:57:36 +00001869 return 1 + (PRPos - ProcResourceDefs.begin());
Andrew Trick8fa00f52012-09-17 22:18:43 +00001870}
1871
Simon Dardis5f95c9a2016-06-24 08:43:27 +00001872bool CodeGenProcModel::isUnsupported(const CodeGenInstruction &Inst) const {
1873 for (const Record *TheDef : UnsupportedFeaturesDefs) {
1874 for (const Record *PredDef : Inst.TheDef->getValueAsListOfDefs("Predicates")) {
1875 if (TheDef->getName() == PredDef->getName())
1876 return true;
1877 }
1878 }
1879 return false;
1880}
1881
Andrew Trick76686492012-09-15 00:19:57 +00001882#ifndef NDEBUG
1883void CodeGenProcModel::dump() const {
1884 dbgs() << Index << ": " << ModelName << " "
1885 << (ModelDef ? ModelDef->getName() : "inferred") << " "
1886 << (ItinsDef ? ItinsDef->getName() : "no itinerary") << '\n';
1887}
1888
1889void CodeGenSchedRW::dump() const {
1890 dbgs() << Name << (IsVariadic ? " (V) " : " ");
1891 if (IsSequence) {
1892 dbgs() << "(";
1893 dumpIdxVec(Sequence);
1894 dbgs() << ")";
1895 }
1896}
1897
1898void CodeGenSchedClass::dump(const CodeGenSchedModels* SchedModels) const {
Andrew Trickbf8a28d2013-03-16 18:58:55 +00001899 dbgs() << "SCHEDCLASS " << Index << ":" << Name << '\n'
Andrew Trick76686492012-09-15 00:19:57 +00001900 << " Writes: ";
1901 for (unsigned i = 0, N = Writes.size(); i < N; ++i) {
1902 SchedModels->getSchedWrite(Writes[i]).dump();
1903 if (i < N-1) {
1904 dbgs() << '\n';
1905 dbgs().indent(10);
1906 }
1907 }
1908 dbgs() << "\n Reads: ";
1909 for (unsigned i = 0, N = Reads.size(); i < N; ++i) {
1910 SchedModels->getSchedRead(Reads[i]).dump();
1911 if (i < N-1) {
1912 dbgs() << '\n';
1913 dbgs().indent(10);
1914 }
1915 }
1916 dbgs() << "\n ProcIdx: "; dumpIdxVec(ProcIndices); dbgs() << '\n';
Andrew Tricke97978f2013-03-26 21:36:39 +00001917 if (!Transitions.empty()) {
1918 dbgs() << "\n Transitions for Proc ";
Javed Absar67b042c2017-09-13 10:31:10 +00001919 for (const CodeGenSchedTransition &Transition : Transitions) {
1920 dumpIdxVec(Transition.ProcIndices);
Andrew Tricke97978f2013-03-26 21:36:39 +00001921 }
1922 }
Andrew Trick76686492012-09-15 00:19:57 +00001923}
Andrew Trick33401e82012-09-15 00:19:59 +00001924
1925void PredTransitions::dump() const {
1926 dbgs() << "Expanded Variants:\n";
1927 for (std::vector<PredTransition>::const_iterator
1928 TI = TransVec.begin(), TE = TransVec.end(); TI != TE; ++TI) {
1929 dbgs() << "{";
1930 for (SmallVectorImpl<PredCheck>::const_iterator
1931 PCI = TI->PredTerm.begin(), PCE = TI->PredTerm.end();
1932 PCI != PCE; ++PCI) {
1933 if (PCI != TI->PredTerm.begin())
1934 dbgs() << ", ";
1935 dbgs() << SchedModels.getSchedRW(PCI->RWIdx, PCI->IsRead).Name
1936 << ":" << PCI->Predicate->getName();
1937 }
1938 dbgs() << "},\n => {";
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001939 for (SmallVectorImpl<SmallVector<unsigned,4>>::const_iterator
Andrew Trick33401e82012-09-15 00:19:59 +00001940 WSI = TI->WriteSequences.begin(), WSE = TI->WriteSequences.end();
1941 WSI != WSE; ++WSI) {
1942 dbgs() << "(";
1943 for (SmallVectorImpl<unsigned>::const_iterator
1944 WI = WSI->begin(), WE = WSI->end(); WI != WE; ++WI) {
1945 if (WI != WSI->begin())
1946 dbgs() << ", ";
1947 dbgs() << SchedModels.getSchedWrite(*WI).Name;
1948 }
1949 dbgs() << "),";
1950 }
1951 dbgs() << "}\n";
1952 }
1953}
Andrew Trick76686492012-09-15 00:19:57 +00001954#endif // NDEBUG