blob: 0babda3c4f566f8a24964697ad519a2fdf90aaa2 [file] [log] [blame]
Andrew Trick2661b412012-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//
10// This file defines structures to encapsulate the machine model as decribed in
11// the target description.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "subtarget-emitter"
16
17#include "CodeGenSchedule.h"
18#include "CodeGenTarget.h"
Andrew Trick48605c32012-09-15 00:19:57 +000019#include "llvm/TableGen/Error.h"
Andrew Trick2661b412012-07-07 04:00:00 +000020#include "llvm/Support/Debug.h"
21
22using namespace llvm;
23
Andrew Trick48605c32012-09-15 00:19:57 +000024#ifndef NDEBUG
25static void dumpIdxVec(const IdxVec &V) {
26 for (unsigned i = 0, e = V.size(); i < e; ++i) {
27 dbgs() << V[i] << ", ";
28 }
29}
Andrew Trick5e613c22012-09-15 00:19:59 +000030static void dumpIdxVec(const SmallVectorImpl<unsigned> &V) {
31 for (unsigned i = 0, e = V.size(); i < e; ++i) {
32 dbgs() << V[i] << ", ";
33 }
34}
Andrew Trick48605c32012-09-15 00:19:57 +000035#endif
36
37/// CodeGenModels ctor interprets machine model records and populates maps.
Andrew Trick2661b412012-07-07 04:00:00 +000038CodeGenSchedModels::CodeGenSchedModels(RecordKeeper &RK,
39 const CodeGenTarget &TGT):
Andrew Trick48605c32012-09-15 00:19:57 +000040 Records(RK), Target(TGT), NumItineraryClasses(0) {
Andrew Trick2661b412012-07-07 04:00:00 +000041
Andrew Trick48605c32012-09-15 00:19:57 +000042 // Instantiate a CodeGenProcModel for each SchedMachineModel with the values
43 // that are explicitly referenced in tablegen records. Resources associated
44 // with each processor will be derived later. Populate ProcModelMap with the
45 // CodeGenProcModel instances.
46 collectProcModels();
Andrew Trick2661b412012-07-07 04:00:00 +000047
Andrew Trick48605c32012-09-15 00:19:57 +000048 // Instantiate a CodeGenSchedRW for each SchedReadWrite record explicitly
49 // defined, and populate SchedReads and SchedWrites vectors. Implicit
50 // SchedReadWrites that represent sequences derived from expanded variant will
51 // be inferred later.
52 collectSchedRW();
53
54 // Instantiate a CodeGenSchedClass for each unique SchedRW signature directly
55 // required by an instruction definition, and populate SchedClassIdxMap. Set
56 // NumItineraryClasses to the number of explicit itinerary classes referenced
57 // by instructions. Set NumInstrSchedClasses to the number of itinerary
58 // classes plus any classes implied by instructions that derive from class
59 // Sched and provide SchedRW list. This does not infer any new classes from
60 // SchedVariant.
61 collectSchedClasses();
62
63 // Find instruction itineraries for each processor. Sort and populate
64 // CodeGenProcMode::ItinDefList. (Cycle-to-cycle itineraries). This requires
65 // all itinerary classes to be discovered.
66 collectProcItins();
67
68 // Find ItinRW records for each processor and itinerary class.
69 // (For per-operand resources mapped to itinerary classes).
70 collectProcItinRW();
Andrew Trick5e613c22012-09-15 00:19:59 +000071
72 // Infer new SchedClasses from SchedVariant.
73 inferSchedClasses();
74
75 DEBUG(for (unsigned i = 0; i < SchedClasses.size(); ++i)
76 SchedClasses[i].dump(this));
Andrew Trick3cbd1782012-09-15 00:20:02 +000077
78 // Populate each CodeGenProcModel's WriteResDefs, ReadAdvanceDefs, and
79 // ProcResourceDefs.
80 collectProcResources();
Andrew Trick2661b412012-07-07 04:00:00 +000081}
82
Andrew Trick48605c32012-09-15 00:19:57 +000083/// Gather all processor models.
84void CodeGenSchedModels::collectProcModels() {
85 RecVec ProcRecords = Records.getAllDerivedDefinitions("Processor");
86 std::sort(ProcRecords.begin(), ProcRecords.end(), LessRecordFieldName());
Andrew Trick2661b412012-07-07 04:00:00 +000087
Andrew Trick48605c32012-09-15 00:19:57 +000088 // Reserve space because we can. Reallocation would be ok.
89 ProcModels.reserve(ProcRecords.size()+1);
90
91 // Use idx=0 for NoModel/NoItineraries.
92 Record *NoModelDef = Records.getDef("NoSchedModel");
93 Record *NoItinsDef = Records.getDef("NoItineraries");
94 ProcModels.push_back(CodeGenProcModel(0, "NoSchedModel",
95 NoModelDef, NoItinsDef));
96 ProcModelMap[NoModelDef] = 0;
97
98 // For each processor, find a unique machine model.
99 for (unsigned i = 0, N = ProcRecords.size(); i < N; ++i)
100 addProcModel(ProcRecords[i]);
101}
102
103/// Get a unique processor model based on the defined MachineModel and
104/// ProcessorItineraries.
105void CodeGenSchedModels::addProcModel(Record *ProcDef) {
106 Record *ModelKey = getModelOrItinDef(ProcDef);
107 if (!ProcModelMap.insert(std::make_pair(ModelKey, ProcModels.size())).second)
108 return;
109
110 std::string Name = ModelKey->getName();
111 if (ModelKey->isSubClassOf("SchedMachineModel")) {
112 Record *ItinsDef = ModelKey->getValueAsDef("Itineraries");
113 ProcModels.push_back(
114 CodeGenProcModel(ProcModels.size(), Name, ModelKey, ItinsDef));
115 }
116 else {
117 // An itinerary is defined without a machine model. Infer a new model.
118 if (!ModelKey->getValueAsListOfDefs("IID").empty())
119 Name = Name + "Model";
120 ProcModels.push_back(
121 CodeGenProcModel(ProcModels.size(), Name,
122 ProcDef->getValueAsDef("SchedModel"), ModelKey));
123 }
124 DEBUG(ProcModels.back().dump());
125}
126
127// Recursively find all reachable SchedReadWrite records.
128static void scanSchedRW(Record *RWDef, RecVec &RWDefs,
129 SmallPtrSet<Record*, 16> &RWSet) {
130 if (!RWSet.insert(RWDef))
131 return;
132 RWDefs.push_back(RWDef);
133 // Reads don't current have sequence records, but it can be added later.
134 if (RWDef->isSubClassOf("WriteSequence")) {
135 RecVec Seq = RWDef->getValueAsListOfDefs("Writes");
136 for (RecIter I = Seq.begin(), E = Seq.end(); I != E; ++I)
137 scanSchedRW(*I, RWDefs, RWSet);
138 }
139 else if (RWDef->isSubClassOf("SchedVariant")) {
140 // Visit each variant (guarded by a different predicate).
141 RecVec Vars = RWDef->getValueAsListOfDefs("Variants");
142 for (RecIter VI = Vars.begin(), VE = Vars.end(); VI != VE; ++VI) {
143 // Visit each RW in the sequence selected by the current variant.
144 RecVec Selected = (*VI)->getValueAsListOfDefs("Selected");
145 for (RecIter I = Selected.begin(), E = Selected.end(); I != E; ++I)
146 scanSchedRW(*I, RWDefs, RWSet);
147 }
148 }
149}
150
151// Collect and sort all SchedReadWrites reachable via tablegen records.
152// More may be inferred later when inferring new SchedClasses from variants.
153void CodeGenSchedModels::collectSchedRW() {
154 // Reserve idx=0 for invalid writes/reads.
155 SchedWrites.resize(1);
156 SchedReads.resize(1);
157
158 SmallPtrSet<Record*, 16> RWSet;
159
160 // Find all SchedReadWrites referenced by instruction defs.
161 RecVec SWDefs, SRDefs;
162 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
163 E = Target.inst_end(); I != E; ++I) {
164 Record *SchedDef = (*I)->TheDef;
165 if (!SchedDef->isSubClassOf("Sched"))
166 continue;
167 RecVec RWs = SchedDef->getValueAsListOfDefs("SchedRW");
168 for (RecIter RWI = RWs.begin(), RWE = RWs.end(); RWI != RWE; ++RWI) {
169 if ((*RWI)->isSubClassOf("SchedWrite"))
170 scanSchedRW(*RWI, SWDefs, RWSet);
171 else {
172 assert((*RWI)->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
173 scanSchedRW(*RWI, SRDefs, RWSet);
174 }
175 }
176 }
177 // Find all ReadWrites referenced by InstRW.
178 RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
179 for (RecIter OI = InstRWDefs.begin(), OE = InstRWDefs.end(); OI != OE; ++OI) {
180 // For all OperandReadWrites.
181 RecVec RWDefs = (*OI)->getValueAsListOfDefs("OperandReadWrites");
182 for (RecIter RWI = RWDefs.begin(), RWE = RWDefs.end();
183 RWI != RWE; ++RWI) {
184 if ((*RWI)->isSubClassOf("SchedWrite"))
185 scanSchedRW(*RWI, SWDefs, RWSet);
186 else {
187 assert((*RWI)->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
188 scanSchedRW(*RWI, SRDefs, RWSet);
189 }
190 }
191 }
192 // Find all ReadWrites referenced by ItinRW.
193 RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
194 for (RecIter II = ItinRWDefs.begin(), IE = ItinRWDefs.end(); II != IE; ++II) {
195 // For all OperandReadWrites.
196 RecVec RWDefs = (*II)->getValueAsListOfDefs("OperandReadWrites");
197 for (RecIter RWI = RWDefs.begin(), RWE = RWDefs.end();
198 RWI != RWE; ++RWI) {
199 if ((*RWI)->isSubClassOf("SchedWrite"))
200 scanSchedRW(*RWI, SWDefs, RWSet);
201 else {
202 assert((*RWI)->isSubClassOf("SchedRead") && "Unknown SchedReadWrite");
203 scanSchedRW(*RWI, SRDefs, RWSet);
204 }
205 }
206 }
207 // Sort and add the SchedReadWrites directly referenced by instructions or
208 // itinerary resources. Index reads and writes in separate domains.
209 std::sort(SWDefs.begin(), SWDefs.end(), LessRecord());
210 for (RecIter SWI = SWDefs.begin(), SWE = SWDefs.end(); SWI != SWE; ++SWI) {
211 assert(!getSchedRWIdx(*SWI, /*IsRead=*/false) && "duplicate SchedWrite");
212 SchedWrites.push_back(CodeGenSchedRW(*SWI));
213 }
214 std::sort(SRDefs.begin(), SRDefs.end(), LessRecord());
215 for (RecIter SRI = SRDefs.begin(), SRE = SRDefs.end(); SRI != SRE; ++SRI) {
216 assert(!getSchedRWIdx(*SRI, /*IsRead-*/true) && "duplicate SchedWrite");
217 SchedReads.push_back(CodeGenSchedRW(*SRI));
218 }
219 // Initialize WriteSequence vectors.
220 for (std::vector<CodeGenSchedRW>::iterator WI = SchedWrites.begin(),
221 WE = SchedWrites.end(); WI != WE; ++WI) {
222 if (!WI->IsSequence)
223 continue;
224 findRWs(WI->TheDef->getValueAsListOfDefs("Writes"), WI->Sequence,
225 /*IsRead=*/false);
226 }
227 DEBUG(
228 for (unsigned WIdx = 0, WEnd = SchedWrites.size(); WIdx != WEnd; ++WIdx) {
229 dbgs() << WIdx << ": ";
230 SchedWrites[WIdx].dump();
231 dbgs() << '\n';
232 }
233 for (unsigned RIdx = 0, REnd = SchedReads.size(); RIdx != REnd; ++RIdx) {
234 dbgs() << RIdx << ": ";
235 SchedReads[RIdx].dump();
236 dbgs() << '\n';
237 }
238 RecVec RWDefs = Records.getAllDerivedDefinitions("SchedReadWrite");
239 for (RecIter RI = RWDefs.begin(), RE = RWDefs.end();
240 RI != RE; ++RI) {
241 if (!getSchedRWIdx(*RI, (*RI)->isSubClassOf("SchedRead"))) {
242 const std::string &Name = (*RI)->getName();
243 if (Name != "NoWrite" && Name != "ReadDefault")
244 dbgs() << "Unused SchedReadWrite " << (*RI)->getName() << '\n';
245 }
246 });
247}
248
249/// Compute a SchedWrite name from a sequence of writes.
250std::string CodeGenSchedModels::genRWName(const IdxVec& Seq, bool IsRead) {
251 std::string Name("(");
252 for (IdxIter I = Seq.begin(), E = Seq.end(); I != E; ++I) {
253 if (I != Seq.begin())
254 Name += '_';
255 Name += getSchedRW(*I, IsRead).Name;
256 }
257 Name += ')';
258 return Name;
259}
260
261unsigned CodeGenSchedModels::getSchedRWIdx(Record *Def, bool IsRead,
262 unsigned After) const {
263 const std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
264 assert(After < RWVec.size() && "start position out of bounds");
265 for (std::vector<CodeGenSchedRW>::const_iterator I = RWVec.begin() + After,
266 E = RWVec.end(); I != E; ++I) {
267 if (I->TheDef == Def)
268 return I - RWVec.begin();
269 }
270 return 0;
271}
272
273namespace llvm {
274void splitSchedReadWrites(const RecVec &RWDefs,
275 RecVec &WriteDefs, RecVec &ReadDefs) {
276 for (RecIter RWI = RWDefs.begin(), RWE = RWDefs.end(); RWI != RWE; ++RWI) {
277 if ((*RWI)->isSubClassOf("SchedWrite"))
278 WriteDefs.push_back(*RWI);
279 else {
280 assert((*RWI)->isSubClassOf("SchedRead") && "unknown SchedReadWrite");
281 ReadDefs.push_back(*RWI);
282 }
283 }
284}
285} // namespace llvm
286
287// Split the SchedReadWrites defs and call findRWs for each list.
288void CodeGenSchedModels::findRWs(const RecVec &RWDefs,
289 IdxVec &Writes, IdxVec &Reads) const {
290 RecVec WriteDefs;
291 RecVec ReadDefs;
292 splitSchedReadWrites(RWDefs, WriteDefs, ReadDefs);
293 findRWs(WriteDefs, Writes, false);
294 findRWs(ReadDefs, Reads, true);
295}
296
297// Call getSchedRWIdx for all elements in a sequence of SchedRW defs.
298void CodeGenSchedModels::findRWs(const RecVec &RWDefs, IdxVec &RWs,
299 bool IsRead) const {
300 for (RecIter RI = RWDefs.begin(), RE = RWDefs.end(); RI != RE; ++RI) {
301 unsigned Idx = getSchedRWIdx(*RI, IsRead);
302 assert(Idx && "failed to collect SchedReadWrite");
303 RWs.push_back(Idx);
304 }
305}
306
Andrew Trick5e613c22012-09-15 00:19:59 +0000307void CodeGenSchedModels::expandRWSequence(unsigned RWIdx, IdxVec &RWSeq,
308 bool IsRead) const {
309 const CodeGenSchedRW &SchedRW = getSchedRW(RWIdx, IsRead);
310 if (!SchedRW.IsSequence) {
311 RWSeq.push_back(RWIdx);
312 return;
313 }
314 int Repeat =
315 SchedRW.TheDef ? SchedRW.TheDef->getValueAsInt("Repeat") : 1;
316 for (int i = 0; i < Repeat; ++i) {
317 for (IdxIter I = SchedRW.Sequence.begin(), E = SchedRW.Sequence.end();
318 I != E; ++I) {
319 expandRWSequence(*I, RWSeq, IsRead);
320 }
321 }
322}
323
324// Find the existing SchedWrite that models this sequence of writes.
325unsigned CodeGenSchedModels::findRWForSequence(const IdxVec &Seq,
326 bool IsRead) {
327 std::vector<CodeGenSchedRW> &RWVec = IsRead ? SchedReads : SchedWrites;
328
329 for (std::vector<CodeGenSchedRW>::iterator I = RWVec.begin(), E = RWVec.end();
330 I != E; ++I) {
331 if (I->Sequence == Seq)
332 return I - RWVec.begin();
333 }
334 // Index zero reserved for invalid RW.
335 return 0;
336}
337
338/// Add this ReadWrite if it doesn't already exist.
339unsigned CodeGenSchedModels::findOrInsertRW(ArrayRef<unsigned> Seq,
340 bool IsRead) {
341 assert(!Seq.empty() && "cannot insert empty sequence");
342 if (Seq.size() == 1)
343 return Seq.back();
344
345 unsigned Idx = findRWForSequence(Seq, IsRead);
346 if (Idx)
347 return Idx;
348
349 CodeGenSchedRW SchedRW(Seq, genRWName(Seq, IsRead));
350 if (IsRead) {
351 SchedReads.push_back(SchedRW);
352 return SchedReads.size() - 1;
353 }
354 SchedWrites.push_back(SchedRW);
355 return SchedWrites.size() - 1;
356}
357
Andrew Trick48605c32012-09-15 00:19:57 +0000358/// Visit all the instruction definitions for this target to gather and
359/// enumerate the itinerary classes. These are the explicitly specified
360/// SchedClasses. More SchedClasses may be inferred.
361void CodeGenSchedModels::collectSchedClasses() {
362
363 // NoItinerary is always the first class at Idx=0
Andrew Trick2661b412012-07-07 04:00:00 +0000364 SchedClasses.resize(1);
365 SchedClasses.back().Name = "NoItinerary";
Andrew Trick48605c32012-09-15 00:19:57 +0000366 SchedClasses.back().ProcIndices.push_back(0);
Andrew Trick2661b412012-07-07 04:00:00 +0000367 SchedClassIdxMap[SchedClasses.back().Name] = 0;
368
369 // Gather and sort all itinerary classes used by instruction descriptions.
Andrew Trick48605c32012-09-15 00:19:57 +0000370 RecVec ItinClassList;
Andrew Trick2661b412012-07-07 04:00:00 +0000371 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
372 E = Target.inst_end(); I != E; ++I) {
Andrew Trick48605c32012-09-15 00:19:57 +0000373 Record *ItinDef = (*I)->TheDef->getValueAsDef("Itinerary");
Andrew Trick2661b412012-07-07 04:00:00 +0000374 // Map a new SchedClass with no index.
Andrew Trick48605c32012-09-15 00:19:57 +0000375 if (!SchedClassIdxMap.count(ItinDef->getName())) {
376 SchedClassIdxMap[ItinDef->getName()] = 0;
377 ItinClassList.push_back(ItinDef);
Andrew Trick2661b412012-07-07 04:00:00 +0000378 }
379 }
380 // Assign each itinerary class unique number, skipping NoItinerary==0
381 NumItineraryClasses = ItinClassList.size();
382 std::sort(ItinClassList.begin(), ItinClassList.end(), LessRecord());
383 for (unsigned i = 0, N = NumItineraryClasses; i < N; i++) {
384 Record *ItinDef = ItinClassList[i];
385 SchedClassIdxMap[ItinDef->getName()] = SchedClasses.size();
386 SchedClasses.push_back(CodeGenSchedClass(ItinDef));
387 }
Andrew Trick48605c32012-09-15 00:19:57 +0000388 // Infer classes from SchedReadWrite resources listed for each
389 // instruction definition that inherits from class Sched.
390 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
391 E = Target.inst_end(); I != E; ++I) {
392 if (!(*I)->TheDef->isSubClassOf("Sched"))
393 continue;
394 IdxVec Writes, Reads;
395 findRWs((*I)->TheDef->getValueAsListOfDefs("SchedRW"), Writes, Reads);
396 // ProcIdx == 0 indicates the class applies to all processors.
397 IdxVec ProcIndices(1, 0);
398 addSchedClass(Writes, Reads, ProcIndices);
399 }
400 // Create classes for InstReadWrite defs.
401 RecVec InstRWDefs = Records.getAllDerivedDefinitions("InstRW");
402 std::sort(InstRWDefs.begin(), InstRWDefs.end(), LessRecord());
403 for (RecIter OI = InstRWDefs.begin(), OE = InstRWDefs.end(); OI != OE; ++OI)
404 createInstRWClass(*OI);
Andrew Trick2661b412012-07-07 04:00:00 +0000405
Andrew Trick48605c32012-09-15 00:19:57 +0000406 NumInstrSchedClasses = SchedClasses.size();
Andrew Trick2661b412012-07-07 04:00:00 +0000407
Andrew Trick48605c32012-09-15 00:19:57 +0000408 bool EnableDump = false;
409 DEBUG(EnableDump = true);
410 if (!EnableDump)
Andrew Trick2661b412012-07-07 04:00:00 +0000411 return;
Andrew Trick48605c32012-09-15 00:19:57 +0000412 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
413 E = Target.inst_end(); I != E; ++I) {
414 Record *SchedDef = (*I)->TheDef;
415 std::string InstName = (*I)->TheDef->getName();
416 if (SchedDef->isSubClassOf("Sched")) {
417 IdxVec Writes;
418 IdxVec Reads;
419 findRWs((*I)->TheDef->getValueAsListOfDefs("SchedRW"), Writes, Reads);
420 dbgs() << "SchedRW machine model for " << InstName;
421 for (IdxIter WI = Writes.begin(), WE = Writes.end(); WI != WE; ++WI)
422 dbgs() << " " << SchedWrites[*WI].Name;
423 for (IdxIter RI = Reads.begin(), RE = Reads.end(); RI != RE; ++RI)
424 dbgs() << " " << SchedReads[*RI].Name;
425 dbgs() << '\n';
426 }
427 unsigned SCIdx = InstrClassMap.lookup((*I)->TheDef);
428 if (SCIdx) {
429 const RecVec &RWDefs = SchedClasses[SCIdx].InstRWs;
430 for (RecIter RWI = RWDefs.begin(), RWE = RWDefs.end();
431 RWI != RWE; ++RWI) {
432 const CodeGenProcModel &ProcModel =
433 getProcModel((*RWI)->getValueAsDef("SchedModel"));
434 dbgs() << "InstrRW on " << ProcModel.ModelName << " for " << InstName;
435 IdxVec Writes;
436 IdxVec Reads;
437 findRWs((*RWI)->getValueAsListOfDefs("OperandReadWrites"),
438 Writes, Reads);
439 for (IdxIter WI = Writes.begin(), WE = Writes.end(); WI != WE; ++WI)
440 dbgs() << " " << SchedWrites[*WI].Name;
441 for (IdxIter RI = Reads.begin(), RE = Reads.end(); RI != RE; ++RI)
442 dbgs() << " " << SchedReads[*RI].Name;
443 dbgs() << '\n';
444 }
445 continue;
446 }
447 if (!SchedDef->isSubClassOf("Sched")
448 && (SchedDef->getValueAsDef("Itinerary")->getName() == "NoItinerary")) {
449 dbgs() << "No machine model for " << (*I)->TheDef->getName() << '\n';
Andrew Trick2661b412012-07-07 04:00:00 +0000450 }
451 }
Andrew Trick48605c32012-09-15 00:19:57 +0000452}
453
454unsigned CodeGenSchedModels::getSchedClassIdx(
455 const RecVec &RWDefs) const {
456
457 IdxVec Writes, Reads;
458 findRWs(RWDefs, Writes, Reads);
459 return findSchedClassIdx(Writes, Reads);
460}
461
462/// Find an SchedClass that has been inferred from a per-operand list of
463/// SchedWrites and SchedReads.
464unsigned CodeGenSchedModels::findSchedClassIdx(const IdxVec &Writes,
465 const IdxVec &Reads) const {
466 for (SchedClassIter I = schedClassBegin(), E = schedClassEnd(); I != E; ++I) {
467 // Classes with InstRWs may have the same Writes/Reads as a class originally
468 // produced by a SchedRW definition. We need to be able to recover the
469 // original class index for processors that don't match any InstRWs.
470 if (I->ItinClassDef || !I->InstRWs.empty())
471 continue;
472
473 if (I->Writes == Writes && I->Reads == Reads) {
474 return I - schedClassBegin();
475 }
Andrew Trick2661b412012-07-07 04:00:00 +0000476 }
Andrew Trick48605c32012-09-15 00:19:57 +0000477 return 0;
478}
Andrew Trick2661b412012-07-07 04:00:00 +0000479
Andrew Trick48605c32012-09-15 00:19:57 +0000480// Get the SchedClass index for an instruction.
481unsigned CodeGenSchedModels::getSchedClassIdx(
482 const CodeGenInstruction &Inst) const {
Andrew Trick2661b412012-07-07 04:00:00 +0000483
Andrew Trick48605c32012-09-15 00:19:57 +0000484 unsigned SCIdx = InstrClassMap.lookup(Inst.TheDef);
485 if (SCIdx)
486 return SCIdx;
Andrew Trick2661b412012-07-07 04:00:00 +0000487
Andrew Trick48605c32012-09-15 00:19:57 +0000488 // If this opcode isn't mapped by the subtarget fallback to the instruction
489 // definition's SchedRW or ItinDef values.
490 if (Inst.TheDef->isSubClassOf("Sched")) {
491 RecVec RWs = Inst.TheDef->getValueAsListOfDefs("SchedRW");
492 return getSchedClassIdx(RWs);
493 }
494 Record *ItinDef = Inst.TheDef->getValueAsDef("Itinerary");
495 assert(SchedClassIdxMap.count(ItinDef->getName()) && "missing ItinClass");
496 unsigned Idx = SchedClassIdxMap.lookup(ItinDef->getName());
497 assert(Idx <= NumItineraryClasses && "bad ItinClass index");
498 return Idx;
499}
500
501std::string CodeGenSchedModels::createSchedClassName(
502 const IdxVec &OperWrites, const IdxVec &OperReads) {
503
504 std::string Name;
505 for (IdxIter WI = OperWrites.begin(), WE = OperWrites.end(); WI != WE; ++WI) {
506 if (WI != OperWrites.begin())
507 Name += '_';
508 Name += SchedWrites[*WI].Name;
509 }
510 for (IdxIter RI = OperReads.begin(), RE = OperReads.end(); RI != RE; ++RI) {
511 Name += '_';
512 Name += SchedReads[*RI].Name;
513 }
514 return Name;
515}
516
517std::string CodeGenSchedModels::createSchedClassName(const RecVec &InstDefs) {
518
519 std::string Name;
520 for (RecIter I = InstDefs.begin(), E = InstDefs.end(); I != E; ++I) {
521 if (I != InstDefs.begin())
522 Name += '_';
523 Name += (*I)->getName();
524 }
525 return Name;
526}
527
528/// Add an inferred sched class from a per-operand list of SchedWrites and
529/// SchedReads. ProcIndices contains the set of IDs of processors that may
530/// utilize this class.
531unsigned CodeGenSchedModels::addSchedClass(const IdxVec &OperWrites,
532 const IdxVec &OperReads,
533 const IdxVec &ProcIndices)
534{
535 assert(!ProcIndices.empty() && "expect at least one ProcIdx");
536
537 unsigned Idx = findSchedClassIdx(OperWrites, OperReads);
538 if (Idx) {
539 IdxVec PI;
540 std::set_union(SchedClasses[Idx].ProcIndices.begin(),
541 SchedClasses[Idx].ProcIndices.end(),
542 ProcIndices.begin(), ProcIndices.end(),
543 std::back_inserter(PI));
544 SchedClasses[Idx].ProcIndices.swap(PI);
545 return Idx;
546 }
547 Idx = SchedClasses.size();
548 SchedClasses.resize(Idx+1);
549 CodeGenSchedClass &SC = SchedClasses.back();
550 SC.Name = createSchedClassName(OperWrites, OperReads);
551 SC.Writes = OperWrites;
552 SC.Reads = OperReads;
553 SC.ProcIndices = ProcIndices;
554
555 return Idx;
556}
557
558// Create classes for each set of opcodes that are in the same InstReadWrite
559// definition across all processors.
560void CodeGenSchedModels::createInstRWClass(Record *InstRWDef) {
561 // ClassInstrs will hold an entry for each subset of Instrs in InstRWDef that
562 // intersects with an existing class via a previous InstRWDef. Instrs that do
563 // not intersect with an existing class refer back to their former class as
564 // determined from ItinDef or SchedRW.
565 SmallVector<std::pair<unsigned, SmallVector<Record *, 8> >, 4> ClassInstrs;
566 // Sort Instrs into sets.
567 RecVec InstDefs = InstRWDef->getValueAsListOfDefs("Instrs");
568 std::sort(InstDefs.begin(), InstDefs.end(), LessRecord());
569 for (RecIter I = InstDefs.begin(), E = InstDefs.end(); I != E; ++I) {
570 unsigned SCIdx = 0;
571 InstClassMapTy::const_iterator Pos = InstrClassMap.find(*I);
572 if (Pos != InstrClassMap.end())
573 SCIdx = Pos->second;
574 else {
575 // This instruction has not been mapped yet. Get the original class. All
576 // instructions in the same InstrRW class must be from the same original
577 // class because that is the fall-back class for other processors.
578 Record *ItinDef = (*I)->getValueAsDef("Itinerary");
579 SCIdx = SchedClassIdxMap.lookup(ItinDef->getName());
580 if (!SCIdx && (*I)->isSubClassOf("Sched"))
581 SCIdx = getSchedClassIdx((*I)->getValueAsListOfDefs("SchedRW"));
582 }
583 unsigned CIdx = 0, CEnd = ClassInstrs.size();
584 for (; CIdx != CEnd; ++CIdx) {
585 if (ClassInstrs[CIdx].first == SCIdx)
586 break;
587 }
588 if (CIdx == CEnd) {
589 ClassInstrs.resize(CEnd + 1);
590 ClassInstrs[CIdx].first = SCIdx;
591 }
592 ClassInstrs[CIdx].second.push_back(*I);
593 }
594 // For each set of Instrs, create a new class if necessary, and map or remap
595 // the Instrs to it.
596 unsigned CIdx = 0, CEnd = ClassInstrs.size();
597 for (; CIdx != CEnd; ++CIdx) {
598 unsigned OldSCIdx = ClassInstrs[CIdx].first;
599 ArrayRef<Record*> InstDefs = ClassInstrs[CIdx].second;
600 // If the all instrs in the current class are accounted for, then leave
601 // them mapped to their old class.
602 if (SchedClasses[OldSCIdx].InstRWs.size() == InstDefs.size()) {
603 assert(SchedClasses[OldSCIdx].ProcIndices[0] == 0 &&
604 "expected a generic SchedClass");
605 continue;
606 }
607 unsigned SCIdx = SchedClasses.size();
608 SchedClasses.resize(SCIdx+1);
609 CodeGenSchedClass &SC = SchedClasses.back();
610 SC.Name = createSchedClassName(InstDefs);
611 // Preserve ItinDef and Writes/Reads for processors without an InstRW entry.
612 SC.ItinClassDef = SchedClasses[OldSCIdx].ItinClassDef;
613 SC.Writes = SchedClasses[OldSCIdx].Writes;
614 SC.Reads = SchedClasses[OldSCIdx].Reads;
615 SC.ProcIndices.push_back(0);
616 // Map each Instr to this new class.
617 // Note that InstDefs may be a smaller list than InstRWDef's "Instrs".
618 for (ArrayRef<Record*>::const_iterator
619 II = InstDefs.begin(), IE = InstDefs.end(); II != IE; ++II) {
620 unsigned OldSCIdx = InstrClassMap[*II];
621 if (OldSCIdx) {
622 SC.InstRWs.insert(SC.InstRWs.end(),
623 SchedClasses[OldSCIdx].InstRWs.begin(),
624 SchedClasses[OldSCIdx].InstRWs.end());
625 }
626 InstrClassMap[*II] = SCIdx;
627 }
628 SC.InstRWs.push_back(InstRWDef);
629 }
Andrew Trick2661b412012-07-07 04:00:00 +0000630}
631
632// Gather the processor itineraries.
Andrew Trick48605c32012-09-15 00:19:57 +0000633void CodeGenSchedModels::collectProcItins() {
634 for (std::vector<CodeGenProcModel>::iterator PI = ProcModels.begin(),
635 PE = ProcModels.end(); PI != PE; ++PI) {
636 CodeGenProcModel &ProcModel = *PI;
637 RecVec ItinRecords = ProcModel.ItinsDef->getValueAsListOfDefs("IID");
638 // Skip empty itinerary.
639 if (ItinRecords.empty())
Andrew Trick2661b412012-07-07 04:00:00 +0000640 continue;
Andrew Trick48605c32012-09-15 00:19:57 +0000641
642 ProcModel.ItinDefList.resize(NumItineraryClasses+1);
643
644 // Insert each itinerary data record in the correct position within
645 // the processor model's ItinDefList.
646 for (unsigned i = 0, N = ItinRecords.size(); i < N; i++) {
647 Record *ItinData = ItinRecords[i];
648 Record *ItinDef = ItinData->getValueAsDef("TheClass");
649 if (!SchedClassIdxMap.count(ItinDef->getName())) {
650 DEBUG(dbgs() << ProcModel.ItinsDef->getName()
651 << " has unused itinerary class " << ItinDef->getName() << '\n');
652 continue;
653 }
654 assert(SchedClassIdxMap.count(ItinDef->getName()) && "missing ItinClass");
655 unsigned Idx = SchedClassIdxMap.lookup(ItinDef->getName());
656 assert(Idx <= NumItineraryClasses && "bad ItinClass index");
657 ProcModel.ItinDefList[Idx] = ItinData;
Andrew Trick2661b412012-07-07 04:00:00 +0000658 }
Andrew Trick48605c32012-09-15 00:19:57 +0000659 // Check for missing itinerary entries.
660 assert(!ProcModel.ItinDefList[0] && "NoItinerary class can't have rec");
661 DEBUG(
662 for (unsigned i = 1, N = ProcModel.ItinDefList.size(); i < N; ++i) {
663 if (!ProcModel.ItinDefList[i])
664 dbgs() << ProcModel.ItinsDef->getName()
665 << " missing itinerary for class "
666 << SchedClasses[i].Name << '\n';
667 });
Andrew Trick2661b412012-07-07 04:00:00 +0000668 }
Andrew Trick2661b412012-07-07 04:00:00 +0000669}
Andrew Trick48605c32012-09-15 00:19:57 +0000670
671// Gather the read/write types for each itinerary class.
672void CodeGenSchedModels::collectProcItinRW() {
673 RecVec ItinRWDefs = Records.getAllDerivedDefinitions("ItinRW");
674 std::sort(ItinRWDefs.begin(), ItinRWDefs.end(), LessRecord());
675 for (RecIter II = ItinRWDefs.begin(), IE = ItinRWDefs.end(); II != IE; ++II) {
676 if (!(*II)->getValueInit("SchedModel")->isComplete())
677 throw TGError((*II)->getLoc(), "SchedModel is undefined");
678 Record *ModelDef = (*II)->getValueAsDef("SchedModel");
679 ProcModelMapTy::const_iterator I = ProcModelMap.find(ModelDef);
680 if (I == ProcModelMap.end()) {
681 throw TGError((*II)->getLoc(), "Undefined SchedMachineModel "
682 + ModelDef->getName());
683 }
684 ProcModels[I->second].ItinRWDefs.push_back(*II);
685 }
686}
687
Andrew Trick5e613c22012-09-15 00:19:59 +0000688/// Infer new classes from existing classes. In the process, this may create new
689/// SchedWrites from sequences of existing SchedWrites.
690void CodeGenSchedModels::inferSchedClasses() {
691 // Visit all existing classes and newly created classes.
692 for (unsigned Idx = 0; Idx != SchedClasses.size(); ++Idx) {
693 if (SchedClasses[Idx].ItinClassDef)
694 inferFromItinClass(SchedClasses[Idx].ItinClassDef, Idx);
695 else if (!SchedClasses[Idx].InstRWs.empty())
696 inferFromInstRWs(Idx);
697 else {
698 inferFromRW(SchedClasses[Idx].Writes, SchedClasses[Idx].Reads,
699 Idx, SchedClasses[Idx].ProcIndices);
700 }
701 assert(SchedClasses.size() < (NumInstrSchedClasses*6) &&
702 "too many SchedVariants");
703 }
704}
705
706/// Infer classes from per-processor itinerary resources.
707void CodeGenSchedModels::inferFromItinClass(Record *ItinClassDef,
708 unsigned FromClassIdx) {
709 for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
710 const CodeGenProcModel &PM = ProcModels[PIdx];
711 // For all ItinRW entries.
712 bool HasMatch = false;
713 for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
714 II != IE; ++II) {
715 RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
716 if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
717 continue;
718 if (HasMatch)
719 throw TGError((*II)->getLoc(), "Duplicate itinerary class "
720 + ItinClassDef->getName()
721 + " in ItinResources for " + PM.ModelName);
722 HasMatch = true;
723 IdxVec Writes, Reads;
724 findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
725 IdxVec ProcIndices(1, PIdx);
726 inferFromRW(Writes, Reads, FromClassIdx, ProcIndices);
727 }
728 }
729}
730
731/// Infer classes from per-processor InstReadWrite definitions.
732void CodeGenSchedModels::inferFromInstRWs(unsigned SCIdx) {
733 const RecVec &RWDefs = SchedClasses[SCIdx].InstRWs;
734 for (RecIter RWI = RWDefs.begin(), RWE = RWDefs.end(); RWI != RWE; ++RWI) {
735 RecVec Instrs = (*RWI)->getValueAsListOfDefs("Instrs");
736 RecIter II = Instrs.begin(), IE = Instrs.end();
737 for (; II != IE; ++II) {
738 if (InstrClassMap[*II] == SCIdx)
739 break;
740 }
741 // If this class no longer has any instructions mapped to it, it has become
742 // irrelevant.
743 if (II == IE)
744 continue;
745 IdxVec Writes, Reads;
746 findRWs((*RWI)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
747 unsigned PIdx = getProcModel((*RWI)->getValueAsDef("SchedModel")).Index;
748 IdxVec ProcIndices(1, PIdx);
749 inferFromRW(Writes, Reads, SCIdx, ProcIndices);
750 }
751}
752
753namespace {
754// Associate a predicate with the SchedReadWrite that it guards.
755// RWIdx is the index of the read/write variant.
756struct PredCheck {
757 bool IsRead;
758 unsigned RWIdx;
759 Record *Predicate;
760
761 PredCheck(bool r, unsigned w, Record *p): IsRead(r), RWIdx(w), Predicate(p) {}
762};
763
764// A Predicate transition is a list of RW sequences guarded by a PredTerm.
765struct PredTransition {
766 // A predicate term is a conjunction of PredChecks.
767 SmallVector<PredCheck, 4> PredTerm;
768 SmallVector<SmallVector<unsigned,4>, 16> WriteSequences;
769 SmallVector<SmallVector<unsigned,4>, 16> ReadSequences;
770};
771
772// Encapsulate a set of partially constructed transitions.
773// The results are built by repeated calls to substituteVariants.
774class PredTransitions {
775 CodeGenSchedModels &SchedModels;
776
777public:
778 std::vector<PredTransition> TransVec;
779
780 PredTransitions(CodeGenSchedModels &sm): SchedModels(sm) {}
781
782 void substituteVariantOperand(const SmallVectorImpl<unsigned> &RWSeq,
783 bool IsRead, unsigned StartIdx);
784
785 void substituteVariants(const PredTransition &Trans);
786
787#ifndef NDEBUG
788 void dump() const;
789#endif
790
791private:
792 bool mutuallyExclusive(Record *PredDef, ArrayRef<PredCheck> Term);
793 void pushVariant(unsigned SchedRW, Record *Variant, PredTransition &Trans,
794 bool IsRead);
795};
796} // anonymous
797
798// Return true if this predicate is mutually exclusive with a PredTerm. This
799// degenerates into checking if the predicate is mutually exclusive with any
800// predicate in the Term's conjunction.
801//
802// All predicates associated with a given SchedRW are considered mutually
803// exclusive. This should work even if the conditions expressed by the
804// predicates are not exclusive because the predicates for a given SchedWrite
805// are always checked in the order they are defined in the .td file. Later
806// conditions implicitly negate any prior condition.
807bool PredTransitions::mutuallyExclusive(Record *PredDef,
808 ArrayRef<PredCheck> Term) {
809
810 for (ArrayRef<PredCheck>::iterator I = Term.begin(), E = Term.end();
811 I != E; ++I) {
812 if (I->Predicate == PredDef)
813 return false;
814
815 const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(I->RWIdx, I->IsRead);
816 assert(SchedRW.HasVariants && "PredCheck must refer to a SchedVariant");
817 RecVec Variants = SchedRW.TheDef->getValueAsListOfDefs("Variants");
818 for (RecIter VI = Variants.begin(), VE = Variants.end(); VI != VE; ++VI) {
819 if ((*VI)->getValueAsDef("Predicate") == PredDef)
820 return true;
821 }
822 }
823 return false;
824}
825
826// Push the Reads/Writes selected by this variant onto the given PredTransition.
827void PredTransitions::pushVariant(unsigned RWIdx, Record *Variant,
828 PredTransition &Trans, bool IsRead) {
829 Trans.PredTerm.push_back(
830 PredCheck(IsRead, RWIdx, Variant->getValueAsDef("Predicate")));
831 RecVec SelectedDefs = Variant->getValueAsListOfDefs("Selected");
832 IdxVec SelectedRWs;
833 SchedModels.findRWs(SelectedDefs, SelectedRWs, IsRead);
834
835 const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(RWIdx, IsRead);
836
837 SmallVectorImpl<SmallVector<unsigned,4> > &RWSequences = IsRead
838 ? Trans.ReadSequences : Trans.WriteSequences;
839 if (SchedRW.IsVariadic) {
840 unsigned OperIdx = RWSequences.size()-1;
841 // Make N-1 copies of this transition's last sequence.
842 for (unsigned i = 1, e = SelectedRWs.size(); i != e; ++i) {
843 RWSequences.push_back(RWSequences[OperIdx]);
844 }
845 // Push each of the N elements of the SelectedRWs onto a copy of the last
846 // sequence (split the current operand into N operands).
847 // Note that write sequences should be expanded within this loop--the entire
848 // sequence belongs to a single operand.
849 for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
850 RWI != RWE; ++RWI, ++OperIdx) {
851 IdxVec ExpandedRWs;
852 if (IsRead)
853 ExpandedRWs.push_back(*RWI);
854 else
855 SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
856 RWSequences[OperIdx].insert(RWSequences[OperIdx].end(),
857 ExpandedRWs.begin(), ExpandedRWs.end());
858 }
859 assert(OperIdx == RWSequences.size() && "missed a sequence");
860 }
861 else {
862 // Push this transition's expanded sequence onto this transition's last
863 // sequence (add to the current operand's sequence).
864 SmallVectorImpl<unsigned> &Seq = RWSequences.back();
865 IdxVec ExpandedRWs;
866 for (IdxIter RWI = SelectedRWs.begin(), RWE = SelectedRWs.end();
867 RWI != RWE; ++RWI) {
868 if (IsRead)
869 ExpandedRWs.push_back(*RWI);
870 else
871 SchedModels.expandRWSequence(*RWI, ExpandedRWs, IsRead);
872 }
873 Seq.insert(Seq.end(), ExpandedRWs.begin(), ExpandedRWs.end());
874 }
875}
876
877// RWSeq is a sequence of all Reads or all Writes for the next read or write
878// operand. StartIdx is an index into TransVec where partial results
879// starts. RWSeq must be applied to all tranistions between StartIdx and the end
880// of TransVec.
881void PredTransitions::substituteVariantOperand(
882 const SmallVectorImpl<unsigned> &RWSeq, bool IsRead, unsigned StartIdx) {
883
884 // Visit each original RW within the current sequence.
885 for (SmallVectorImpl<unsigned>::const_iterator
886 RWI = RWSeq.begin(), RWE = RWSeq.end(); RWI != RWE; ++RWI) {
887 const CodeGenSchedRW &SchedRW = SchedModels.getSchedRW(*RWI, IsRead);
888 // Push this RW on all partial PredTransitions or distribute variants.
889 // New PredTransitions may be pushed within this loop which should not be
890 // revisited (TransEnd must be loop invariant).
891 for (unsigned TransIdx = StartIdx, TransEnd = TransVec.size();
892 TransIdx != TransEnd; ++TransIdx) {
893 // In the common case, push RW onto the current operand's sequence.
894 if (!SchedRW.HasVariants) {
895 if (IsRead)
896 TransVec[TransIdx].ReadSequences.back().push_back(*RWI);
897 else
898 TransVec[TransIdx].WriteSequences.back().push_back(*RWI);
899 continue;
900 }
901 // Distribute this partial PredTransition across intersecting variants.
902 RecVec Variants = SchedRW.TheDef->getValueAsListOfDefs("Variants");
903 std::vector<std::pair<Record*,unsigned> > IntersectingVariants;
904 for (RecIter VI = Variants.begin(), VE = Variants.end(); VI != VE; ++VI) {
905 Record *PredDef = (*VI)->getValueAsDef("Predicate");
906 if (mutuallyExclusive(PredDef, TransVec[TransIdx].PredTerm))
907 continue;
908 if (IntersectingVariants.empty())
909 // The first variant builds on the existing transition.
910 IntersectingVariants.push_back(std::make_pair(*VI, TransIdx));
911 else {
912 // Push another copy of the current transition for more variants.
913 IntersectingVariants.push_back(
914 std::make_pair(*VI, TransVec.size()));
915 TransVec.push_back(TransVec[TransIdx]);
916 }
917 }
918 // Now expand each variant on top of its copy of the transition.
919 for (std::vector<std::pair<Record*, unsigned> >::const_iterator
920 IVI = IntersectingVariants.begin(),
921 IVE = IntersectingVariants.end();
922 IVI != IVE; ++IVI)
923 pushVariant(*RWI, IVI->first, TransVec[IVI->second], IsRead);
924 }
925 }
926}
927
928// For each variant of a Read/Write in Trans, substitute the sequence of
929// Read/Writes guarded by the variant. This is exponential in the number of
930// variant Read/Writes, but in practice detection of mutually exclusive
931// predicates should result in linear growth in the total number variants.
932//
933// This is one step in a breadth-first search of nested variants.
934void PredTransitions::substituteVariants(const PredTransition &Trans) {
935 // Build up a set of partial results starting at the back of
936 // PredTransitions. Remember the first new transition.
937 unsigned StartIdx = TransVec.size();
938 TransVec.resize(TransVec.size() + 1);
939 TransVec.back().PredTerm = Trans.PredTerm;
940
941 // Visit each original write sequence.
942 for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
943 WSI = Trans.WriteSequences.begin(), WSE = Trans.WriteSequences.end();
944 WSI != WSE; ++WSI) {
945 // Push a new (empty) write sequence onto all partial Transitions.
946 for (std::vector<PredTransition>::iterator I =
947 TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
948 I->WriteSequences.resize(I->WriteSequences.size() + 1);
949 }
950 substituteVariantOperand(*WSI, /*IsRead=*/false, StartIdx);
951 }
952 // Visit each original read sequence.
953 for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
954 RSI = Trans.ReadSequences.begin(), RSE = Trans.ReadSequences.end();
955 RSI != RSE; ++RSI) {
956 // Push a new (empty) read sequence onto all partial Transitions.
957 for (std::vector<PredTransition>::iterator I =
958 TransVec.begin() + StartIdx, E = TransVec.end(); I != E; ++I) {
959 I->ReadSequences.resize(I->ReadSequences.size() + 1);
960 }
961 substituteVariantOperand(*RSI, /*IsRead=*/true, StartIdx);
962 }
963}
964
965static bool hasVariant(ArrayRef<PredTransition> Transitions,
966 CodeGenSchedModels &SchedModels) {
967 for (ArrayRef<PredTransition>::iterator
968 PTI = Transitions.begin(), PTE = Transitions.end();
969 PTI != PTE; ++PTI) {
970 for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
971 WSI = PTI->WriteSequences.begin(), WSE = PTI->WriteSequences.end();
972 WSI != WSE; ++WSI) {
973 for (SmallVectorImpl<unsigned>::const_iterator
974 WI = WSI->begin(), WE = WSI->end(); WI != WE; ++WI) {
975 if (SchedModels.getSchedWrite(*WI).HasVariants)
976 return true;
977 }
978 }
979 for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
980 RSI = PTI->ReadSequences.begin(), RSE = PTI->ReadSequences.end();
981 RSI != RSE; ++RSI) {
982 for (SmallVectorImpl<unsigned>::const_iterator
983 RI = RSI->begin(), RE = RSI->end(); RI != RE; ++RI) {
984 if (SchedModels.getSchedRead(*RI).HasVariants)
985 return true;
986 }
987 }
988 }
989 return false;
990}
991
992// Create a new SchedClass for each variant found by inferFromRW. Pass
993// ProcIndices by copy to avoid referencing anything from SchedClasses.
994static void inferFromTransitions(ArrayRef<PredTransition> LastTransitions,
995 unsigned FromClassIdx, IdxVec ProcIndices,
996 CodeGenSchedModels &SchedModels) {
997 // For each PredTransition, create a new CodeGenSchedTransition, which usually
998 // requires creating a new SchedClass.
999 for (ArrayRef<PredTransition>::iterator
1000 I = LastTransitions.begin(), E = LastTransitions.end(); I != E; ++I) {
1001 IdxVec OperWritesVariant;
1002 for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
1003 WSI = I->WriteSequences.begin(), WSE = I->WriteSequences.end();
1004 WSI != WSE; ++WSI) {
1005 // Create a new write representing the expanded sequence.
1006 OperWritesVariant.push_back(
1007 SchedModels.findOrInsertRW(*WSI, /*IsRead=*/false));
1008 }
1009 IdxVec OperReadsVariant;
1010 for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
1011 RSI = I->ReadSequences.begin(), RSE = I->ReadSequences.end();
1012 RSI != RSE; ++RSI) {
1013 // Create a new write representing the expanded sequence.
1014 OperReadsVariant.push_back(
1015 SchedModels.findOrInsertRW(*RSI, /*IsRead=*/true));
1016 }
1017 CodeGenSchedTransition SCTrans;
1018 SCTrans.ToClassIdx =
1019 SchedModels.addSchedClass(OperWritesVariant, OperReadsVariant,
1020 ProcIndices);
1021 SCTrans.ProcIndices = ProcIndices;
1022 // The final PredTerm is unique set of predicates guarding the transition.
1023 RecVec Preds;
1024 for (SmallVectorImpl<PredCheck>::const_iterator
1025 PI = I->PredTerm.begin(), PE = I->PredTerm.end(); PI != PE; ++PI) {
1026 Preds.push_back(PI->Predicate);
1027 }
1028 RecIter PredsEnd = std::unique(Preds.begin(), Preds.end());
1029 Preds.resize(PredsEnd - Preds.begin());
1030 SCTrans.PredTerm = Preds;
1031 SchedModels.getSchedClass(FromClassIdx).Transitions.push_back(SCTrans);
1032 }
1033}
1034
1035/// Find each variant write that OperWrites or OperaReads refers to and create a
1036/// new SchedClass for each variant.
1037void CodeGenSchedModels::inferFromRW(const IdxVec &OperWrites,
1038 const IdxVec &OperReads,
1039 unsigned FromClassIdx,
1040 const IdxVec &ProcIndices) {
1041 DEBUG(dbgs() << "INFERRW Writes: ");
1042
1043 // Create a seed transition with an empty PredTerm and the expanded sequences
1044 // of SchedWrites for the current SchedClass.
1045 std::vector<PredTransition> LastTransitions;
1046 LastTransitions.resize(1);
1047 for (IdxIter I = OperWrites.begin(), E = OperWrites.end(); I != E; ++I) {
1048 IdxVec WriteSeq;
1049 expandRWSequence(*I, WriteSeq, /*IsRead=*/false);
1050 unsigned Idx = LastTransitions[0].WriteSequences.size();
1051 LastTransitions[0].WriteSequences.resize(Idx + 1);
1052 SmallVectorImpl<unsigned> &Seq = LastTransitions[0].WriteSequences[Idx];
1053 for (IdxIter WI = WriteSeq.begin(), WE = WriteSeq.end(); WI != WE; ++WI)
1054 Seq.push_back(*WI);
1055 DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
1056 }
1057 DEBUG(dbgs() << " Reads: ");
1058 for (IdxIter I = OperReads.begin(), E = OperReads.end(); I != E; ++I) {
1059 IdxVec ReadSeq;
1060 expandRWSequence(*I, ReadSeq, /*IsRead=*/true);
1061 unsigned Idx = LastTransitions[0].ReadSequences.size();
1062 LastTransitions[0].ReadSequences.resize(Idx + 1);
1063 SmallVectorImpl<unsigned> &Seq = LastTransitions[0].ReadSequences[Idx];
1064 for (IdxIter RI = ReadSeq.begin(), RE = ReadSeq.end(); RI != RE; ++RI)
1065 Seq.push_back(*RI);
1066 DEBUG(dbgs() << "("; dumpIdxVec(Seq); dbgs() << ") ");
1067 }
1068 DEBUG(dbgs() << '\n');
1069
1070 // Collect all PredTransitions for individual operands.
1071 // Iterate until no variant writes remain.
1072 while (hasVariant(LastTransitions, *this)) {
1073 PredTransitions Transitions(*this);
1074 for (std::vector<PredTransition>::const_iterator
1075 I = LastTransitions.begin(), E = LastTransitions.end();
1076 I != E; ++I) {
1077 Transitions.substituteVariants(*I);
1078 }
1079 DEBUG(Transitions.dump());
1080 LastTransitions.swap(Transitions.TransVec);
1081 }
1082 // If the first transition has no variants, nothing to do.
1083 if (LastTransitions[0].PredTerm.empty())
1084 return;
1085
1086 // WARNING: We are about to mutate the SchedClasses vector. Do not refer to
1087 // OperWrites, OperReads, or ProcIndices after calling inferFromTransitions.
1088 inferFromTransitions(LastTransitions, FromClassIdx, ProcIndices, *this);
1089}
1090
Andrew Trick3cbd1782012-09-15 00:20:02 +00001091// Collect and sort WriteRes, ReadAdvance, and ProcResources.
1092void CodeGenSchedModels::collectProcResources() {
1093 // Add any subtarget-specific SchedReadWrites that are directly associated
1094 // with processor resources. Refer to the parent SchedClass's ProcIndices to
1095 // determine which processors they apply to.
1096 for (SchedClassIter SCI = schedClassBegin(), SCE = schedClassEnd();
1097 SCI != SCE; ++SCI) {
1098 if (SCI->ItinClassDef)
1099 collectItinProcResources(SCI->ItinClassDef);
1100 else
1101 collectRWResources(SCI->Writes, SCI->Reads, SCI->ProcIndices);
1102 }
1103 // Add resources separately defined by each subtarget.
1104 RecVec WRDefs = Records.getAllDerivedDefinitions("WriteRes");
1105 for (RecIter WRI = WRDefs.begin(), WRE = WRDefs.end(); WRI != WRE; ++WRI) {
1106 Record *ModelDef = (*WRI)->getValueAsDef("SchedModel");
1107 addWriteRes(*WRI, getProcModel(ModelDef).Index);
1108 }
1109 RecVec RADefs = Records.getAllDerivedDefinitions("ReadAdvance");
1110 for (RecIter RAI = RADefs.begin(), RAE = RADefs.end(); RAI != RAE; ++RAI) {
1111 Record *ModelDef = (*RAI)->getValueAsDef("SchedModel");
1112 addReadAdvance(*RAI, getProcModel(ModelDef).Index);
1113 }
1114 // Finalize each ProcModel by sorting the record arrays.
1115 for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
1116 CodeGenProcModel &PM = ProcModels[PIdx];
1117 std::sort(PM.WriteResDefs.begin(), PM.WriteResDefs.end(),
1118 LessRecord());
1119 std::sort(PM.ReadAdvanceDefs.begin(), PM.ReadAdvanceDefs.end(),
1120 LessRecord());
1121 std::sort(PM.ProcResourceDefs.begin(), PM.ProcResourceDefs.end(),
1122 LessRecord());
1123 DEBUG(
1124 PM.dump();
1125 dbgs() << "WriteResDefs: ";
1126 for (RecIter RI = PM.WriteResDefs.begin(),
1127 RE = PM.WriteResDefs.end(); RI != RE; ++RI) {
1128 if ((*RI)->isSubClassOf("WriteRes"))
1129 dbgs() << (*RI)->getValueAsDef("WriteType")->getName() << " ";
1130 else
1131 dbgs() << (*RI)->getName() << " ";
1132 }
1133 dbgs() << "\nReadAdvanceDefs: ";
1134 for (RecIter RI = PM.ReadAdvanceDefs.begin(),
1135 RE = PM.ReadAdvanceDefs.end(); RI != RE; ++RI) {
1136 if ((*RI)->isSubClassOf("ReadAdvance"))
1137 dbgs() << (*RI)->getValueAsDef("ReadType")->getName() << " ";
1138 else
1139 dbgs() << (*RI)->getName() << " ";
1140 }
1141 dbgs() << "\nProcResourceDefs: ";
1142 for (RecIter RI = PM.ProcResourceDefs.begin(),
1143 RE = PM.ProcResourceDefs.end(); RI != RE; ++RI) {
1144 dbgs() << (*RI)->getName() << " ";
1145 }
1146 dbgs() << '\n');
1147 }
1148}
1149
1150// Collect itinerary class resources for each processor.
1151void CodeGenSchedModels::collectItinProcResources(Record *ItinClassDef) {
1152 for (unsigned PIdx = 0, PEnd = ProcModels.size(); PIdx != PEnd; ++PIdx) {
1153 const CodeGenProcModel &PM = ProcModels[PIdx];
1154 // For all ItinRW entries.
1155 bool HasMatch = false;
1156 for (RecIter II = PM.ItinRWDefs.begin(), IE = PM.ItinRWDefs.end();
1157 II != IE; ++II) {
1158 RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
1159 if (!std::count(Matched.begin(), Matched.end(), ItinClassDef))
1160 continue;
1161 if (HasMatch)
1162 throw TGError((*II)->getLoc(), "Duplicate itinerary class "
1163 + ItinClassDef->getName()
1164 + " in ItinResources for " + PM.ModelName);
1165 HasMatch = true;
1166 IdxVec Writes, Reads;
1167 findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"), Writes, Reads);
1168 IdxVec ProcIndices(1, PIdx);
1169 collectRWResources(Writes, Reads, ProcIndices);
1170 }
1171 }
1172}
1173
1174
1175// Collect resources for a set of read/write types and processor indices.
1176void CodeGenSchedModels::collectRWResources(const IdxVec &Writes,
1177 const IdxVec &Reads,
1178 const IdxVec &ProcIndices) {
1179
1180 for (IdxIter WI = Writes.begin(), WE = Writes.end(); WI != WE; ++WI) {
1181 const CodeGenSchedRW &SchedRW = getSchedRW(*WI, /*IsRead=*/false);
1182 if (SchedRW.TheDef && SchedRW.TheDef->isSubClassOf("SchedWriteRes")) {
1183 for (IdxIter PI = ProcIndices.begin(), PE = ProcIndices.end();
1184 PI != PE; ++PI) {
1185 addWriteRes(SchedRW.TheDef, *PI);
1186 }
1187 }
1188 }
1189 for (IdxIter RI = Reads.begin(), RE = Reads.end(); RI != RE; ++RI) {
1190 const CodeGenSchedRW &SchedRW = getSchedRW(*RI, /*IsRead=*/true);
1191 if (SchedRW.TheDef && SchedRW.TheDef->isSubClassOf("SchedReadAdvance")) {
1192 for (IdxIter PI = ProcIndices.begin(), PE = ProcIndices.end();
1193 PI != PE; ++PI) {
1194 addReadAdvance(SchedRW.TheDef, *PI);
1195 }
1196 }
1197 }
1198}
1199
1200// Find the processor's resource units for this kind of resource.
1201Record *CodeGenSchedModels::findProcResUnits(Record *ProcResKind,
1202 const CodeGenProcModel &PM) const {
1203 if (ProcResKind->isSubClassOf("ProcResourceUnits"))
1204 return ProcResKind;
1205
1206 Record *ProcUnitDef = 0;
1207 RecVec ProcResourceDefs =
1208 Records.getAllDerivedDefinitions("ProcResourceUnits");
1209
1210 for (RecIter RI = ProcResourceDefs.begin(), RE = ProcResourceDefs.end();
1211 RI != RE; ++RI) {
1212
1213 if ((*RI)->getValueAsDef("Kind") == ProcResKind
1214 && (*RI)->getValueAsDef("SchedModel") == PM.ModelDef) {
1215 if (ProcUnitDef) {
1216 throw TGError((*RI)->getLoc(),
1217 "Multiple ProcessorResourceUnits associated with "
1218 + ProcResKind->getName());
1219 }
1220 ProcUnitDef = *RI;
1221 }
1222 }
1223 if (!ProcUnitDef) {
1224 throw TGError(ProcResKind->getLoc(),
1225 "No ProcessorResources associated with "
1226 + ProcResKind->getName());
1227 }
1228 return ProcUnitDef;
1229}
1230
1231// Iteratively add a resource and its super resources.
1232void CodeGenSchedModels::addProcResource(Record *ProcResKind,
1233 CodeGenProcModel &PM) {
1234 for (;;) {
1235 Record *ProcResUnits = findProcResUnits(ProcResKind, PM);
1236
1237 // See if this ProcResource is already associated with this processor.
1238 RecIter I = std::find(PM.ProcResourceDefs.begin(),
1239 PM.ProcResourceDefs.end(), ProcResUnits);
1240 if (I != PM.ProcResourceDefs.end())
1241 return;
1242
1243 PM.ProcResourceDefs.push_back(ProcResUnits);
1244 if (!ProcResUnits->getValueInit("Super")->isComplete())
1245 return;
1246
1247 ProcResKind = ProcResUnits->getValueAsDef("Super");
1248 }
1249}
1250
1251// Add resources for a SchedWrite to this processor if they don't exist.
1252void CodeGenSchedModels::addWriteRes(Record *ProcWriteResDef, unsigned PIdx) {
1253 RecVec &WRDefs = ProcModels[PIdx].WriteResDefs;
1254 RecIter WRI = std::find(WRDefs.begin(), WRDefs.end(), ProcWriteResDef);
1255 if (WRI != WRDefs.end())
1256 return;
1257 WRDefs.push_back(ProcWriteResDef);
1258
1259 // Visit ProcResourceKinds referenced by the newly discovered WriteRes.
1260 RecVec ProcResDefs = ProcWriteResDef->getValueAsListOfDefs("ProcResources");
1261 for (RecIter WritePRI = ProcResDefs.begin(), WritePRE = ProcResDefs.end();
1262 WritePRI != WritePRE; ++WritePRI) {
1263 addProcResource(*WritePRI, ProcModels[PIdx]);
1264 }
1265}
1266
1267// Add resources for a ReadAdvance to this processor if they don't exist.
1268void CodeGenSchedModels::addReadAdvance(Record *ProcReadAdvanceDef,
1269 unsigned PIdx) {
1270 RecVec &RADefs = ProcModels[PIdx].ReadAdvanceDefs;
1271 RecIter I = std::find(RADefs.begin(), RADefs.end(), ProcReadAdvanceDef);
1272 if (I != RADefs.end())
1273 return;
1274 RADefs.push_back(ProcReadAdvanceDef);
1275}
1276
Andrew Trickbc4ff6e2012-09-17 22:18:43 +00001277unsigned CodeGenProcModel::getProcResourceIdx(Record *PRDef) const {
1278 RecIter PRPos = std::find(ProcResourceDefs.begin(), ProcResourceDefs.end(),
1279 PRDef);
1280 if (PRPos == ProcResourceDefs.end())
1281 throw TGError(PRDef->getLoc(), "ProcResource def is not included in "
1282 "the ProcResources list for " + ModelName);
1283 // Idx=0 is reserved for invalid.
1284 return 1 + PRPos - ProcResourceDefs.begin();
1285}
1286
Andrew Trick48605c32012-09-15 00:19:57 +00001287#ifndef NDEBUG
1288void CodeGenProcModel::dump() const {
1289 dbgs() << Index << ": " << ModelName << " "
1290 << (ModelDef ? ModelDef->getName() : "inferred") << " "
1291 << (ItinsDef ? ItinsDef->getName() : "no itinerary") << '\n';
1292}
1293
1294void CodeGenSchedRW::dump() const {
1295 dbgs() << Name << (IsVariadic ? " (V) " : " ");
1296 if (IsSequence) {
1297 dbgs() << "(";
1298 dumpIdxVec(Sequence);
1299 dbgs() << ")";
1300 }
1301}
1302
1303void CodeGenSchedClass::dump(const CodeGenSchedModels* SchedModels) const {
1304 dbgs() << "SCHEDCLASS " << Name << '\n'
1305 << " Writes: ";
1306 for (unsigned i = 0, N = Writes.size(); i < N; ++i) {
1307 SchedModels->getSchedWrite(Writes[i]).dump();
1308 if (i < N-1) {
1309 dbgs() << '\n';
1310 dbgs().indent(10);
1311 }
1312 }
1313 dbgs() << "\n Reads: ";
1314 for (unsigned i = 0, N = Reads.size(); i < N; ++i) {
1315 SchedModels->getSchedRead(Reads[i]).dump();
1316 if (i < N-1) {
1317 dbgs() << '\n';
1318 dbgs().indent(10);
1319 }
1320 }
1321 dbgs() << "\n ProcIdx: "; dumpIdxVec(ProcIndices); dbgs() << '\n';
1322}
Andrew Trick5e613c22012-09-15 00:19:59 +00001323
1324void PredTransitions::dump() const {
1325 dbgs() << "Expanded Variants:\n";
1326 for (std::vector<PredTransition>::const_iterator
1327 TI = TransVec.begin(), TE = TransVec.end(); TI != TE; ++TI) {
1328 dbgs() << "{";
1329 for (SmallVectorImpl<PredCheck>::const_iterator
1330 PCI = TI->PredTerm.begin(), PCE = TI->PredTerm.end();
1331 PCI != PCE; ++PCI) {
1332 if (PCI != TI->PredTerm.begin())
1333 dbgs() << ", ";
1334 dbgs() << SchedModels.getSchedRW(PCI->RWIdx, PCI->IsRead).Name
1335 << ":" << PCI->Predicate->getName();
1336 }
1337 dbgs() << "},\n => {";
1338 for (SmallVectorImpl<SmallVector<unsigned,4> >::const_iterator
1339 WSI = TI->WriteSequences.begin(), WSE = TI->WriteSequences.end();
1340 WSI != WSE; ++WSI) {
1341 dbgs() << "(";
1342 for (SmallVectorImpl<unsigned>::const_iterator
1343 WI = WSI->begin(), WE = WSI->end(); WI != WE; ++WI) {
1344 if (WI != WSI->begin())
1345 dbgs() << ", ";
1346 dbgs() << SchedModels.getSchedWrite(*WI).Name;
1347 }
1348 dbgs() << "),";
1349 }
1350 dbgs() << "}\n";
1351 }
1352}
Andrew Trick48605c32012-09-15 00:19:57 +00001353#endif // NDEBUG