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