1 //===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits subtarget enumerations.
12 //===----------------------------------------------------------------------===//
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"
39 #define DEBUG_TYPE "subtarget-emitter"
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;
54 // Reserve an invalid entry at index 0
56 ProcSchedClasses.resize(1);
57 WriteProcResources.resize(1);
58 WriteLatencies.resize(1);
59 WriterNames.push_back("InvalidWrite");
60 ReadAdvanceEntries.resize(1);
64 struct LessWriteProcResources {
65 bool operator()(const MCWriteProcResEntry &LHS,
66 const MCWriteProcResEntry &RHS) {
67 return LHS.ProcResourceIdx < RHS.ProcResourceIdx;
71 RecordKeeper &Records;
72 CodeGenSchedModels &SchedModels;
75 void Enumeration(raw_ostream &OS);
76 unsigned FeatureKeyValues(raw_ostream &OS);
77 unsigned CPUKeyValues(raw_ostream &OS);
78 void FormItineraryStageString(const std::string &Names,
79 Record *ItinData, std::string &ItinString,
81 void FormItineraryOperandCycleString(Record *ItinData, std::string &ItinString,
82 unsigned &NOperandCycles);
83 void FormItineraryBypassString(const std::string &Names,
85 std::string &ItinString, unsigned NOperandCycles);
86 void EmitStageAndOperandCycleData(raw_ostream &OS,
87 std::vector<std::vector<InstrItinerary>>
89 void EmitItineraries(raw_ostream &OS,
90 std::vector<std::vector<InstrItinerary>>
92 void EmitProcessorProp(raw_ostream &OS, const Record *R, StringRef Name,
94 void EmitProcessorResources(const CodeGenProcModel &ProcModel,
96 Record *FindWriteResources(const CodeGenSchedRW &SchedWrite,
97 const CodeGenProcModel &ProcModel);
98 Record *FindReadAdvance(const CodeGenSchedRW &SchedRead,
99 const CodeGenProcModel &ProcModel);
100 void ExpandProcResources(RecVec &PRVec, std::vector<int64_t> &Cycles,
101 const CodeGenProcModel &ProcModel);
102 void GenSchedClassTables(const CodeGenProcModel &ProcModel,
103 SchedClassTables &SchedTables);
104 void EmitSchedClassTables(SchedClassTables &SchedTables, raw_ostream &OS);
105 void EmitProcessorModels(raw_ostream &OS);
106 void EmitProcessorLookup(raw_ostream &OS);
107 void EmitSchedModelHelpers(const std::string &ClassName, raw_ostream &OS);
108 void EmitSchedModel(raw_ostream &OS);
109 void ParseFeaturesFunction(raw_ostream &OS, unsigned NumFeatures,
113 SubtargetEmitter(RecordKeeper &R, CodeGenTarget &TGT):
114 Records(R), SchedModels(TGT.getSchedModels()), Target(TGT.getName()) {}
116 void run(raw_ostream &o);
119 } // end anonymous namespace
122 // Enumeration - Emit the specified class as an enumeration.
124 void SubtargetEmitter::Enumeration(raw_ostream &OS) {
125 // Get all records of class and sort
126 std::vector<Record*> DefList =
127 Records.getAllDerivedDefinitions("SubtargetFeature");
128 std::sort(DefList.begin(), DefList.end(), LessRecord());
130 unsigned N = DefList.size();
133 if (N > MAX_SUBTARGET_FEATURES)
134 PrintFatalError("Too many subtarget features! Bump MAX_SUBTARGET_FEATURES.");
136 OS << "namespace " << Target << " {\n";
142 for (unsigned i = 0; i < N;) {
144 Record *Def = DefList[i];
147 OS << " " << Def->getName() << " = " << i;
148 if (++i < N) OS << ",";
153 // Close enumeration and namespace
155 OS << "} // end namespace " << Target << "\n";
159 // FeatureKeyValues - Emit data of all the subtarget features. Used by the
162 unsigned SubtargetEmitter::FeatureKeyValues(raw_ostream &OS) {
163 // Gather and sort all the features
164 std::vector<Record*> FeatureList =
165 Records.getAllDerivedDefinitions("SubtargetFeature");
167 if (FeatureList.empty())
170 std::sort(FeatureList.begin(), FeatureList.end(), LessRecordFieldName());
172 // Begin feature table
173 OS << "// Sorted (by key) array of values for CPU features.\n"
174 << "extern const llvm::SubtargetFeatureKV " << Target
175 << "FeatureKV[] = {\n";
178 unsigned NumFeatures = 0;
179 for (unsigned i = 0, N = FeatureList.size(); i < N; ++i) {
181 Record *Feature = FeatureList[i];
183 const std::string &Name = Feature->getName();
184 const std::string &CommandLineName = Feature->getValueAsString("Name");
185 const std::string &Desc = Feature->getValueAsString("Desc");
187 if (CommandLineName.empty()) continue;
189 // Emit as { "feature", "description", { featureEnum }, { i1 , i2 , ... , in } }
191 << "\"" << CommandLineName << "\", "
192 << "\"" << Desc << "\", "
193 << "{ " << Target << "::" << Name << " }, ";
195 const std::vector<Record*> &ImpliesList =
196 Feature->getValueAsListOfDefs("Implies");
199 for (unsigned j = 0, M = ImpliesList.size(); j < M;) {
200 OS << " " << Target << "::" << ImpliesList[j]->getName();
201 if (++j < M) OS << ",";
208 // Depending on 'if more in the list' emit comma
209 if ((i + 1) < N) OS << ",";
221 // CPUKeyValues - Emit data of all the subtarget processors. Used by command
224 unsigned SubtargetEmitter::CPUKeyValues(raw_ostream &OS) {
225 // Gather and sort processor information
226 std::vector<Record*> ProcessorList =
227 Records.getAllDerivedDefinitions("Processor");
228 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
230 // Begin processor table
231 OS << "// Sorted (by key) array of values for CPU subtype.\n"
232 << "extern const llvm::SubtargetFeatureKV " << Target
233 << "SubTypeKV[] = {\n";
235 // For each processor
236 for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
238 Record *Processor = ProcessorList[i];
240 const std::string &Name = Processor->getValueAsString("Name");
241 const std::vector<Record*> &FeatureList =
242 Processor->getValueAsListOfDefs("Features");
244 // Emit as { "cpu", "description", { f1 , f2 , ... fn } },
246 << "\"" << Name << "\", "
247 << "\"Select the " << Name << " processor\", ";
250 for (unsigned j = 0, M = FeatureList.size(); j < M;) {
251 OS << " " << Target << "::" << FeatureList[j]->getName();
252 if (++j < M) OS << ",";
256 // The { } is for the "implies" section of this data structure.
259 // Depending on 'if more in the list' emit comma
260 if (++i < N) OS << ",";
265 // End processor table
268 return ProcessorList.size();
272 // FormItineraryStageString - Compose a string containing the stage
273 // data initialization for the specified itinerary. N is the number
276 void SubtargetEmitter::FormItineraryStageString(const std::string &Name,
278 std::string &ItinString,
281 const std::vector<Record*> &StageList =
282 ItinData->getValueAsListOfDefs("Stages");
285 unsigned N = NStages = StageList.size();
286 for (unsigned i = 0; i < N;) {
288 const Record *Stage = StageList[i];
290 // Form string as ,{ cycles, u1 | u2 | ... | un, timeinc, kind }
291 int Cycles = Stage->getValueAsInt("Cycles");
292 ItinString += " { " + itostr(Cycles) + ", ";
295 const std::vector<Record*> &UnitList = Stage->getValueAsListOfDefs("Units");
298 for (unsigned j = 0, M = UnitList.size(); j < M;) {
299 // Add name and bitwise or
300 ItinString += Name + "FU::" + UnitList[j]->getName().str();
301 if (++j < M) ItinString += " | ";
304 int TimeInc = Stage->getValueAsInt("TimeInc");
305 ItinString += ", " + itostr(TimeInc);
307 int Kind = Stage->getValueAsInt("Kind");
308 ItinString += ", (llvm::InstrStage::ReservationKinds)" + itostr(Kind);
312 if (++i < N) ItinString += ", ";
317 // FormItineraryOperandCycleString - Compose a string containing the
318 // operand cycle initialization for the specified itinerary. N is the
319 // number of operands that has cycles specified.
321 void SubtargetEmitter::FormItineraryOperandCycleString(Record *ItinData,
322 std::string &ItinString, unsigned &NOperandCycles) {
323 // Get operand cycle list
324 const std::vector<int64_t> &OperandCycleList =
325 ItinData->getValueAsListOfInts("OperandCycles");
327 // For each operand cycle
328 unsigned N = NOperandCycles = OperandCycleList.size();
329 for (unsigned i = 0; i < N;) {
330 // Next operand cycle
331 const int OCycle = OperandCycleList[i];
333 ItinString += " " + itostr(OCycle);
334 if (++i < N) ItinString += ", ";
338 void SubtargetEmitter::FormItineraryBypassString(const std::string &Name,
340 std::string &ItinString,
341 unsigned NOperandCycles) {
342 const std::vector<Record*> &BypassList =
343 ItinData->getValueAsListOfDefs("Bypasses");
344 unsigned N = BypassList.size();
347 ItinString += Name + "Bypass::" + BypassList[i]->getName().str();
348 if (++i < NOperandCycles) ItinString += ", ";
350 for (; i < NOperandCycles;) {
352 if (++i < NOperandCycles) ItinString += ", ";
357 // EmitStageAndOperandCycleData - Generate unique itinerary stages and operand
358 // cycle tables. Create a list of InstrItinerary objects (ProcItinLists) indexed
359 // by CodeGenSchedClass::Index.
361 void SubtargetEmitter::
362 EmitStageAndOperandCycleData(raw_ostream &OS,
363 std::vector<std::vector<InstrItinerary>>
365 // Multiple processor models may share an itinerary record. Emit it once.
366 SmallPtrSet<Record*, 8> ItinsDefSet;
368 // Emit functional units for all the itineraries.
369 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
371 if (!ItinsDefSet.insert(ProcModel.ItinsDef).second)
374 std::vector<Record*> FUs = ProcModel.ItinsDef->getValueAsListOfDefs("FU");
378 const std::string &Name = ProcModel.ItinsDef->getName();
379 OS << "\n// Functional units for \"" << Name << "\"\n"
380 << "namespace " << Name << "FU {\n";
382 for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j)
383 OS << " const unsigned " << FUs[j]->getName()
384 << " = 1 << " << j << ";\n";
386 OS << "} // end namespace " << Name << "FU\n";
388 std::vector<Record*> BPs = ProcModel.ItinsDef->getValueAsListOfDefs("BP");
390 OS << "\n// Pipeline forwarding pathes for itineraries \"" << Name
391 << "\"\n" << "namespace " << Name << "Bypass {\n";
393 OS << " const unsigned NoBypass = 0;\n";
394 for (unsigned j = 0, BPN = BPs.size(); j < BPN; ++j)
395 OS << " const unsigned " << BPs[j]->getName()
396 << " = 1 << " << j << ";\n";
398 OS << "} // end namespace " << Name << "Bypass\n";
402 // Begin stages table
403 std::string StageTable = "\nextern const llvm::InstrStage " + Target +
405 StageTable += " { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n";
407 // Begin operand cycle table
408 std::string OperandCycleTable = "extern const unsigned " + Target +
409 "OperandCycles[] = {\n";
410 OperandCycleTable += " 0, // No itinerary\n";
412 // Begin pipeline bypass table
413 std::string BypassTable = "extern const unsigned " + Target +
414 "ForwardingPaths[] = {\n";
415 BypassTable += " 0, // No itinerary\n";
417 // For each Itinerary across all processors, add a unique entry to the stages,
418 // operand cycles, and pipepine bypess tables. Then add the new Itinerary
419 // object with computed offsets to the ProcItinLists result.
420 unsigned StageCount = 1, OperandCycleCount = 1;
421 std::map<std::string, unsigned> ItinStageMap, ItinOperandMap;
422 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
423 // Add process itinerary to the list.
424 ProcItinLists.resize(ProcItinLists.size()+1);
426 // If this processor defines no itineraries, then leave the itinerary list
428 std::vector<InstrItinerary> &ItinList = ProcItinLists.back();
429 if (!ProcModel.hasItineraries())
432 const std::string &Name = ProcModel.ItinsDef->getName();
434 ItinList.resize(SchedModels.numInstrSchedClasses());
435 assert(ProcModel.ItinDefList.size() == ItinList.size() && "bad Itins");
437 for (unsigned SchedClassIdx = 0, SchedClassEnd = ItinList.size();
438 SchedClassIdx < SchedClassEnd; ++SchedClassIdx) {
440 // Next itinerary data
441 Record *ItinData = ProcModel.ItinDefList[SchedClassIdx];
443 // Get string and stage count
444 std::string ItinStageString;
445 unsigned NStages = 0;
447 FormItineraryStageString(Name, ItinData, ItinStageString, NStages);
449 // Get string and operand cycle count
450 std::string ItinOperandCycleString;
451 unsigned NOperandCycles = 0;
452 std::string ItinBypassString;
454 FormItineraryOperandCycleString(ItinData, ItinOperandCycleString,
457 FormItineraryBypassString(Name, ItinData, ItinBypassString,
461 // Check to see if stage already exists and create if it doesn't
462 unsigned FindStage = 0;
464 FindStage = ItinStageMap[ItinStageString];
465 if (FindStage == 0) {
466 // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // indices
467 StageTable += ItinStageString + ", // " + itostr(StageCount);
469 StageTable += "-" + itostr(StageCount + NStages - 1);
471 // Record Itin class number.
472 ItinStageMap[ItinStageString] = FindStage = StageCount;
473 StageCount += NStages;
477 // Check to see if operand cycle already exists and create if it doesn't
478 unsigned FindOperandCycle = 0;
479 if (NOperandCycles > 0) {
480 std::string ItinOperandString = ItinOperandCycleString+ItinBypassString;
481 FindOperandCycle = ItinOperandMap[ItinOperandString];
482 if (FindOperandCycle == 0) {
483 // Emit as cycle, // index
484 OperandCycleTable += ItinOperandCycleString + ", // ";
485 std::string OperandIdxComment = itostr(OperandCycleCount);
486 if (NOperandCycles > 1)
487 OperandIdxComment += "-"
488 + itostr(OperandCycleCount + NOperandCycles - 1);
489 OperandCycleTable += OperandIdxComment + "\n";
490 // Record Itin class number.
491 ItinOperandMap[ItinOperandCycleString] =
492 FindOperandCycle = OperandCycleCount;
493 // Emit as bypass, // index
494 BypassTable += ItinBypassString + ", // " + OperandIdxComment + "\n";
495 OperandCycleCount += NOperandCycles;
499 // Set up itinerary as location and location + stage count
500 int NumUOps = ItinData ? ItinData->getValueAsInt("NumMicroOps") : 0;
501 InstrItinerary Intinerary = { NumUOps, FindStage, FindStage + NStages,
503 FindOperandCycle + NOperandCycles };
505 // Inject - empty slots will be 0, 0
506 ItinList[SchedClassIdx] = Intinerary;
511 StageTable += " { 0, 0, 0, llvm::InstrStage::Required } // End stages\n";
512 StageTable += "};\n";
514 // Closing operand cycles
515 OperandCycleTable += " 0 // End operand cycles\n";
516 OperandCycleTable += "};\n";
518 BypassTable += " 0 // End bypass tables\n";
519 BypassTable += "};\n";
523 OS << OperandCycleTable;
528 // EmitProcessorData - Generate data for processor itineraries that were
529 // computed during EmitStageAndOperandCycleData(). ProcItinLists lists all
530 // Itineraries for each processor. The Itinerary lists are indexed on
531 // CodeGenSchedClass::Index.
533 void SubtargetEmitter::
534 EmitItineraries(raw_ostream &OS,
535 std::vector<std::vector<InstrItinerary>> &ProcItinLists) {
536 // Multiple processor models may share an itinerary record. Emit it once.
537 SmallPtrSet<Record*, 8> ItinsDefSet;
539 // For each processor's machine model
540 std::vector<std::vector<InstrItinerary>>::iterator
541 ProcItinListsIter = ProcItinLists.begin();
542 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
543 PE = SchedModels.procModelEnd(); PI != PE; ++PI, ++ProcItinListsIter) {
545 Record *ItinsDef = PI->ItinsDef;
546 if (!ItinsDefSet.insert(ItinsDef).second)
549 // Get processor itinerary name
550 const std::string &Name = ItinsDef->getName();
552 // Get the itinerary list for the processor.
553 assert(ProcItinListsIter != ProcItinLists.end() && "bad iterator");
554 std::vector<InstrItinerary> &ItinList = *ProcItinListsIter;
556 // Empty itineraries aren't referenced anywhere in the tablegen output
557 // so don't emit them.
558 if (ItinList.empty())
562 OS << "static const llvm::InstrItinerary ";
564 // Begin processor itinerary table
565 OS << Name << "[] = {\n";
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];
571 // Emit Itinerary in the form of
572 // { firstStage, lastStage, firstCycle, lastCycle } // index
574 Intinerary.NumMicroOps << ", " <<
575 Intinerary.FirstStage << ", " <<
576 Intinerary.LastStage << ", " <<
577 Intinerary.FirstOperandCycle << ", " <<
578 Intinerary.LastOperandCycle << " }" <<
579 ", // " << j << " " << SchedModels.getSchedClass(j).Name << "\n";
581 // End processor itinerary table
582 OS << " { 0, ~0U, ~0U, ~0U, ~0U } // end marker\n";
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
590 void SubtargetEmitter::EmitProcessorProp(raw_ostream &OS, const Record *R,
591 StringRef Name, char Separator) {
593 int V = R ? R->getValueAsInt(Name) : -1;
595 OS << V << Separator << " // " << Name;
597 OS << "MCSchedModel::Default" << Name << Separator;
601 void SubtargetEmitter::EmitProcessorResources(const CodeGenProcModel &ProcModel,
603 char Sep = ProcModel.ProcResourceDefs.empty() ? ' ' : ',';
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";
610 for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) {
611 Record *PRDef = ProcModel.ProcResourceDefs[i];
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");
625 if (PRDef->getValueInit("Super")->isComplete()) {
626 SuperDef = SchedModels.findProcResUnits(
627 PRDef->getValueAsDef("Super"), ProcModel);
628 SuperIdx = ProcModel.getProcResourceIdx(SuperDef);
630 NumUnits = PRDef->getValueAsInt("NumUnits");
632 // Emit the ProcResourceDesc
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;
641 OS << ", Super=" << SuperDef->getName();
647 // Find the WriteRes Record that defines processor resources for this
649 Record *SubtargetEmitter::FindWriteResources(
650 const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) {
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;
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)
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;
672 if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes"))
675 // Check this processor's list of write resources.
676 Record *ResDef = nullptr;
677 for (Record *WR : ProcModel.WriteResDefs) {
678 if (!WR->isSubClassOf("WriteRes"))
680 if (AliasDef == WR->getValueAsDef("WriteType")
681 || SchedWrite.TheDef == WR->getValueAsDef("WriteType")) {
683 PrintFatalError(WR->getLoc(), "Resources are defined for both "
684 "SchedWrite and its alias on processor " +
685 ProcModel.ModelName);
690 // TODO: If ProcModel has a base model (previous generation processor),
691 // then call FindWriteResources recursively with that model here.
693 PrintFatalError(ProcModel.ModelDef->getLoc(),
694 std::string("Processor does not define resources for ")
695 + SchedWrite.TheDef->getName());
700 /// Find the ReadAdvance record for the given SchedRead on this processor or
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;
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)
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;
724 if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance"))
727 // Check this processor's ReadAdvanceList.
728 Record *ResDef = nullptr;
729 for (Record *RA : ProcModel.ReadAdvanceDefs) {
730 if (!RA->isSubClassOf("ReadAdvance"))
732 if (AliasDef == RA->getValueAsDef("ReadType")
733 || SchedRead.TheDef == RA->getValueAsDef("ReadType")) {
735 PrintFatalError(RA->getLoc(), "Resources are defined for both "
736 "SchedRead and its alias on processor " +
737 ProcModel.ModelName);
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());
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];
762 if (PRDef->isSubClassOf("ProcResGroup"))
763 SubResources = PRDef->getValueAsListOfDefs("Resources");
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.");
775 SchedModels.findProcResUnits(SubDef->getValueAsDef("Super"), PM);
776 PRVec.push_back(SuperDef);
777 Cycles.push_back(Cycles[i]);
781 for (Record *PR : PM.ProcResourceDefs) {
782 if (PR == PRDef || !PR->isSubClassOf("ProcResGroup"))
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)) {
793 Cycles.push_back(Cycles[i]);
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())
807 std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back();
808 for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) {
809 DEBUG(SC.dump(&SchedModels));
811 SCTab.resize(SCTab.size() + 1);
812 MCSchedClassDesc &SCDesc = SCTab.back();
813 // SCDesc.Name is guarded by NDEBUG
814 SCDesc.NumMicroOps = 0;
815 SCDesc.BeginGroup = false;
816 SCDesc.EndGroup = false;
817 SCDesc.WriteProcResIdx = 0;
818 SCDesc.WriteLatencyIdx = 0;
819 SCDesc.ReadAdvanceIdx = 0;
821 // A Variant SchedClass has no resources of its own.
822 bool HasVariants = false;
823 for (std::vector<CodeGenSchedTransition>::const_iterator
824 TI = SC.Transitions.begin(), TE = SC.Transitions.end();
826 if (TI->ProcIndices[0] == 0) {
830 if (is_contained(TI->ProcIndices, ProcModel.Index)) {
836 SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps;
840 // Determine if the SchedClass is actually reachable on this processor. If
841 // not don't try to locate the processor resources, it will fail.
842 // If ProcIndices contains 0, this class applies to all processors.
843 assert(!SC.ProcIndices.empty() && "expect at least one procidx");
844 if (SC.ProcIndices[0] != 0) {
845 if (!is_contained(SC.ProcIndices, ProcModel.Index))
848 IdxVec Writes = SC.Writes;
849 IdxVec Reads = SC.Reads;
850 if (!SC.InstRWs.empty()) {
851 // This class has a default ReadWrite list which can be overriden by
852 // InstRW definitions.
853 Record *RWDef = nullptr;
854 for (Record *RW : SC.InstRWs) {
855 Record *RWModelDef = RW->getValueAsDef("SchedModel");
856 if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) {
864 SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
868 if (Writes.empty()) {
869 // Check this processor's itinerary class resources.
870 for (Record *I : ProcModel.ItinRWDefs) {
871 RecVec Matched = I->getValueAsListOfDefs("MatchedItinClasses");
872 if (is_contained(Matched, SC.ItinClassDef)) {
873 SchedModels.findRWs(I->getValueAsListOfDefs("OperandReadWrites"),
878 if (Writes.empty()) {
879 DEBUG(dbgs() << ProcModel.ModelName
880 << " does not have resources for class " << SC.Name << '\n');
883 // Sum resources across all operand writes.
884 std::vector<MCWriteProcResEntry> WriteProcResources;
885 std::vector<MCWriteLatencyEntry> WriteLatencies;
886 std::vector<std::string> WriterNames;
887 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries;
888 for (unsigned W : Writes) {
890 SchedModels.expandRWSeqForProc(W, WriteSeq, /*IsRead=*/false,
893 // For each operand, create a latency entry.
894 MCWriteLatencyEntry WLEntry;
896 unsigned WriteID = WriteSeq.back();
897 WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name);
898 // If this Write is not referenced by a ReadAdvance, don't distinguish it
899 // from other WriteLatency entries.
900 if (!SchedModels.hasReadOfWrite(
901 SchedModels.getSchedWrite(WriteID).TheDef)) {
904 WLEntry.WriteResourceID = WriteID;
906 for (unsigned WS : WriteSeq) {
909 FindWriteResources(SchedModels.getSchedWrite(WS), ProcModel);
911 // Mark the parent class as invalid for unsupported write types.
912 if (WriteRes->getValueAsBit("Unsupported")) {
913 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
916 WLEntry.Cycles += WriteRes->getValueAsInt("Latency");
917 SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps");
918 SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup");
919 SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup");
921 // Create an entry for each ProcResource listed in WriteRes.
922 RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources");
923 std::vector<int64_t> Cycles =
924 WriteRes->getValueAsListOfInts("ResourceCycles");
926 ExpandProcResources(PRVec, Cycles, ProcModel);
928 for (unsigned PRIdx = 0, PREnd = PRVec.size();
929 PRIdx != PREnd; ++PRIdx) {
930 MCWriteProcResEntry WPREntry;
931 WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]);
932 assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx");
933 WPREntry.Cycles = Cycles[PRIdx];
934 // If this resource is already used in this sequence, add the current
935 // entry's cycles so that the same resource appears to be used
936 // serially, rather than multiple parallel uses. This is important for
937 // in-order machine where the resource consumption is a hazard.
938 unsigned WPRIdx = 0, WPREnd = WriteProcResources.size();
939 for( ; WPRIdx != WPREnd; ++WPRIdx) {
940 if (WriteProcResources[WPRIdx].ProcResourceIdx
941 == WPREntry.ProcResourceIdx) {
942 WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles;
946 if (WPRIdx == WPREnd)
947 WriteProcResources.push_back(WPREntry);
950 WriteLatencies.push_back(WLEntry);
952 // Create an entry for each operand Read in this SchedClass.
953 // Entries must be sorted first by UseIdx then by WriteResourceID.
954 for (unsigned UseIdx = 0, EndIdx = Reads.size();
955 UseIdx != EndIdx; ++UseIdx) {
956 Record *ReadAdvance =
957 FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel);
961 // Mark the parent class as invalid for unsupported write types.
962 if (ReadAdvance->getValueAsBit("Unsupported")) {
963 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
966 RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites");
968 if (ValidWrites.empty())
969 WriteIDs.push_back(0);
971 for (Record *VW : ValidWrites) {
972 WriteIDs.push_back(SchedModels.getSchedRWIdx(VW, /*IsRead=*/false));
975 std::sort(WriteIDs.begin(), WriteIDs.end());
976 for(unsigned W : WriteIDs) {
977 MCReadAdvanceEntry RAEntry;
978 RAEntry.UseIdx = UseIdx;
979 RAEntry.WriteResourceID = W;
980 RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles");
981 ReadAdvanceEntries.push_back(RAEntry);
984 if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) {
985 WriteProcResources.clear();
986 WriteLatencies.clear();
987 ReadAdvanceEntries.clear();
989 // Add the information for this SchedClass to the global tables using basic
992 // WritePrecRes entries are sorted by ProcResIdx.
993 std::sort(WriteProcResources.begin(), WriteProcResources.end(),
994 LessWriteProcResources());
996 SCDesc.NumWriteProcResEntries = WriteProcResources.size();
997 std::vector<MCWriteProcResEntry>::iterator WPRPos =
998 std::search(SchedTables.WriteProcResources.begin(),
999 SchedTables.WriteProcResources.end(),
1000 WriteProcResources.begin(), WriteProcResources.end());
1001 if (WPRPos != SchedTables.WriteProcResources.end())
1002 SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin();
1004 SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size();
1005 SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(),
1006 WriteProcResources.end());
1008 // Latency entries must remain in operand order.
1009 SCDesc.NumWriteLatencyEntries = WriteLatencies.size();
1010 std::vector<MCWriteLatencyEntry>::iterator WLPos =
1011 std::search(SchedTables.WriteLatencies.begin(),
1012 SchedTables.WriteLatencies.end(),
1013 WriteLatencies.begin(), WriteLatencies.end());
1014 if (WLPos != SchedTables.WriteLatencies.end()) {
1015 unsigned idx = WLPos - SchedTables.WriteLatencies.begin();
1016 SCDesc.WriteLatencyIdx = idx;
1017 for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i)
1018 if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) ==
1019 std::string::npos) {
1020 SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i];
1024 SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size();
1025 SchedTables.WriteLatencies.insert(SchedTables.WriteLatencies.end(),
1026 WriteLatencies.begin(),
1027 WriteLatencies.end());
1028 SchedTables.WriterNames.insert(SchedTables.WriterNames.end(),
1029 WriterNames.begin(), WriterNames.end());
1031 // ReadAdvanceEntries must remain in operand order.
1032 SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size();
1033 std::vector<MCReadAdvanceEntry>::iterator RAPos =
1034 std::search(SchedTables.ReadAdvanceEntries.begin(),
1035 SchedTables.ReadAdvanceEntries.end(),
1036 ReadAdvanceEntries.begin(), ReadAdvanceEntries.end());
1037 if (RAPos != SchedTables.ReadAdvanceEntries.end())
1038 SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin();
1040 SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size();
1041 SchedTables.ReadAdvanceEntries.insert(RAPos, ReadAdvanceEntries.begin(),
1042 ReadAdvanceEntries.end());
1047 // Emit SchedClass tables for all processors and associated global tables.
1048 void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables,
1050 // Emit global WriteProcResTable.
1051 OS << "\n// {ProcResourceIdx, Cycles}\n"
1052 << "extern const llvm::MCWriteProcResEntry "
1053 << Target << "WriteProcResTable[] = {\n"
1054 << " { 0, 0}, // Invalid\n";
1055 for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size();
1056 WPRIdx != WPREnd; ++WPRIdx) {
1057 MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx];
1058 OS << " {" << format("%2d", WPREntry.ProcResourceIdx) << ", "
1059 << format("%2d", WPREntry.Cycles) << "}";
1060 if (WPRIdx + 1 < WPREnd)
1062 OS << " // #" << WPRIdx << '\n';
1064 OS << "}; // " << Target << "WriteProcResTable\n";
1066 // Emit global WriteLatencyTable.
1067 OS << "\n// {Cycles, WriteResourceID}\n"
1068 << "extern const llvm::MCWriteLatencyEntry "
1069 << Target << "WriteLatencyTable[] = {\n"
1070 << " { 0, 0}, // Invalid\n";
1071 for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size();
1072 WLIdx != WLEnd; ++WLIdx) {
1073 MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx];
1074 OS << " {" << format("%2d", WLEntry.Cycles) << ", "
1075 << format("%2d", WLEntry.WriteResourceID) << "}";
1076 if (WLIdx + 1 < WLEnd)
1078 OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n';
1080 OS << "}; // " << Target << "WriteLatencyTable\n";
1082 // Emit global ReadAdvanceTable.
1083 OS << "\n// {UseIdx, WriteResourceID, Cycles}\n"
1084 << "extern const llvm::MCReadAdvanceEntry "
1085 << Target << "ReadAdvanceTable[] = {\n"
1086 << " {0, 0, 0}, // Invalid\n";
1087 for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size();
1088 RAIdx != RAEnd; ++RAIdx) {
1089 MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx];
1090 OS << " {" << RAEntry.UseIdx << ", "
1091 << format("%2d", RAEntry.WriteResourceID) << ", "
1092 << format("%2d", RAEntry.Cycles) << "}";
1093 if (RAIdx + 1 < RAEnd)
1095 OS << " // #" << RAIdx << '\n';
1097 OS << "}; // " << Target << "ReadAdvanceTable\n";
1099 // Emit a SchedClass table for each processor.
1100 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
1101 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
1102 if (!PI->hasInstrSchedModel())
1105 std::vector<MCSchedClassDesc> &SCTab =
1106 SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())];
1108 OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup,"
1109 << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n";
1110 OS << "static const llvm::MCSchedClassDesc "
1111 << PI->ModelName << "SchedClasses[] = {\n";
1113 // The first class is always invalid. We no way to distinguish it except by
1114 // name and position.
1115 assert(SchedModels.getSchedClass(0).Name == "NoInstrModel"
1116 && "invalid class not first");
1117 OS << " {DBGFIELD(\"InvalidSchedClass\") "
1118 << MCSchedClassDesc::InvalidNumMicroOps
1119 << ", false, false, 0, 0, 0, 0, 0, 0},\n";
1121 for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) {
1122 MCSchedClassDesc &MCDesc = SCTab[SCIdx];
1123 const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx);
1124 OS << " {DBGFIELD(\"" << SchedClass.Name << "\") ";
1125 if (SchedClass.Name.size() < 18)
1126 OS.indent(18 - SchedClass.Name.size());
1127 OS << MCDesc.NumMicroOps
1128 << ", " << ( MCDesc.BeginGroup ? "true" : "false" )
1129 << ", " << ( MCDesc.EndGroup ? "true" : "false" )
1130 << ", " << format("%2d", MCDesc.WriteProcResIdx)
1131 << ", " << MCDesc.NumWriteProcResEntries
1132 << ", " << format("%2d", MCDesc.WriteLatencyIdx)
1133 << ", " << MCDesc.NumWriteLatencyEntries
1134 << ", " << format("%2d", MCDesc.ReadAdvanceIdx)
1135 << ", " << MCDesc.NumReadAdvanceEntries << "}";
1136 if (SCIdx + 1 < SCEnd)
1138 OS << " // #" << SCIdx << '\n';
1140 OS << "}; // " << PI->ModelName << "SchedClasses\n";
1144 void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) {
1145 // For each processor model.
1146 for (const CodeGenProcModel &PM : SchedModels.procModels()) {
1147 // Emit processor resource table.
1148 if (PM.hasInstrSchedModel())
1149 EmitProcessorResources(PM, OS);
1150 else if(!PM.ProcResourceDefs.empty())
1151 PrintFatalError(PM.ModelDef->getLoc(), "SchedMachineModel defines "
1152 "ProcResources without defining WriteRes SchedWriteRes");
1154 // Begin processor itinerary properties
1156 OS << "static const llvm::MCSchedModel " << PM.ModelName << " = {\n";
1157 EmitProcessorProp(OS, PM.ModelDef, "IssueWidth", ',');
1158 EmitProcessorProp(OS, PM.ModelDef, "MicroOpBufferSize", ',');
1159 EmitProcessorProp(OS, PM.ModelDef, "LoopMicroOpBufferSize", ',');
1160 EmitProcessorProp(OS, PM.ModelDef, "LoadLatency", ',');
1161 EmitProcessorProp(OS, PM.ModelDef, "HighLatency", ',');
1162 EmitProcessorProp(OS, PM.ModelDef, "MispredictPenalty", ',');
1164 bool PostRAScheduler =
1165 (PM.ModelDef ? PM.ModelDef->getValueAsBit("PostRAScheduler") : false);
1167 OS << " " << (PostRAScheduler ? "true" : "false") << ", // "
1168 << "PostRAScheduler\n";
1170 bool CompleteModel =
1171 (PM.ModelDef ? PM.ModelDef->getValueAsBit("CompleteModel") : false);
1173 OS << " " << (CompleteModel ? "true" : "false") << ", // "
1174 << "CompleteModel\n";
1176 OS << " " << PM.Index << ", // Processor ID\n";
1177 if (PM.hasInstrSchedModel())
1178 OS << " " << PM.ModelName << "ProcResources" << ",\n"
1179 << " " << PM.ModelName << "SchedClasses" << ",\n"
1180 << " " << PM.ProcResourceDefs.size()+1 << ",\n"
1181 << " " << (SchedModels.schedClassEnd()
1182 - SchedModels.schedClassBegin()) << ",\n";
1184 OS << " nullptr, nullptr, 0, 0,"
1185 << " // No instruction-level machine model.\n";
1186 if (PM.hasItineraries())
1187 OS << " " << PM.ItinsDef->getName() << "};\n";
1189 OS << " nullptr}; // No Itinerary\n";
1194 // EmitProcessorLookup - generate cpu name to itinerary lookup table.
1196 void SubtargetEmitter::EmitProcessorLookup(raw_ostream &OS) {
1197 // Gather and sort processor information
1198 std::vector<Record*> ProcessorList =
1199 Records.getAllDerivedDefinitions("Processor");
1200 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
1202 // Begin processor table
1204 OS << "// Sorted (by key) array of itineraries for CPU subtype.\n"
1205 << "extern const llvm::SubtargetInfoKV "
1206 << Target << "ProcSchedKV[] = {\n";
1208 // For each processor
1209 for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
1211 Record *Processor = ProcessorList[i];
1213 const std::string &Name = Processor->getValueAsString("Name");
1214 const std::string &ProcModelName =
1215 SchedModels.getModelForProc(Processor).ModelName;
1217 // Emit as { "cpu", procinit },
1218 OS << " { \"" << Name << "\", (const void *)&" << ProcModelName << " }";
1220 // Depending on ''if more in the list'' emit comma
1221 if (++i < N) OS << ",";
1226 // End processor table
1231 // EmitSchedModel - Emits all scheduling model tables, folding common patterns.
1233 void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) {
1234 OS << "#ifdef DBGFIELD\n"
1235 << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n"
1237 << "#ifndef NDEBUG\n"
1238 << "#define DBGFIELD(x) x,\n"
1240 << "#define DBGFIELD(x)\n"
1243 if (SchedModels.hasItineraries()) {
1244 std::vector<std::vector<InstrItinerary>> ProcItinLists;
1245 // Emit the stage data
1246 EmitStageAndOperandCycleData(OS, ProcItinLists);
1247 EmitItineraries(OS, ProcItinLists);
1249 OS << "\n// ===============================================================\n"
1250 << "// Data tables for the new per-operand machine model.\n";
1252 SchedClassTables SchedTables;
1253 for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
1254 GenSchedClassTables(ProcModel, SchedTables);
1256 EmitSchedClassTables(SchedTables, OS);
1258 // Emit the processor machine model
1259 EmitProcessorModels(OS);
1260 // Emit the processor lookup data
1261 EmitProcessorLookup(OS);
1263 OS << "#undef DBGFIELD";
1266 void SubtargetEmitter::EmitSchedModelHelpers(const std::string &ClassName,
1268 OS << "unsigned " << ClassName
1269 << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI,"
1270 << " const TargetSchedModel *SchedModel) const {\n";
1272 std::vector<Record*> Prologs = Records.getAllDerivedDefinitions("PredicateProlog");
1273 std::sort(Prologs.begin(), Prologs.end(), LessRecord());
1274 for (Record *P : Prologs) {
1275 OS << P->getValueAsString("Code") << '\n';
1277 IdxVec VariantClasses;
1278 for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) {
1279 if (SC.Transitions.empty())
1281 VariantClasses.push_back(SC.Index);
1283 if (!VariantClasses.empty()) {
1284 OS << " switch (SchedClass) {\n";
1285 for (unsigned VC : VariantClasses) {
1286 const CodeGenSchedClass &SC = SchedModels.getSchedClass(VC);
1287 OS << " case " << VC << ": // " << SC.Name << '\n';
1289 for (const CodeGenSchedTransition &T : SC.Transitions) {
1291 std::set_union(T.ProcIndices.begin(), T.ProcIndices.end(),
1292 ProcIndices.begin(), ProcIndices.end(),
1293 std::back_inserter(PI));
1294 ProcIndices.swap(PI);
1296 for (unsigned PI : ProcIndices) {
1299 OS << "if (SchedModel->getProcessorID() == " << PI << ") ";
1300 OS << "{ // " << (SchedModels.procModelBegin() + PI)->ModelName
1302 for (const CodeGenSchedTransition &T : SC.Transitions) {
1303 if (PI != 0 && !std::count(T.ProcIndices.begin(),
1304 T.ProcIndices.end(), PI)) {
1308 for (RecIter RI = T.PredTerm.begin(), RE = T.PredTerm.end();
1310 if (RI != T.PredTerm.begin())
1312 OS << "(" << (*RI)->getValueAsString("Predicate") << ")";
1315 << " return " << T.ToClassIdx << "; // "
1316 << SchedModels.getSchedClass(T.ToClassIdx).Name << '\n';
1322 if (SC.isInferred())
1323 OS << " return " << SC.Index << ";\n";
1328 OS << " report_fatal_error(\"Expected a variant SchedClass\");\n"
1329 << "} // " << ClassName << "::resolveSchedClass\n";
1333 // ParseFeaturesFunction - Produces a subtarget specific function for parsing
1334 // the subtarget features string.
1336 void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS,
1337 unsigned NumFeatures,
1338 unsigned NumProcs) {
1339 std::vector<Record*> Features =
1340 Records.getAllDerivedDefinitions("SubtargetFeature");
1341 std::sort(Features.begin(), Features.end(), LessRecord());
1343 OS << "// ParseSubtargetFeatures - Parses features string setting specified\n"
1344 << "// subtarget options.\n"
1347 OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef FS) {\n"
1348 << " DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n"
1349 << " DEBUG(dbgs() << \"\\nCPU:\" << CPU << \"\\n\\n\");\n";
1351 if (Features.empty()) {
1356 OS << " InitMCProcessorInfo(CPU, FS);\n"
1357 << " const FeatureBitset& Bits = getFeatureBits();\n";
1359 for (Record *R : Features) {
1361 const std::string &Instance = R->getName();
1362 const std::string &Value = R->getValueAsString("Value");
1363 const std::string &Attribute = R->getValueAsString("Attribute");
1365 if (Value=="true" || Value=="false")
1366 OS << " if (Bits[" << Target << "::"
1367 << Instance << "]) "
1368 << Attribute << " = " << Value << ";\n";
1370 OS << " if (Bits[" << Target << "::"
1371 << Instance << "] && "
1372 << Attribute << " < " << Value << ") "
1373 << Attribute << " = " << Value << ";\n";
1380 // SubtargetEmitter::run - Main subtarget enumeration emitter.
1382 void SubtargetEmitter::run(raw_ostream &OS) {
1383 emitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);
1385 OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n";
1386 OS << "#undef GET_SUBTARGETINFO_ENUM\n\n";
1388 OS << "namespace llvm {\n";
1390 OS << "} // end namespace llvm\n\n";
1391 OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n";
1393 OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n";
1394 OS << "#undef GET_SUBTARGETINFO_MC_DESC\n\n";
1396 OS << "namespace llvm {\n";
1398 OS << "namespace {\n";
1400 unsigned NumFeatures = FeatureKeyValues(OS);
1402 unsigned NumProcs = CPUKeyValues(OS);
1407 OS << "} // end anonymous namespace\n\n";
1410 // MCInstrInfo initialization routine.
1411 OS << "static inline MCSubtargetInfo *create" << Target
1412 << "MCSubtargetInfoImpl("
1413 << "const Triple &TT, StringRef CPU, StringRef FS) {\n";
1414 OS << " return new MCSubtargetInfo(TT, CPU, FS, ";
1416 OS << Target << "FeatureKV, ";
1420 OS << Target << "SubTypeKV, ";
1423 OS << '\n'; OS.indent(22);
1424 OS << Target << "ProcSchedKV, "
1425 << Target << "WriteProcResTable, "
1426 << Target << "WriteLatencyTable, "
1427 << Target << "ReadAdvanceTable, ";
1428 OS << '\n'; OS.indent(22);
1429 if (SchedModels.hasItineraries()) {
1430 OS << Target << "Stages, "
1431 << Target << "OperandCycles, "
1432 << Target << "ForwardingPaths";
1434 OS << "nullptr, nullptr, nullptr";
1437 OS << "} // end namespace llvm\n\n";
1439 OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n";
1441 OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n";
1442 OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n\n";
1444 OS << "#include \"llvm/Support/Debug.h\"\n";
1445 OS << "#include \"llvm/Support/raw_ostream.h\"\n\n";
1446 ParseFeaturesFunction(OS, NumFeatures, NumProcs);
1448 OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n";
1450 // Create a TargetSubtargetInfo subclass to hide the MC layer initialization.
1451 OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n";
1452 OS << "#undef GET_SUBTARGETINFO_HEADER\n\n";
1454 std::string ClassName = Target + "GenSubtargetInfo";
1455 OS << "namespace llvm {\n";
1456 OS << "class DFAPacketizer;\n";
1457 OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n"
1458 << " explicit " << ClassName << "(const Triple &TT, StringRef CPU, "
1459 << "StringRef FS);\n"
1461 << " unsigned resolveSchedClass(unsigned SchedClass, "
1462 << " const MachineInstr *DefMI,"
1463 << " const TargetSchedModel *SchedModel) const override;\n"
1464 << " DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)"
1467 OS << "} // end namespace llvm\n\n";
1469 OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n";
1471 OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n";
1472 OS << "#undef GET_SUBTARGETINFO_CTOR\n\n";
1474 OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n\n";
1475 OS << "namespace llvm {\n";
1476 OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n";
1477 OS << "extern const llvm::SubtargetFeatureKV " << Target << "SubTypeKV[];\n";
1478 OS << "extern const llvm::SubtargetInfoKV " << Target << "ProcSchedKV[];\n";
1479 OS << "extern const llvm::MCWriteProcResEntry "
1480 << Target << "WriteProcResTable[];\n";
1481 OS << "extern const llvm::MCWriteLatencyEntry "
1482 << Target << "WriteLatencyTable[];\n";
1483 OS << "extern const llvm::MCReadAdvanceEntry "
1484 << Target << "ReadAdvanceTable[];\n";
1486 if (SchedModels.hasItineraries()) {
1487 OS << "extern const llvm::InstrStage " << Target << "Stages[];\n";
1488 OS << "extern const unsigned " << Target << "OperandCycles[];\n";
1489 OS << "extern const unsigned " << Target << "ForwardingPaths[];\n";
1492 OS << ClassName << "::" << ClassName << "(const Triple &TT, StringRef CPU, "
1493 << "StringRef FS)\n"
1494 << " : TargetSubtargetInfo(TT, CPU, FS, ";
1496 OS << "makeArrayRef(" << Target << "FeatureKV, " << NumFeatures << "), ";
1500 OS << "makeArrayRef(" << Target << "SubTypeKV, " << NumProcs << "), ";
1503 OS << '\n'; OS.indent(24);
1504 OS << Target << "ProcSchedKV, "
1505 << Target << "WriteProcResTable, "
1506 << Target << "WriteLatencyTable, "
1507 << Target << "ReadAdvanceTable, ";
1508 OS << '\n'; OS.indent(24);
1509 if (SchedModels.hasItineraries()) {
1510 OS << Target << "Stages, "
1511 << Target << "OperandCycles, "
1512 << Target << "ForwardingPaths";
1514 OS << "nullptr, nullptr, nullptr";
1517 EmitSchedModelHelpers(ClassName, OS);
1519 OS << "} // end namespace llvm\n\n";
1521 OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n";
1526 void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) {
1527 CodeGenTarget CGTarget(RK);
1528 SubtargetEmitter(RK, CGTarget).run(OS);
1531 } // end namespace llvm