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