1 //===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===// 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 tablegen backend emits subtarget enumerations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenTarget.h" 15 #include "CodeGenSchedule.h" 16 #include "llvm/ADT/SmallPtrSet.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/MC/MCInstrItineraries.h" 21 #include "llvm/MC/MCSchedule.h" 22 #include "llvm/MC/SubtargetFeature.h" 23 #include "llvm/Support/Debug.h" 24 #include "llvm/Support/Format.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/TableGen/Error.h" 27 #include "llvm/TableGen/Record.h" 28 #include "llvm/TableGen/TableGenBackend.h" 29 #include <algorithm> 30 #include <cassert> 31 #include <cstdint> 32 #include <iterator> 33 #include <map> 34 #include <string> 35 #include <vector> 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "subtarget-emitter" 40 41 namespace { 42 43 class SubtargetEmitter { 44 // Each processor has a SchedClassDesc table with an entry for each SchedClass. 45 // The SchedClassDesc table indexes into a global write resource table, write 46 // latency table, and read advance table. 47 struct SchedClassTables { 48 std::vector<std::vector<MCSchedClassDesc>> ProcSchedClasses; 49 std::vector<MCWriteProcResEntry> WriteProcResources; 50 std::vector<MCWriteLatencyEntry> WriteLatencies; 51 std::vector<std::string> WriterNames; 52 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries; 53 54 // Reserve an invalid entry at index 0 55 SchedClassTables() { 56 ProcSchedClasses.resize(1); 57 WriteProcResources.resize(1); 58 WriteLatencies.resize(1); 59 WriterNames.push_back("InvalidWrite"); 60 ReadAdvanceEntries.resize(1); 61 } 62 }; 63 64 struct LessWriteProcResources { 65 bool operator()(const MCWriteProcResEntry &LHS, 66 const MCWriteProcResEntry &RHS) { 67 return LHS.ProcResourceIdx < RHS.ProcResourceIdx; 68 } 69 }; 70 71 const CodeGenTarget &TGT; 72 RecordKeeper &Records; 73 CodeGenSchedModels &SchedModels; 74 std::string Target; 75 76 void Enumeration(raw_ostream &OS); 77 unsigned FeatureKeyValues(raw_ostream &OS); 78 unsigned CPUKeyValues(raw_ostream &OS); 79 void FormItineraryStageString(const std::string &Names, 80 Record *ItinData, std::string &ItinString, 81 unsigned &NStages); 82 void FormItineraryOperandCycleString(Record *ItinData, std::string &ItinString, 83 unsigned &NOperandCycles); 84 void FormItineraryBypassString(const std::string &Names, 85 Record *ItinData, 86 std::string &ItinString, unsigned NOperandCycles); 87 void EmitStageAndOperandCycleData(raw_ostream &OS, 88 std::vector<std::vector<InstrItinerary>> 89 &ProcItinLists); 90 void EmitItineraries(raw_ostream &OS, 91 std::vector<std::vector<InstrItinerary>> 92 &ProcItinLists); 93 void EmitProcessorProp(raw_ostream &OS, const Record *R, StringRef Name, 94 char Separator); 95 void EmitProcessorResources(const CodeGenProcModel &ProcModel, 96 raw_ostream &OS); 97 Record *FindWriteResources(const CodeGenSchedRW &SchedWrite, 98 const CodeGenProcModel &ProcModel); 99 Record *FindReadAdvance(const CodeGenSchedRW &SchedRead, 100 const CodeGenProcModel &ProcModel); 101 void ExpandProcResources(RecVec &PRVec, std::vector<int64_t> &Cycles, 102 const CodeGenProcModel &ProcModel); 103 void GenSchedClassTables(const CodeGenProcModel &ProcModel, 104 SchedClassTables &SchedTables); 105 void EmitSchedClassTables(SchedClassTables &SchedTables, raw_ostream &OS); 106 void EmitProcessorModels(raw_ostream &OS); 107 void EmitProcessorLookup(raw_ostream &OS); 108 void EmitSchedModelHelpers(const std::string &ClassName, raw_ostream &OS); 109 void EmitSchedModel(raw_ostream &OS); 110 void EmitHwModeCheck(const std::string &ClassName, raw_ostream &OS); 111 void ParseFeaturesFunction(raw_ostream &OS, unsigned NumFeatures, 112 unsigned NumProcs); 113 114 public: 115 SubtargetEmitter(RecordKeeper &R, CodeGenTarget &TGT) 116 : TGT(TGT), Records(R), SchedModels(TGT.getSchedModels()), 117 Target(TGT.getName()) {} 118 119 void run(raw_ostream &o); 120 }; 121 122 } // end anonymous namespace 123 124 // 125 // Enumeration - Emit the specified class as an enumeration. 126 // 127 void SubtargetEmitter::Enumeration(raw_ostream &OS) { 128 // Get all records of class and sort 129 std::vector<Record*> DefList = 130 Records.getAllDerivedDefinitions("SubtargetFeature"); 131 std::sort(DefList.begin(), DefList.end(), LessRecord()); 132 133 unsigned N = DefList.size(); 134 if (N == 0) 135 return; 136 if (N > MAX_SUBTARGET_FEATURES) 137 PrintFatalError("Too many subtarget features! Bump MAX_SUBTARGET_FEATURES."); 138 139 OS << "namespace " << Target << " {\n"; 140 141 // Open enumeration. 142 OS << "enum {\n"; 143 144 // For each record 145 for (unsigned i = 0; i < N;) { 146 // Next record 147 Record *Def = DefList[i]; 148 149 // Get and emit name 150 OS << " " << Def->getName() << " = " << i; 151 if (++i < N) OS << ","; 152 153 OS << "\n"; 154 } 155 156 // Close enumeration and namespace 157 OS << "};\n"; 158 OS << "} // end namespace " << Target << "\n"; 159 } 160 161 // 162 // FeatureKeyValues - Emit data of all the subtarget features. Used by the 163 // command line. 164 // 165 unsigned SubtargetEmitter::FeatureKeyValues(raw_ostream &OS) { 166 // Gather and sort all the features 167 std::vector<Record*> FeatureList = 168 Records.getAllDerivedDefinitions("SubtargetFeature"); 169 170 if (FeatureList.empty()) 171 return 0; 172 173 std::sort(FeatureList.begin(), FeatureList.end(), LessRecordFieldName()); 174 175 // Begin feature table 176 OS << "// Sorted (by key) array of values for CPU features.\n" 177 << "extern const llvm::SubtargetFeatureKV " << Target 178 << "FeatureKV[] = {\n"; 179 180 // For each feature 181 unsigned NumFeatures = 0; 182 for (unsigned i = 0, N = FeatureList.size(); i < N; ++i) { 183 // Next feature 184 Record *Feature = FeatureList[i]; 185 186 StringRef Name = Feature->getName(); 187 StringRef CommandLineName = Feature->getValueAsString("Name"); 188 StringRef Desc = Feature->getValueAsString("Desc"); 189 190 if (CommandLineName.empty()) continue; 191 192 // Emit as { "feature", "description", { featureEnum }, { i1 , i2 , ... , in } } 193 OS << " { " 194 << "\"" << CommandLineName << "\", " 195 << "\"" << Desc << "\", " 196 << "{ " << Target << "::" << Name << " }, "; 197 198 const std::vector<Record*> &ImpliesList = 199 Feature->getValueAsListOfDefs("Implies"); 200 201 OS << "{"; 202 for (unsigned j = 0, M = ImpliesList.size(); j < M;) { 203 OS << " " << Target << "::" << ImpliesList[j]->getName(); 204 if (++j < M) OS << ","; 205 } 206 OS << " }"; 207 208 OS << " }"; 209 ++NumFeatures; 210 211 // Depending on 'if more in the list' emit comma 212 if ((i + 1) < N) OS << ","; 213 214 OS << "\n"; 215 } 216 217 // End feature table 218 OS << "};\n"; 219 220 return NumFeatures; 221 } 222 223 // 224 // CPUKeyValues - Emit data of all the subtarget processors. Used by command 225 // line. 226 // 227 unsigned SubtargetEmitter::CPUKeyValues(raw_ostream &OS) { 228 // Gather and sort processor information 229 std::vector<Record*> ProcessorList = 230 Records.getAllDerivedDefinitions("Processor"); 231 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName()); 232 233 // Begin processor table 234 OS << "// Sorted (by key) array of values for CPU subtype.\n" 235 << "extern const llvm::SubtargetFeatureKV " << Target 236 << "SubTypeKV[] = {\n"; 237 238 // For each processor 239 for (unsigned i = 0, N = ProcessorList.size(); i < N;) { 240 // Next processor 241 Record *Processor = ProcessorList[i]; 242 243 StringRef Name = Processor->getValueAsString("Name"); 244 const std::vector<Record*> &FeatureList = 245 Processor->getValueAsListOfDefs("Features"); 246 247 // Emit as { "cpu", "description", { f1 , f2 , ... fn } }, 248 OS << " { " 249 << "\"" << Name << "\", " 250 << "\"Select the " << Name << " processor\", "; 251 252 OS << "{"; 253 for (unsigned j = 0, M = FeatureList.size(); j < M;) { 254 OS << " " << Target << "::" << FeatureList[j]->getName(); 255 if (++j < M) OS << ","; 256 } 257 OS << " }"; 258 259 // The { } is for the "implies" section of this data structure. 260 OS << ", { } }"; 261 262 // Depending on 'if more in the list' emit comma 263 if (++i < N) OS << ","; 264 265 OS << "\n"; 266 } 267 268 // End processor table 269 OS << "};\n"; 270 271 return ProcessorList.size(); 272 } 273 274 // 275 // FormItineraryStageString - Compose a string containing the stage 276 // data initialization for the specified itinerary. N is the number 277 // of stages. 278 // 279 void SubtargetEmitter::FormItineraryStageString(const std::string &Name, 280 Record *ItinData, 281 std::string &ItinString, 282 unsigned &NStages) { 283 // Get states list 284 const std::vector<Record*> &StageList = 285 ItinData->getValueAsListOfDefs("Stages"); 286 287 // For each stage 288 unsigned N = NStages = StageList.size(); 289 for (unsigned i = 0; i < N;) { 290 // Next stage 291 const Record *Stage = StageList[i]; 292 293 // Form string as ,{ cycles, u1 | u2 | ... | un, timeinc, kind } 294 int Cycles = Stage->getValueAsInt("Cycles"); 295 ItinString += " { " + itostr(Cycles) + ", "; 296 297 // Get unit list 298 const std::vector<Record*> &UnitList = Stage->getValueAsListOfDefs("Units"); 299 300 // For each unit 301 for (unsigned j = 0, M = UnitList.size(); j < M;) { 302 // Add name and bitwise or 303 ItinString += Name + "FU::" + UnitList[j]->getName().str(); 304 if (++j < M) ItinString += " | "; 305 } 306 307 int TimeInc = Stage->getValueAsInt("TimeInc"); 308 ItinString += ", " + itostr(TimeInc); 309 310 int Kind = Stage->getValueAsInt("Kind"); 311 ItinString += ", (llvm::InstrStage::ReservationKinds)" + itostr(Kind); 312 313 // Close off stage 314 ItinString += " }"; 315 if (++i < N) ItinString += ", "; 316 } 317 } 318 319 // 320 // FormItineraryOperandCycleString - Compose a string containing the 321 // operand cycle initialization for the specified itinerary. N is the 322 // number of operands that has cycles specified. 323 // 324 void SubtargetEmitter::FormItineraryOperandCycleString(Record *ItinData, 325 std::string &ItinString, unsigned &NOperandCycles) { 326 // Get operand cycle list 327 const std::vector<int64_t> &OperandCycleList = 328 ItinData->getValueAsListOfInts("OperandCycles"); 329 330 // For each operand cycle 331 unsigned N = NOperandCycles = OperandCycleList.size(); 332 for (unsigned i = 0; i < N;) { 333 // Next operand cycle 334 const int OCycle = OperandCycleList[i]; 335 336 ItinString += " " + itostr(OCycle); 337 if (++i < N) ItinString += ", "; 338 } 339 } 340 341 void SubtargetEmitter::FormItineraryBypassString(const std::string &Name, 342 Record *ItinData, 343 std::string &ItinString, 344 unsigned NOperandCycles) { 345 const std::vector<Record*> &BypassList = 346 ItinData->getValueAsListOfDefs("Bypasses"); 347 unsigned N = BypassList.size(); 348 unsigned i = 0; 349 for (; i < N;) { 350 ItinString += Name + "Bypass::" + BypassList[i]->getName().str(); 351 if (++i < NOperandCycles) ItinString += ", "; 352 } 353 for (; i < NOperandCycles;) { 354 ItinString += " 0"; 355 if (++i < NOperandCycles) ItinString += ", "; 356 } 357 } 358 359 // 360 // EmitStageAndOperandCycleData - Generate unique itinerary stages and operand 361 // cycle tables. Create a list of InstrItinerary objects (ProcItinLists) indexed 362 // by CodeGenSchedClass::Index. 363 // 364 void SubtargetEmitter:: 365 EmitStageAndOperandCycleData(raw_ostream &OS, 366 std::vector<std::vector<InstrItinerary>> 367 &ProcItinLists) { 368 // Multiple processor models may share an itinerary record. Emit it once. 369 SmallPtrSet<Record*, 8> ItinsDefSet; 370 371 // Emit functional units for all the itineraries. 372 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { 373 374 if (!ItinsDefSet.insert(ProcModel.ItinsDef).second) 375 continue; 376 377 std::vector<Record*> FUs = ProcModel.ItinsDef->getValueAsListOfDefs("FU"); 378 if (FUs.empty()) 379 continue; 380 381 StringRef Name = ProcModel.ItinsDef->getName(); 382 OS << "\n// Functional units for \"" << Name << "\"\n" 383 << "namespace " << Name << "FU {\n"; 384 385 for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j) 386 OS << " const unsigned " << FUs[j]->getName() 387 << " = 1 << " << j << ";\n"; 388 389 OS << "} // end namespace " << Name << "FU\n"; 390 391 std::vector<Record*> BPs = ProcModel.ItinsDef->getValueAsListOfDefs("BP"); 392 if (!BPs.empty()) { 393 OS << "\n// Pipeline forwarding pathes for itineraries \"" << Name 394 << "\"\n" << "namespace " << Name << "Bypass {\n"; 395 396 OS << " const unsigned NoBypass = 0;\n"; 397 for (unsigned j = 0, BPN = BPs.size(); j < BPN; ++j) 398 OS << " const unsigned " << BPs[j]->getName() 399 << " = 1 << " << j << ";\n"; 400 401 OS << "} // end namespace " << Name << "Bypass\n"; 402 } 403 } 404 405 // Begin stages table 406 std::string StageTable = "\nextern const llvm::InstrStage " + Target + 407 "Stages[] = {\n"; 408 StageTable += " { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n"; 409 410 // Begin operand cycle table 411 std::string OperandCycleTable = "extern const unsigned " + Target + 412 "OperandCycles[] = {\n"; 413 OperandCycleTable += " 0, // No itinerary\n"; 414 415 // Begin pipeline bypass table 416 std::string BypassTable = "extern const unsigned " + Target + 417 "ForwardingPaths[] = {\n"; 418 BypassTable += " 0, // No itinerary\n"; 419 420 // For each Itinerary across all processors, add a unique entry to the stages, 421 // operand cycles, and pipeline bypass tables. Then add the new Itinerary 422 // object with computed offsets to the ProcItinLists result. 423 unsigned StageCount = 1, OperandCycleCount = 1; 424 std::map<std::string, unsigned> ItinStageMap, ItinOperandMap; 425 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { 426 // Add process itinerary to the list. 427 ProcItinLists.resize(ProcItinLists.size()+1); 428 429 // If this processor defines no itineraries, then leave the itinerary list 430 // empty. 431 std::vector<InstrItinerary> &ItinList = ProcItinLists.back(); 432 if (!ProcModel.hasItineraries()) 433 continue; 434 435 StringRef Name = ProcModel.ItinsDef->getName(); 436 437 ItinList.resize(SchedModels.numInstrSchedClasses()); 438 assert(ProcModel.ItinDefList.size() == ItinList.size() && "bad Itins"); 439 440 for (unsigned SchedClassIdx = 0, SchedClassEnd = ItinList.size(); 441 SchedClassIdx < SchedClassEnd; ++SchedClassIdx) { 442 443 // Next itinerary data 444 Record *ItinData = ProcModel.ItinDefList[SchedClassIdx]; 445 446 // Get string and stage count 447 std::string ItinStageString; 448 unsigned NStages = 0; 449 if (ItinData) 450 FormItineraryStageString(Name, ItinData, ItinStageString, NStages); 451 452 // Get string and operand cycle count 453 std::string ItinOperandCycleString; 454 unsigned NOperandCycles = 0; 455 std::string ItinBypassString; 456 if (ItinData) { 457 FormItineraryOperandCycleString(ItinData, ItinOperandCycleString, 458 NOperandCycles); 459 460 FormItineraryBypassString(Name, ItinData, ItinBypassString, 461 NOperandCycles); 462 } 463 464 // Check to see if stage already exists and create if it doesn't 465 unsigned FindStage = 0; 466 if (NStages > 0) { 467 FindStage = ItinStageMap[ItinStageString]; 468 if (FindStage == 0) { 469 // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // indices 470 StageTable += ItinStageString + ", // " + itostr(StageCount); 471 if (NStages > 1) 472 StageTable += "-" + itostr(StageCount + NStages - 1); 473 StageTable += "\n"; 474 // Record Itin class number. 475 ItinStageMap[ItinStageString] = FindStage = StageCount; 476 StageCount += NStages; 477 } 478 } 479 480 // Check to see if operand cycle already exists and create if it doesn't 481 unsigned FindOperandCycle = 0; 482 if (NOperandCycles > 0) { 483 std::string ItinOperandString = ItinOperandCycleString+ItinBypassString; 484 FindOperandCycle = ItinOperandMap[ItinOperandString]; 485 if (FindOperandCycle == 0) { 486 // Emit as cycle, // index 487 OperandCycleTable += ItinOperandCycleString + ", // "; 488 std::string OperandIdxComment = itostr(OperandCycleCount); 489 if (NOperandCycles > 1) 490 OperandIdxComment += "-" 491 + itostr(OperandCycleCount + NOperandCycles - 1); 492 OperandCycleTable += OperandIdxComment + "\n"; 493 // Record Itin class number. 494 ItinOperandMap[ItinOperandCycleString] = 495 FindOperandCycle = OperandCycleCount; 496 // Emit as bypass, // index 497 BypassTable += ItinBypassString + ", // " + OperandIdxComment + "\n"; 498 OperandCycleCount += NOperandCycles; 499 } 500 } 501 502 // Set up itinerary as location and location + stage count 503 int NumUOps = ItinData ? ItinData->getValueAsInt("NumMicroOps") : 0; 504 InstrItinerary Intinerary = { NumUOps, FindStage, FindStage + NStages, 505 FindOperandCycle, 506 FindOperandCycle + NOperandCycles }; 507 508 // Inject - empty slots will be 0, 0 509 ItinList[SchedClassIdx] = Intinerary; 510 } 511 } 512 513 // Closing stage 514 StageTable += " { 0, 0, 0, llvm::InstrStage::Required } // End stages\n"; 515 StageTable += "};\n"; 516 517 // Closing operand cycles 518 OperandCycleTable += " 0 // End operand cycles\n"; 519 OperandCycleTable += "};\n"; 520 521 BypassTable += " 0 // End bypass tables\n"; 522 BypassTable += "};\n"; 523 524 // Emit tables. 525 OS << StageTable; 526 OS << OperandCycleTable; 527 OS << BypassTable; 528 } 529 530 // 531 // EmitProcessorData - Generate data for processor itineraries that were 532 // computed during EmitStageAndOperandCycleData(). ProcItinLists lists all 533 // Itineraries for each processor. The Itinerary lists are indexed on 534 // CodeGenSchedClass::Index. 535 // 536 void SubtargetEmitter:: 537 EmitItineraries(raw_ostream &OS, 538 std::vector<std::vector<InstrItinerary>> &ProcItinLists) { 539 // Multiple processor models may share an itinerary record. Emit it once. 540 SmallPtrSet<Record*, 8> ItinsDefSet; 541 542 // For each processor's machine model 543 std::vector<std::vector<InstrItinerary>>::iterator 544 ProcItinListsIter = ProcItinLists.begin(); 545 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(), 546 PE = SchedModels.procModelEnd(); PI != PE; ++PI, ++ProcItinListsIter) { 547 548 Record *ItinsDef = PI->ItinsDef; 549 if (!ItinsDefSet.insert(ItinsDef).second) 550 continue; 551 552 // Get the itinerary list for the processor. 553 assert(ProcItinListsIter != ProcItinLists.end() && "bad iterator"); 554 std::vector<InstrItinerary> &ItinList = *ProcItinListsIter; 555 556 // Empty itineraries aren't referenced anywhere in the tablegen output 557 // so don't emit them. 558 if (ItinList.empty()) 559 continue; 560 561 OS << "\n"; 562 OS << "static const llvm::InstrItinerary "; 563 564 // Begin processor itinerary table 565 OS << ItinsDef->getName() << "[] = {\n"; 566 567 // For each itinerary class in CodeGenSchedClass::Index order. 568 for (unsigned j = 0, M = ItinList.size(); j < M; ++j) { 569 InstrItinerary &Intinerary = ItinList[j]; 570 571 // Emit Itinerary in the form of 572 // { firstStage, lastStage, firstCycle, lastCycle } // index 573 OS << " { " << 574 Intinerary.NumMicroOps << ", " << 575 Intinerary.FirstStage << ", " << 576 Intinerary.LastStage << ", " << 577 Intinerary.FirstOperandCycle << ", " << 578 Intinerary.LastOperandCycle << " }" << 579 ", // " << j << " " << SchedModels.getSchedClass(j).Name << "\n"; 580 } 581 // End processor itinerary table 582 OS << " { 0, ~0U, ~0U, ~0U, ~0U } // end marker\n"; 583 OS << "};\n"; 584 } 585 } 586 587 // Emit either the value defined in the TableGen Record, or the default 588 // value defined in the C++ header. The Record is null if the processor does not 589 // define a model. 590 void SubtargetEmitter::EmitProcessorProp(raw_ostream &OS, const Record *R, 591 StringRef Name, char Separator) { 592 OS << " "; 593 int V = R ? R->getValueAsInt(Name) : -1; 594 if (V >= 0) 595 OS << V << Separator << " // " << Name; 596 else 597 OS << "MCSchedModel::Default" << Name << Separator; 598 OS << '\n'; 599 } 600 601 void SubtargetEmitter::EmitProcessorResources(const CodeGenProcModel &ProcModel, 602 raw_ostream &OS) { 603 char Sep = ProcModel.ProcResourceDefs.empty() ? ' ' : ','; 604 605 OS << "\n// {Name, NumUnits, SuperIdx, IsBuffered}\n"; 606 OS << "static const llvm::MCProcResourceDesc " 607 << ProcModel.ModelName << "ProcResources" << "[] = {\n" 608 << " {DBGFIELD(\"InvalidUnit\") 0, 0, 0}" << Sep << "\n"; 609 610 for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) { 611 Record *PRDef = ProcModel.ProcResourceDefs[i]; 612 613 Record *SuperDef = nullptr; 614 unsigned SuperIdx = 0; 615 unsigned NumUnits = 0; 616 int BufferSize = PRDef->getValueAsInt("BufferSize"); 617 if (PRDef->isSubClassOf("ProcResGroup")) { 618 RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources"); 619 for (Record *RU : ResUnits) { 620 NumUnits += RU->getValueAsInt("NumUnits"); 621 } 622 } 623 else { 624 // Find the SuperIdx 625 if (PRDef->getValueInit("Super")->isComplete()) { 626 SuperDef = SchedModels.findProcResUnits( 627 PRDef->getValueAsDef("Super"), ProcModel); 628 SuperIdx = ProcModel.getProcResourceIdx(SuperDef); 629 } 630 NumUnits = PRDef->getValueAsInt("NumUnits"); 631 } 632 // Emit the ProcResourceDesc 633 if (i+1 == e) 634 Sep = ' '; 635 OS << " {DBGFIELD(\"" << PRDef->getName() << "\") "; 636 if (PRDef->getName().size() < 15) 637 OS.indent(15 - PRDef->getName().size()); 638 OS << NumUnits << ", " << SuperIdx << ", " 639 << BufferSize << "}" << Sep << " // #" << i+1; 640 if (SuperDef) 641 OS << ", Super=" << SuperDef->getName(); 642 OS << "\n"; 643 } 644 OS << "};\n"; 645 } 646 647 // Find the WriteRes Record that defines processor resources for this 648 // SchedWrite. 649 Record *SubtargetEmitter::FindWriteResources( 650 const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) { 651 652 // Check if the SchedWrite is already subtarget-specific and directly 653 // specifies a set of processor resources. 654 if (SchedWrite.TheDef->isSubClassOf("SchedWriteRes")) 655 return SchedWrite.TheDef; 656 657 Record *AliasDef = nullptr; 658 for (Record *A : SchedWrite.Aliases) { 659 const CodeGenSchedRW &AliasRW = 660 SchedModels.getSchedRW(A->getValueAsDef("AliasRW")); 661 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) { 662 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel"); 663 if (&SchedModels.getProcModel(ModelDef) != &ProcModel) 664 continue; 665 } 666 if (AliasDef) 667 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases " 668 "defined for processor " + ProcModel.ModelName + 669 " Ensure only one SchedAlias exists per RW."); 670 AliasDef = AliasRW.TheDef; 671 } 672 if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes")) 673 return AliasDef; 674 675 // Check this processor's list of write resources. 676 Record *ResDef = nullptr; 677 for (Record *WR : ProcModel.WriteResDefs) { 678 if (!WR->isSubClassOf("WriteRes")) 679 continue; 680 if (AliasDef == WR->getValueAsDef("WriteType") 681 || SchedWrite.TheDef == WR->getValueAsDef("WriteType")) { 682 if (ResDef) { 683 PrintFatalError(WR->getLoc(), "Resources are defined for both " 684 "SchedWrite and its alias on processor " + 685 ProcModel.ModelName); 686 } 687 ResDef = WR; 688 } 689 } 690 // TODO: If ProcModel has a base model (previous generation processor), 691 // then call FindWriteResources recursively with that model here. 692 if (!ResDef) { 693 PrintFatalError(ProcModel.ModelDef->getLoc(), 694 std::string("Processor does not define resources for ") 695 + SchedWrite.TheDef->getName()); 696 } 697 return ResDef; 698 } 699 700 /// Find the ReadAdvance record for the given SchedRead on this processor or 701 /// return NULL. 702 Record *SubtargetEmitter::FindReadAdvance(const CodeGenSchedRW &SchedRead, 703 const CodeGenProcModel &ProcModel) { 704 // Check for SchedReads that directly specify a ReadAdvance. 705 if (SchedRead.TheDef->isSubClassOf("SchedReadAdvance")) 706 return SchedRead.TheDef; 707 708 // Check this processor's list of aliases for SchedRead. 709 Record *AliasDef = nullptr; 710 for (Record *A : SchedRead.Aliases) { 711 const CodeGenSchedRW &AliasRW = 712 SchedModels.getSchedRW(A->getValueAsDef("AliasRW")); 713 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) { 714 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel"); 715 if (&SchedModels.getProcModel(ModelDef) != &ProcModel) 716 continue; 717 } 718 if (AliasDef) 719 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases " 720 "defined for processor " + ProcModel.ModelName + 721 " Ensure only one SchedAlias exists per RW."); 722 AliasDef = AliasRW.TheDef; 723 } 724 if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance")) 725 return AliasDef; 726 727 // Check this processor's ReadAdvanceList. 728 Record *ResDef = nullptr; 729 for (Record *RA : ProcModel.ReadAdvanceDefs) { 730 if (!RA->isSubClassOf("ReadAdvance")) 731 continue; 732 if (AliasDef == RA->getValueAsDef("ReadType") 733 || SchedRead.TheDef == RA->getValueAsDef("ReadType")) { 734 if (ResDef) { 735 PrintFatalError(RA->getLoc(), "Resources are defined for both " 736 "SchedRead and its alias on processor " + 737 ProcModel.ModelName); 738 } 739 ResDef = RA; 740 } 741 } 742 // TODO: If ProcModel has a base model (previous generation processor), 743 // then call FindReadAdvance recursively with that model here. 744 if (!ResDef && SchedRead.TheDef->getName() != "ReadDefault") { 745 PrintFatalError(ProcModel.ModelDef->getLoc(), 746 std::string("Processor does not define resources for ") 747 + SchedRead.TheDef->getName()); 748 } 749 return ResDef; 750 } 751 752 // Expand an explicit list of processor resources into a full list of implied 753 // resource groups and super resources that cover them. 754 void SubtargetEmitter::ExpandProcResources(RecVec &PRVec, 755 std::vector<int64_t> &Cycles, 756 const CodeGenProcModel &PM) { 757 // Default to 1 resource cycle. 758 Cycles.resize(PRVec.size(), 1); 759 for (unsigned i = 0, e = PRVec.size(); i != e; ++i) { 760 Record *PRDef = PRVec[i]; 761 RecVec SubResources; 762 if (PRDef->isSubClassOf("ProcResGroup")) 763 SubResources = PRDef->getValueAsListOfDefs("Resources"); 764 else { 765 SubResources.push_back(PRDef); 766 PRDef = SchedModels.findProcResUnits(PRVec[i], PM); 767 for (Record *SubDef = PRDef; 768 SubDef->getValueInit("Super")->isComplete();) { 769 if (SubDef->isSubClassOf("ProcResGroup")) { 770 // Disallow this for simplicitly. 771 PrintFatalError(SubDef->getLoc(), "Processor resource group " 772 " cannot be a super resources."); 773 } 774 Record *SuperDef = 775 SchedModels.findProcResUnits(SubDef->getValueAsDef("Super"), PM); 776 PRVec.push_back(SuperDef); 777 Cycles.push_back(Cycles[i]); 778 SubDef = SuperDef; 779 } 780 } 781 for (Record *PR : PM.ProcResourceDefs) { 782 if (PR == PRDef || !PR->isSubClassOf("ProcResGroup")) 783 continue; 784 RecVec SuperResources = PR->getValueAsListOfDefs("Resources"); 785 RecIter SubI = SubResources.begin(), SubE = SubResources.end(); 786 for( ; SubI != SubE; ++SubI) { 787 if (!is_contained(SuperResources, *SubI)) { 788 break; 789 } 790 } 791 if (SubI == SubE) { 792 PRVec.push_back(PR); 793 Cycles.push_back(Cycles[i]); 794 } 795 } 796 } 797 } 798 799 // Generate the SchedClass table for this processor and update global 800 // tables. Must be called for each processor in order. 801 void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel, 802 SchedClassTables &SchedTables) { 803 SchedTables.ProcSchedClasses.resize(SchedTables.ProcSchedClasses.size() + 1); 804 if (!ProcModel.hasInstrSchedModel()) 805 return; 806 807 std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back(); 808 DEBUG(dbgs() << "\n+++ SCHED CLASSES (GenSchedClassTables) +++\n"); 809 for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) { 810 DEBUG(SC.dump(&SchedModels)); 811 812 SCTab.resize(SCTab.size() + 1); 813 MCSchedClassDesc &SCDesc = SCTab.back(); 814 // SCDesc.Name is guarded by NDEBUG 815 SCDesc.NumMicroOps = 0; 816 SCDesc.BeginGroup = false; 817 SCDesc.EndGroup = false; 818 SCDesc.WriteProcResIdx = 0; 819 SCDesc.WriteLatencyIdx = 0; 820 SCDesc.ReadAdvanceIdx = 0; 821 822 // A Variant SchedClass has no resources of its own. 823 bool HasVariants = false; 824 for (std::vector<CodeGenSchedTransition>::const_iterator 825 TI = SC.Transitions.begin(), TE = SC.Transitions.end(); 826 TI != TE; ++TI) { 827 if (TI->ProcIndices[0] == 0) { 828 HasVariants = true; 829 break; 830 } 831 if (is_contained(TI->ProcIndices, ProcModel.Index)) { 832 HasVariants = true; 833 break; 834 } 835 } 836 if (HasVariants) { 837 SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps; 838 continue; 839 } 840 841 // Determine if the SchedClass is actually reachable on this processor. If 842 // not don't try to locate the processor resources, it will fail. 843 // If ProcIndices contains 0, this class applies to all processors. 844 assert(!SC.ProcIndices.empty() && "expect at least one procidx"); 845 if (SC.ProcIndices[0] != 0) { 846 if (!is_contained(SC.ProcIndices, ProcModel.Index)) 847 continue; 848 } 849 IdxVec Writes = SC.Writes; 850 IdxVec Reads = SC.Reads; 851 if (!SC.InstRWs.empty()) { 852 // This class has a default ReadWrite list which can be overriden by 853 // InstRW definitions. 854 Record *RWDef = nullptr; 855 for (Record *RW : SC.InstRWs) { 856 Record *RWModelDef = RW->getValueAsDef("SchedModel"); 857 if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) { 858 RWDef = RW; 859 break; 860 } 861 } 862 if (RWDef) { 863 Writes.clear(); 864 Reads.clear(); 865 SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"), 866 Writes, Reads); 867 } 868 } 869 if (Writes.empty()) { 870 // Check this processor's itinerary class resources. 871 for (Record *I : ProcModel.ItinRWDefs) { 872 RecVec Matched = I->getValueAsListOfDefs("MatchedItinClasses"); 873 if (is_contained(Matched, SC.ItinClassDef)) { 874 SchedModels.findRWs(I->getValueAsListOfDefs("OperandReadWrites"), 875 Writes, Reads); 876 break; 877 } 878 } 879 if (Writes.empty()) { 880 DEBUG(dbgs() << ProcModel.ModelName 881 << " does not have resources for class " << SC.Name << '\n'); 882 } 883 } 884 // Sum resources across all operand writes. 885 std::vector<MCWriteProcResEntry> WriteProcResources; 886 std::vector<MCWriteLatencyEntry> WriteLatencies; 887 std::vector<std::string> WriterNames; 888 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries; 889 for (unsigned W : Writes) { 890 IdxVec WriteSeq; 891 SchedModels.expandRWSeqForProc(W, WriteSeq, /*IsRead=*/false, 892 ProcModel); 893 894 // For each operand, create a latency entry. 895 MCWriteLatencyEntry WLEntry; 896 WLEntry.Cycles = 0; 897 unsigned WriteID = WriteSeq.back(); 898 WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name); 899 // If this Write is not referenced by a ReadAdvance, don't distinguish it 900 // from other WriteLatency entries. 901 if (!SchedModels.hasReadOfWrite( 902 SchedModels.getSchedWrite(WriteID).TheDef)) { 903 WriteID = 0; 904 } 905 WLEntry.WriteResourceID = WriteID; 906 907 for (unsigned WS : WriteSeq) { 908 909 Record *WriteRes = 910 FindWriteResources(SchedModels.getSchedWrite(WS), ProcModel); 911 912 // Mark the parent class as invalid for unsupported write types. 913 if (WriteRes->getValueAsBit("Unsupported")) { 914 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps; 915 break; 916 } 917 WLEntry.Cycles += WriteRes->getValueAsInt("Latency"); 918 SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps"); 919 SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup"); 920 SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup"); 921 SCDesc.BeginGroup |= WriteRes->getValueAsBit("SingleIssue"); 922 SCDesc.EndGroup |= WriteRes->getValueAsBit("SingleIssue"); 923 924 // Create an entry for each ProcResource listed in WriteRes. 925 RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources"); 926 std::vector<int64_t> Cycles = 927 WriteRes->getValueAsListOfInts("ResourceCycles"); 928 929 ExpandProcResources(PRVec, Cycles, ProcModel); 930 931 for (unsigned PRIdx = 0, PREnd = PRVec.size(); 932 PRIdx != PREnd; ++PRIdx) { 933 MCWriteProcResEntry WPREntry; 934 WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]); 935 assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx"); 936 WPREntry.Cycles = Cycles[PRIdx]; 937 // If this resource is already used in this sequence, add the current 938 // entry's cycles so that the same resource appears to be used 939 // serially, rather than multiple parallel uses. This is important for 940 // in-order machine where the resource consumption is a hazard. 941 unsigned WPRIdx = 0, WPREnd = WriteProcResources.size(); 942 for( ; WPRIdx != WPREnd; ++WPRIdx) { 943 if (WriteProcResources[WPRIdx].ProcResourceIdx 944 == WPREntry.ProcResourceIdx) { 945 WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles; 946 break; 947 } 948 } 949 if (WPRIdx == WPREnd) 950 WriteProcResources.push_back(WPREntry); 951 } 952 } 953 WriteLatencies.push_back(WLEntry); 954 } 955 // Create an entry for each operand Read in this SchedClass. 956 // Entries must be sorted first by UseIdx then by WriteResourceID. 957 for (unsigned UseIdx = 0, EndIdx = Reads.size(); 958 UseIdx != EndIdx; ++UseIdx) { 959 Record *ReadAdvance = 960 FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel); 961 if (!ReadAdvance) 962 continue; 963 964 // Mark the parent class as invalid for unsupported write types. 965 if (ReadAdvance->getValueAsBit("Unsupported")) { 966 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps; 967 break; 968 } 969 RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites"); 970 IdxVec WriteIDs; 971 if (ValidWrites.empty()) 972 WriteIDs.push_back(0); 973 else { 974 for (Record *VW : ValidWrites) { 975 WriteIDs.push_back(SchedModels.getSchedRWIdx(VW, /*IsRead=*/false)); 976 } 977 } 978 std::sort(WriteIDs.begin(), WriteIDs.end()); 979 for(unsigned W : WriteIDs) { 980 MCReadAdvanceEntry RAEntry; 981 RAEntry.UseIdx = UseIdx; 982 RAEntry.WriteResourceID = W; 983 RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles"); 984 ReadAdvanceEntries.push_back(RAEntry); 985 } 986 } 987 if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) { 988 WriteProcResources.clear(); 989 WriteLatencies.clear(); 990 ReadAdvanceEntries.clear(); 991 } 992 // Add the information for this SchedClass to the global tables using basic 993 // compression. 994 // 995 // WritePrecRes entries are sorted by ProcResIdx. 996 std::sort(WriteProcResources.begin(), WriteProcResources.end(), 997 LessWriteProcResources()); 998 999 SCDesc.NumWriteProcResEntries = WriteProcResources.size(); 1000 std::vector<MCWriteProcResEntry>::iterator WPRPos = 1001 std::search(SchedTables.WriteProcResources.begin(), 1002 SchedTables.WriteProcResources.end(), 1003 WriteProcResources.begin(), WriteProcResources.end()); 1004 if (WPRPos != SchedTables.WriteProcResources.end()) 1005 SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin(); 1006 else { 1007 SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size(); 1008 SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(), 1009 WriteProcResources.end()); 1010 } 1011 // Latency entries must remain in operand order. 1012 SCDesc.NumWriteLatencyEntries = WriteLatencies.size(); 1013 std::vector<MCWriteLatencyEntry>::iterator WLPos = 1014 std::search(SchedTables.WriteLatencies.begin(), 1015 SchedTables.WriteLatencies.end(), 1016 WriteLatencies.begin(), WriteLatencies.end()); 1017 if (WLPos != SchedTables.WriteLatencies.end()) { 1018 unsigned idx = WLPos - SchedTables.WriteLatencies.begin(); 1019 SCDesc.WriteLatencyIdx = idx; 1020 for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i) 1021 if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) == 1022 std::string::npos) { 1023 SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i]; 1024 } 1025 } 1026 else { 1027 SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size(); 1028 SchedTables.WriteLatencies.insert(SchedTables.WriteLatencies.end(), 1029 WriteLatencies.begin(), 1030 WriteLatencies.end()); 1031 SchedTables.WriterNames.insert(SchedTables.WriterNames.end(), 1032 WriterNames.begin(), WriterNames.end()); 1033 } 1034 // ReadAdvanceEntries must remain in operand order. 1035 SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size(); 1036 std::vector<MCReadAdvanceEntry>::iterator RAPos = 1037 std::search(SchedTables.ReadAdvanceEntries.begin(), 1038 SchedTables.ReadAdvanceEntries.end(), 1039 ReadAdvanceEntries.begin(), ReadAdvanceEntries.end()); 1040 if (RAPos != SchedTables.ReadAdvanceEntries.end()) 1041 SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin(); 1042 else { 1043 SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size(); 1044 SchedTables.ReadAdvanceEntries.insert(RAPos, ReadAdvanceEntries.begin(), 1045 ReadAdvanceEntries.end()); 1046 } 1047 } 1048 } 1049 1050 // Emit SchedClass tables for all processors and associated global tables. 1051 void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables, 1052 raw_ostream &OS) { 1053 // Emit global WriteProcResTable. 1054 OS << "\n// {ProcResourceIdx, Cycles}\n" 1055 << "extern const llvm::MCWriteProcResEntry " 1056 << Target << "WriteProcResTable[] = {\n" 1057 << " { 0, 0}, // Invalid\n"; 1058 for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size(); 1059 WPRIdx != WPREnd; ++WPRIdx) { 1060 MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx]; 1061 OS << " {" << format("%2d", WPREntry.ProcResourceIdx) << ", " 1062 << format("%2d", WPREntry.Cycles) << "}"; 1063 if (WPRIdx + 1 < WPREnd) 1064 OS << ','; 1065 OS << " // #" << WPRIdx << '\n'; 1066 } 1067 OS << "}; // " << Target << "WriteProcResTable\n"; 1068 1069 // Emit global WriteLatencyTable. 1070 OS << "\n// {Cycles, WriteResourceID}\n" 1071 << "extern const llvm::MCWriteLatencyEntry " 1072 << Target << "WriteLatencyTable[] = {\n" 1073 << " { 0, 0}, // Invalid\n"; 1074 for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size(); 1075 WLIdx != WLEnd; ++WLIdx) { 1076 MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx]; 1077 OS << " {" << format("%2d", WLEntry.Cycles) << ", " 1078 << format("%2d", WLEntry.WriteResourceID) << "}"; 1079 if (WLIdx + 1 < WLEnd) 1080 OS << ','; 1081 OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n'; 1082 } 1083 OS << "}; // " << Target << "WriteLatencyTable\n"; 1084 1085 // Emit global ReadAdvanceTable. 1086 OS << "\n// {UseIdx, WriteResourceID, Cycles}\n" 1087 << "extern const llvm::MCReadAdvanceEntry " 1088 << Target << "ReadAdvanceTable[] = {\n" 1089 << " {0, 0, 0}, // Invalid\n"; 1090 for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size(); 1091 RAIdx != RAEnd; ++RAIdx) { 1092 MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx]; 1093 OS << " {" << RAEntry.UseIdx << ", " 1094 << format("%2d", RAEntry.WriteResourceID) << ", " 1095 << format("%2d", RAEntry.Cycles) << "}"; 1096 if (RAIdx + 1 < RAEnd) 1097 OS << ','; 1098 OS << " // #" << RAIdx << '\n'; 1099 } 1100 OS << "}; // " << Target << "ReadAdvanceTable\n"; 1101 1102 // Emit a SchedClass table for each processor. 1103 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(), 1104 PE = SchedModels.procModelEnd(); PI != PE; ++PI) { 1105 if (!PI->hasInstrSchedModel()) 1106 continue; 1107 1108 std::vector<MCSchedClassDesc> &SCTab = 1109 SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())]; 1110 1111 OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup," 1112 << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n"; 1113 OS << "static const llvm::MCSchedClassDesc " 1114 << PI->ModelName << "SchedClasses[] = {\n"; 1115 1116 // The first class is always invalid. We no way to distinguish it except by 1117 // name and position. 1118 assert(SchedModels.getSchedClass(0).Name == "NoInstrModel" 1119 && "invalid class not first"); 1120 OS << " {DBGFIELD(\"InvalidSchedClass\") " 1121 << MCSchedClassDesc::InvalidNumMicroOps 1122 << ", false, false, 0, 0, 0, 0, 0, 0},\n"; 1123 1124 for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) { 1125 MCSchedClassDesc &MCDesc = SCTab[SCIdx]; 1126 const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx); 1127 OS << " {DBGFIELD(\"" << SchedClass.Name << "\") "; 1128 if (SchedClass.Name.size() < 18) 1129 OS.indent(18 - SchedClass.Name.size()); 1130 OS << MCDesc.NumMicroOps 1131 << ", " << ( MCDesc.BeginGroup ? "true" : "false" ) 1132 << ", " << ( MCDesc.EndGroup ? "true" : "false" ) 1133 << ", " << format("%2d", MCDesc.WriteProcResIdx) 1134 << ", " << MCDesc.NumWriteProcResEntries 1135 << ", " << format("%2d", MCDesc.WriteLatencyIdx) 1136 << ", " << MCDesc.NumWriteLatencyEntries 1137 << ", " << format("%2d", MCDesc.ReadAdvanceIdx) 1138 << ", " << MCDesc.NumReadAdvanceEntries << "}"; 1139 if (SCIdx + 1 < SCEnd) 1140 OS << ','; 1141 OS << " // #" << SCIdx << '\n'; 1142 } 1143 OS << "}; // " << PI->ModelName << "SchedClasses\n"; 1144 } 1145 } 1146 1147 void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) { 1148 // For each processor model. 1149 for (const CodeGenProcModel &PM : SchedModels.procModels()) { 1150 // Emit processor resource table. 1151 if (PM.hasInstrSchedModel()) 1152 EmitProcessorResources(PM, OS); 1153 else if(!PM.ProcResourceDefs.empty()) 1154 PrintFatalError(PM.ModelDef->getLoc(), "SchedMachineModel defines " 1155 "ProcResources without defining WriteRes SchedWriteRes"); 1156 1157 // Begin processor itinerary properties 1158 OS << "\n"; 1159 OS << "static const llvm::MCSchedModel " << PM.ModelName << " = {\n"; 1160 EmitProcessorProp(OS, PM.ModelDef, "IssueWidth", ','); 1161 EmitProcessorProp(OS, PM.ModelDef, "MicroOpBufferSize", ','); 1162 EmitProcessorProp(OS, PM.ModelDef, "LoopMicroOpBufferSize", ','); 1163 EmitProcessorProp(OS, PM.ModelDef, "LoadLatency", ','); 1164 EmitProcessorProp(OS, PM.ModelDef, "HighLatency", ','); 1165 EmitProcessorProp(OS, PM.ModelDef, "MispredictPenalty", ','); 1166 1167 bool PostRAScheduler = 1168 (PM.ModelDef ? PM.ModelDef->getValueAsBit("PostRAScheduler") : false); 1169 1170 OS << " " << (PostRAScheduler ? "true" : "false") << ", // " 1171 << "PostRAScheduler\n"; 1172 1173 bool CompleteModel = 1174 (PM.ModelDef ? PM.ModelDef->getValueAsBit("CompleteModel") : false); 1175 1176 OS << " " << (CompleteModel ? "true" : "false") << ", // " 1177 << "CompleteModel\n"; 1178 1179 OS << " " << PM.Index << ", // Processor ID\n"; 1180 if (PM.hasInstrSchedModel()) 1181 OS << " " << PM.ModelName << "ProcResources" << ",\n" 1182 << " " << PM.ModelName << "SchedClasses" << ",\n" 1183 << " " << PM.ProcResourceDefs.size()+1 << ",\n" 1184 << " " << (SchedModels.schedClassEnd() 1185 - SchedModels.schedClassBegin()) << ",\n"; 1186 else 1187 OS << " nullptr, nullptr, 0, 0," 1188 << " // No instruction-level machine model.\n"; 1189 if (PM.hasItineraries()) 1190 OS << " " << PM.ItinsDef->getName() << "};\n"; 1191 else 1192 OS << " nullptr}; // No Itinerary\n"; 1193 } 1194 } 1195 1196 // 1197 // EmitProcessorLookup - generate cpu name to itinerary lookup table. 1198 // 1199 void SubtargetEmitter::EmitProcessorLookup(raw_ostream &OS) { 1200 // Gather and sort processor information 1201 std::vector<Record*> ProcessorList = 1202 Records.getAllDerivedDefinitions("Processor"); 1203 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName()); 1204 1205 // Begin processor table 1206 OS << "\n"; 1207 OS << "// Sorted (by key) array of itineraries for CPU subtype.\n" 1208 << "extern const llvm::SubtargetInfoKV " 1209 << Target << "ProcSchedKV[] = {\n"; 1210 1211 // For each processor 1212 for (unsigned i = 0, N = ProcessorList.size(); i < N;) { 1213 // Next processor 1214 Record *Processor = ProcessorList[i]; 1215 1216 StringRef Name = Processor->getValueAsString("Name"); 1217 const std::string &ProcModelName = 1218 SchedModels.getModelForProc(Processor).ModelName; 1219 1220 // Emit as { "cpu", procinit }, 1221 OS << " { \"" << Name << "\", (const void *)&" << ProcModelName << " }"; 1222 1223 // Depending on ''if more in the list'' emit comma 1224 if (++i < N) OS << ","; 1225 1226 OS << "\n"; 1227 } 1228 1229 // End processor table 1230 OS << "};\n"; 1231 } 1232 1233 // 1234 // EmitSchedModel - Emits all scheduling model tables, folding common patterns. 1235 // 1236 void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) { 1237 OS << "#ifdef DBGFIELD\n" 1238 << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n" 1239 << "#endif\n" 1240 << "#ifndef NDEBUG\n" 1241 << "#define DBGFIELD(x) x,\n" 1242 << "#else\n" 1243 << "#define DBGFIELD(x)\n" 1244 << "#endif\n"; 1245 1246 if (SchedModels.hasItineraries()) { 1247 std::vector<std::vector<InstrItinerary>> ProcItinLists; 1248 // Emit the stage data 1249 EmitStageAndOperandCycleData(OS, ProcItinLists); 1250 EmitItineraries(OS, ProcItinLists); 1251 } 1252 OS << "\n// ===============================================================\n" 1253 << "// Data tables for the new per-operand machine model.\n"; 1254 1255 SchedClassTables SchedTables; 1256 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) { 1257 GenSchedClassTables(ProcModel, SchedTables); 1258 } 1259 EmitSchedClassTables(SchedTables, OS); 1260 1261 // Emit the processor machine model 1262 EmitProcessorModels(OS); 1263 // Emit the processor lookup data 1264 EmitProcessorLookup(OS); 1265 1266 OS << "#undef DBGFIELD"; 1267 } 1268 1269 void SubtargetEmitter::EmitSchedModelHelpers(const std::string &ClassName, 1270 raw_ostream &OS) { 1271 OS << "unsigned " << ClassName 1272 << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI," 1273 << " const TargetSchedModel *SchedModel) const {\n"; 1274 1275 std::vector<Record*> Prologs = Records.getAllDerivedDefinitions("PredicateProlog"); 1276 std::sort(Prologs.begin(), Prologs.end(), LessRecord()); 1277 for (Record *P : Prologs) { 1278 OS << P->getValueAsString("Code") << '\n'; 1279 } 1280 IdxVec VariantClasses; 1281 for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) { 1282 if (SC.Transitions.empty()) 1283 continue; 1284 VariantClasses.push_back(SC.Index); 1285 } 1286 if (!VariantClasses.empty()) { 1287 OS << " switch (SchedClass) {\n"; 1288 for (unsigned VC : VariantClasses) { 1289 const CodeGenSchedClass &SC = SchedModels.getSchedClass(VC); 1290 OS << " case " << VC << ": // " << SC.Name << '\n'; 1291 IdxVec ProcIndices; 1292 for (const CodeGenSchedTransition &T : SC.Transitions) { 1293 IdxVec PI; 1294 std::set_union(T.ProcIndices.begin(), T.ProcIndices.end(), 1295 ProcIndices.begin(), ProcIndices.end(), 1296 std::back_inserter(PI)); 1297 ProcIndices.swap(PI); 1298 } 1299 for (unsigned PI : ProcIndices) { 1300 OS << " "; 1301 if (PI != 0) 1302 OS << "if (SchedModel->getProcessorID() == " << PI << ") "; 1303 OS << "{ // " << (SchedModels.procModelBegin() + PI)->ModelName 1304 << '\n'; 1305 for (const CodeGenSchedTransition &T : SC.Transitions) { 1306 if (PI != 0 && !std::count(T.ProcIndices.begin(), 1307 T.ProcIndices.end(), PI)) { 1308 continue; 1309 } 1310 OS << " if ("; 1311 for (RecIter RI = T.PredTerm.begin(), RE = T.PredTerm.end(); 1312 RI != RE; ++RI) { 1313 if (RI != T.PredTerm.begin()) 1314 OS << "\n && "; 1315 OS << "(" << (*RI)->getValueAsString("Predicate") << ")"; 1316 } 1317 OS << ")\n" 1318 << " return " << T.ToClassIdx << "; // " 1319 << SchedModels.getSchedClass(T.ToClassIdx).Name << '\n'; 1320 } 1321 OS << " }\n"; 1322 if (PI == 0) 1323 break; 1324 } 1325 if (SC.isInferred()) 1326 OS << " return " << SC.Index << ";\n"; 1327 OS << " break;\n"; 1328 } 1329 OS << " };\n"; 1330 } 1331 OS << " report_fatal_error(\"Expected a variant SchedClass\");\n" 1332 << "} // " << ClassName << "::resolveSchedClass\n"; 1333 } 1334 1335 void SubtargetEmitter::EmitHwModeCheck(const std::string &ClassName, 1336 raw_ostream &OS) { 1337 const CodeGenHwModes &CGH = TGT.getHwModes(); 1338 assert(CGH.getNumModeIds() > 0); 1339 if (CGH.getNumModeIds() == 1) 1340 return; 1341 1342 OS << "unsigned " << ClassName << "::getHwMode() const {\n"; 1343 for (unsigned M = 1, NumModes = CGH.getNumModeIds(); M != NumModes; ++M) { 1344 const HwMode &HM = CGH.getMode(M); 1345 OS << " if (checkFeatures(\"" << HM.Features 1346 << "\")) return " << M << ";\n"; 1347 } 1348 OS << " return 0;\n}\n"; 1349 } 1350 1351 // 1352 // ParseFeaturesFunction - Produces a subtarget specific function for parsing 1353 // the subtarget features string. 1354 // 1355 void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS, 1356 unsigned NumFeatures, 1357 unsigned NumProcs) { 1358 std::vector<Record*> Features = 1359 Records.getAllDerivedDefinitions("SubtargetFeature"); 1360 std::sort(Features.begin(), Features.end(), LessRecord()); 1361 1362 OS << "// ParseSubtargetFeatures - Parses features string setting specified\n" 1363 << "// subtarget options.\n" 1364 << "void llvm::"; 1365 OS << Target; 1366 OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef FS) {\n" 1367 << " DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n" 1368 << " DEBUG(dbgs() << \"\\nCPU:\" << CPU << \"\\n\\n\");\n"; 1369 1370 if (Features.empty()) { 1371 OS << "}\n"; 1372 return; 1373 } 1374 1375 OS << " InitMCProcessorInfo(CPU, FS);\n" 1376 << " const FeatureBitset& Bits = getFeatureBits();\n"; 1377 1378 for (Record *R : Features) { 1379 // Next record 1380 StringRef Instance = R->getName(); 1381 StringRef Value = R->getValueAsString("Value"); 1382 StringRef Attribute = R->getValueAsString("Attribute"); 1383 1384 if (Value=="true" || Value=="false") 1385 OS << " if (Bits[" << Target << "::" 1386 << Instance << "]) " 1387 << Attribute << " = " << Value << ";\n"; 1388 else 1389 OS << " if (Bits[" << Target << "::" 1390 << Instance << "] && " 1391 << Attribute << " < " << Value << ") " 1392 << Attribute << " = " << Value << ";\n"; 1393 } 1394 1395 OS << "}\n"; 1396 } 1397 1398 // 1399 // SubtargetEmitter::run - Main subtarget enumeration emitter. 1400 // 1401 void SubtargetEmitter::run(raw_ostream &OS) { 1402 emitSourceFileHeader("Subtarget Enumeration Source Fragment", OS); 1403 1404 OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n"; 1405 OS << "#undef GET_SUBTARGETINFO_ENUM\n\n"; 1406 1407 OS << "namespace llvm {\n"; 1408 Enumeration(OS); 1409 OS << "} // end namespace llvm\n\n"; 1410 OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n"; 1411 1412 OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n"; 1413 OS << "#undef GET_SUBTARGETINFO_MC_DESC\n\n"; 1414 1415 OS << "namespace llvm {\n"; 1416 #if 0 1417 OS << "namespace {\n"; 1418 #endif 1419 unsigned NumFeatures = FeatureKeyValues(OS); 1420 OS << "\n"; 1421 unsigned NumProcs = CPUKeyValues(OS); 1422 OS << "\n"; 1423 EmitSchedModel(OS); 1424 OS << "\n"; 1425 #if 0 1426 OS << "} // end anonymous namespace\n\n"; 1427 #endif 1428 1429 // MCInstrInfo initialization routine. 1430 OS << "static inline MCSubtargetInfo *create" << Target 1431 << "MCSubtargetInfoImpl(" 1432 << "const Triple &TT, StringRef CPU, StringRef FS) {\n"; 1433 OS << " return new MCSubtargetInfo(TT, CPU, FS, "; 1434 if (NumFeatures) 1435 OS << Target << "FeatureKV, "; 1436 else 1437 OS << "None, "; 1438 if (NumProcs) 1439 OS << Target << "SubTypeKV, "; 1440 else 1441 OS << "None, "; 1442 OS << '\n'; OS.indent(22); 1443 OS << Target << "ProcSchedKV, " 1444 << Target << "WriteProcResTable, " 1445 << Target << "WriteLatencyTable, " 1446 << Target << "ReadAdvanceTable, "; 1447 OS << '\n'; OS.indent(22); 1448 if (SchedModels.hasItineraries()) { 1449 OS << Target << "Stages, " 1450 << Target << "OperandCycles, " 1451 << Target << "ForwardingPaths"; 1452 } else 1453 OS << "nullptr, nullptr, nullptr"; 1454 OS << ");\n}\n\n"; 1455 1456 OS << "} // end namespace llvm\n\n"; 1457 1458 OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n"; 1459 1460 OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n"; 1461 OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n\n"; 1462 1463 OS << "#include \"llvm/Support/Debug.h\"\n"; 1464 OS << "#include \"llvm/Support/raw_ostream.h\"\n\n"; 1465 ParseFeaturesFunction(OS, NumFeatures, NumProcs); 1466 1467 OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n"; 1468 1469 // Create a TargetSubtargetInfo subclass to hide the MC layer initialization. 1470 OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n"; 1471 OS << "#undef GET_SUBTARGETINFO_HEADER\n\n"; 1472 1473 std::string ClassName = Target + "GenSubtargetInfo"; 1474 OS << "namespace llvm {\n"; 1475 OS << "class DFAPacketizer;\n"; 1476 OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n" 1477 << " explicit " << ClassName << "(const Triple &TT, StringRef CPU, " 1478 << "StringRef FS);\n" 1479 << "public:\n" 1480 << " unsigned resolveSchedClass(unsigned SchedClass, " 1481 << " const MachineInstr *DefMI," 1482 << " const TargetSchedModel *SchedModel) const override;\n" 1483 << " DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)" 1484 << " const;\n"; 1485 if (TGT.getHwModes().getNumModeIds() > 1) 1486 OS << " unsigned getHwMode() const override;\n"; 1487 OS << "};\n" 1488 << "} // end namespace llvm\n\n"; 1489 1490 OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n"; 1491 1492 OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n"; 1493 OS << "#undef GET_SUBTARGETINFO_CTOR\n\n"; 1494 1495 OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n\n"; 1496 OS << "namespace llvm {\n"; 1497 OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n"; 1498 OS << "extern const llvm::SubtargetFeatureKV " << Target << "SubTypeKV[];\n"; 1499 OS << "extern const llvm::SubtargetInfoKV " << Target << "ProcSchedKV[];\n"; 1500 OS << "extern const llvm::MCWriteProcResEntry " 1501 << Target << "WriteProcResTable[];\n"; 1502 OS << "extern const llvm::MCWriteLatencyEntry " 1503 << Target << "WriteLatencyTable[];\n"; 1504 OS << "extern const llvm::MCReadAdvanceEntry " 1505 << Target << "ReadAdvanceTable[];\n"; 1506 1507 if (SchedModels.hasItineraries()) { 1508 OS << "extern const llvm::InstrStage " << Target << "Stages[];\n"; 1509 OS << "extern const unsigned " << Target << "OperandCycles[];\n"; 1510 OS << "extern const unsigned " << Target << "ForwardingPaths[];\n"; 1511 } 1512 1513 OS << ClassName << "::" << ClassName << "(const Triple &TT, StringRef CPU, " 1514 << "StringRef FS)\n" 1515 << " : TargetSubtargetInfo(TT, CPU, FS, "; 1516 if (NumFeatures) 1517 OS << "makeArrayRef(" << Target << "FeatureKV, " << NumFeatures << "), "; 1518 else 1519 OS << "None, "; 1520 if (NumProcs) 1521 OS << "makeArrayRef(" << Target << "SubTypeKV, " << NumProcs << "), "; 1522 else 1523 OS << "None, "; 1524 OS << '\n'; OS.indent(24); 1525 OS << Target << "ProcSchedKV, " 1526 << Target << "WriteProcResTable, " 1527 << Target << "WriteLatencyTable, " 1528 << Target << "ReadAdvanceTable, "; 1529 OS << '\n'; OS.indent(24); 1530 if (SchedModels.hasItineraries()) { 1531 OS << Target << "Stages, " 1532 << Target << "OperandCycles, " 1533 << Target << "ForwardingPaths"; 1534 } else 1535 OS << "nullptr, nullptr, nullptr"; 1536 OS << ") {}\n\n"; 1537 1538 EmitSchedModelHelpers(ClassName, OS); 1539 EmitHwModeCheck(ClassName, OS); 1540 1541 OS << "} // end namespace llvm\n\n"; 1542 1543 OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n"; 1544 } 1545 1546 namespace llvm { 1547 1548 void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) { 1549 CodeGenTarget CGTarget(RK); 1550 SubtargetEmitter(RK, CGTarget).run(OS); 1551 } 1552 1553 } // end namespace llvm 1554