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