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