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/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/MC/MCInstrItineraries.h"
19 #include "llvm/MC/SubtargetFeature.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/TableGen/Error.h"
23 #include "llvm/TableGen/Record.h"
24 #include "llvm/TableGen/TableGenBackend.h"
31 #define DEBUG_TYPE "subtarget-emitter"
34 class SubtargetEmitter {
35 // Each processor has a SchedClassDesc table with an entry for each SchedClass.
36 // The SchedClassDesc table indexes into a global write resource table, write
37 // latency table, and read advance table.
38 struct SchedClassTables {
39 std::vector<std::vector<MCSchedClassDesc> > ProcSchedClasses;
40 std::vector<MCWriteProcResEntry> WriteProcResources;
41 std::vector<MCWriteLatencyEntry> WriteLatencies;
42 std::vector<std::string> WriterNames;
43 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries;
45 // Reserve an invalid entry at index 0
47 ProcSchedClasses.resize(1);
48 WriteProcResources.resize(1);
49 WriteLatencies.resize(1);
50 WriterNames.push_back("InvalidWrite");
51 ReadAdvanceEntries.resize(1);
55 struct LessWriteProcResources {
56 bool operator()(const MCWriteProcResEntry &LHS,
57 const MCWriteProcResEntry &RHS) {
58 return LHS.ProcResourceIdx < RHS.ProcResourceIdx;
62 RecordKeeper &Records;
63 CodeGenSchedModels &SchedModels;
66 void Enumeration(raw_ostream &OS, const char *ClassName);
67 unsigned FeatureKeyValues(raw_ostream &OS);
68 unsigned CPUKeyValues(raw_ostream &OS);
69 void FormItineraryStageString(const std::string &Names,
70 Record *ItinData, std::string &ItinString,
72 void FormItineraryOperandCycleString(Record *ItinData, std::string &ItinString,
73 unsigned &NOperandCycles);
74 void FormItineraryBypassString(const std::string &Names,
76 std::string &ItinString, unsigned NOperandCycles);
77 void EmitStageAndOperandCycleData(raw_ostream &OS,
78 std::vector<std::vector<InstrItinerary> >
80 void EmitItineraries(raw_ostream &OS,
81 std::vector<std::vector<InstrItinerary> >
83 void EmitProcessorProp(raw_ostream &OS, const Record *R, const char *Name,
85 void EmitProcessorResources(const CodeGenProcModel &ProcModel,
87 Record *FindWriteResources(const CodeGenSchedRW &SchedWrite,
88 const CodeGenProcModel &ProcModel);
89 Record *FindReadAdvance(const CodeGenSchedRW &SchedRead,
90 const CodeGenProcModel &ProcModel);
91 void ExpandProcResources(RecVec &PRVec, std::vector<int64_t> &Cycles,
92 const CodeGenProcModel &ProcModel);
93 void GenSchedClassTables(const CodeGenProcModel &ProcModel,
94 SchedClassTables &SchedTables);
95 void EmitSchedClassTables(SchedClassTables &SchedTables, raw_ostream &OS);
96 void EmitProcessorModels(raw_ostream &OS);
97 void EmitProcessorLookup(raw_ostream &OS);
98 void EmitSchedModelHelpers(std::string ClassName, raw_ostream &OS);
99 void EmitSchedModel(raw_ostream &OS);
100 void ParseFeaturesFunction(raw_ostream &OS, unsigned NumFeatures,
104 SubtargetEmitter(RecordKeeper &R, CodeGenTarget &TGT):
105 Records(R), SchedModels(TGT.getSchedModels()), Target(TGT.getName()) {}
107 void run(raw_ostream &o);
110 } // End anonymous namespace
113 // Enumeration - Emit the specified class as an enumeration.
115 void SubtargetEmitter::Enumeration(raw_ostream &OS,
116 const char *ClassName) {
117 // Get all records of class and sort
118 std::vector<Record*> DefList = Records.getAllDerivedDefinitions(ClassName);
119 std::sort(DefList.begin(), DefList.end(), LessRecord());
121 unsigned N = DefList.size();
124 if (N > MAX_SUBTARGET_FEATURES) {
125 errs() << "Too many subtarget features! Bump MAX_SUBTARGET_FEATURES.";
129 OS << "namespace " << Target << " {\n";
135 for (unsigned i = 0; i < N;) {
137 Record *Def = DefList[i];
140 OS << " " << Def->getName() << " = " << i;
141 if (++i < N) OS << ",";
146 // Close enumeration and namespace
151 // FeatureKeyValues - Emit data of all the subtarget features. Used by the
154 unsigned SubtargetEmitter::FeatureKeyValues(raw_ostream &OS) {
155 // Gather and sort all the features
156 std::vector<Record*> FeatureList =
157 Records.getAllDerivedDefinitions("SubtargetFeature");
159 if (FeatureList.empty())
162 std::sort(FeatureList.begin(), FeatureList.end(), LessRecordFieldName());
164 // Begin feature table
165 OS << "// Sorted (by key) array of values for CPU features.\n"
166 << "extern const llvm::SubtargetFeatureKV " << Target
167 << "FeatureKV[] = {\n";
170 unsigned NumFeatures = 0;
171 for (unsigned i = 0, N = FeatureList.size(); i < N; ++i) {
173 Record *Feature = FeatureList[i];
175 const std::string &Name = Feature->getName();
176 const std::string &CommandLineName = Feature->getValueAsString("Name");
177 const std::string &Desc = Feature->getValueAsString("Desc");
179 if (CommandLineName.empty()) continue;
181 // Emit as { "feature", "description", { featureEnum }, { i1 , i2 , ... , in } }
183 << "\"" << CommandLineName << "\", "
184 << "\"" << Desc << "\", "
185 << "{ " << Target << "::" << Name << " }, ";
187 const std::vector<Record*> &ImpliesList =
188 Feature->getValueAsListOfDefs("Implies");
190 if (ImpliesList.empty()) {
194 for (unsigned j = 0, M = ImpliesList.size(); j < M;) {
195 OS << Target << "::" << ImpliesList[j]->getName();
196 if (++j < M) OS << ", ";
204 // Depending on 'if more in the list' emit comma
205 if ((i + 1) < N) OS << ",";
217 // CPUKeyValues - Emit data of all the subtarget processors. Used by command
220 unsigned SubtargetEmitter::CPUKeyValues(raw_ostream &OS) {
221 // Gather and sort processor information
222 std::vector<Record*> ProcessorList =
223 Records.getAllDerivedDefinitions("Processor");
224 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
226 // Begin processor table
227 OS << "// Sorted (by key) array of values for CPU subtype.\n"
228 << "extern const llvm::SubtargetFeatureKV " << Target
229 << "SubTypeKV[] = {\n";
231 // For each processor
232 for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
234 Record *Processor = ProcessorList[i];
236 const std::string &Name = Processor->getValueAsString("Name");
237 const std::vector<Record*> &FeatureList =
238 Processor->getValueAsListOfDefs("Features");
240 // Emit as { "cpu", "description", { f1 , f2 , ... fn } },
242 << "\"" << Name << "\", "
243 << "\"Select the " << Name << " processor\", ";
245 if (FeatureList.empty()) {
249 for (unsigned j = 0, M = FeatureList.size(); j < M;) {
250 OS << Target << "::" << FeatureList[j]->getName();
251 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();
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();
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> >
366 // Multiple processor models may share an itinerary record. Emit it once.
367 SmallPtrSet<Record*, 8> ItinsDefSet;
369 // Emit functional units for all the itineraries.
370 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
371 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
373 if (!ItinsDefSet.insert(PI->ItinsDef).second)
376 std::vector<Record*> FUs = PI->ItinsDef->getValueAsListOfDefs("FU");
380 const std::string &Name = PI->ItinsDef->getName();
381 OS << "\n// Functional units for \"" << Name << "\"\n"
382 << "namespace " << Name << "FU {\n";
384 for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j)
385 OS << " const unsigned " << FUs[j]->getName()
386 << " = 1 << " << j << ";\n";
390 std::vector<Record*> BPs = PI->ItinsDef->getValueAsListOfDefs("BP");
392 OS << "\n// Pipeline forwarding pathes for itineraries \"" << Name
393 << "\"\n" << "namespace " << Name << "Bypass {\n";
395 OS << " const unsigned NoBypass = 0;\n";
396 for (unsigned j = 0, BPN = BPs.size(); j < BPN; ++j)
397 OS << " const unsigned " << BPs[j]->getName()
398 << " = 1 << " << j << ";\n";
404 // Begin stages table
405 std::string StageTable = "\nextern const llvm::InstrStage " + Target +
407 StageTable += " { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n";
409 // Begin operand cycle table
410 std::string OperandCycleTable = "extern const unsigned " + Target +
411 "OperandCycles[] = {\n";
412 OperandCycleTable += " 0, // No itinerary\n";
414 // Begin pipeline bypass table
415 std::string BypassTable = "extern const unsigned " + Target +
416 "ForwardingPaths[] = {\n";
417 BypassTable += " 0, // No itinerary\n";
419 // For each Itinerary across all processors, add a unique entry to the stages,
420 // operand cycles, and pipepine bypess tables. Then add the new Itinerary
421 // object with computed offsets to the ProcItinLists result.
422 unsigned StageCount = 1, OperandCycleCount = 1;
423 std::map<std::string, unsigned> ItinStageMap, ItinOperandMap;
424 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
425 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
426 const CodeGenProcModel &ProcModel = *PI;
428 // Add process itinerary to the list.
429 ProcItinLists.resize(ProcItinLists.size()+1);
431 // If this processor defines no itineraries, then leave the itinerary list
433 std::vector<InstrItinerary> &ItinList = ProcItinLists.back();
434 if (!ProcModel.hasItineraries())
437 const std::string &Name = ProcModel.ItinsDef->getName();
439 ItinList.resize(SchedModels.numInstrSchedClasses());
440 assert(ProcModel.ItinDefList.size() == ItinList.size() && "bad Itins");
442 for (unsigned SchedClassIdx = 0, SchedClassEnd = ItinList.size();
443 SchedClassIdx < SchedClassEnd; ++SchedClassIdx) {
445 // Next itinerary data
446 Record *ItinData = ProcModel.ItinDefList[SchedClassIdx];
448 // Get string and stage count
449 std::string ItinStageString;
450 unsigned NStages = 0;
452 FormItineraryStageString(Name, ItinData, ItinStageString, NStages);
454 // Get string and operand cycle count
455 std::string ItinOperandCycleString;
456 unsigned NOperandCycles = 0;
457 std::string ItinBypassString;
459 FormItineraryOperandCycleString(ItinData, ItinOperandCycleString,
462 FormItineraryBypassString(Name, ItinData, ItinBypassString,
466 // Check to see if stage already exists and create if it doesn't
467 unsigned FindStage = 0;
469 FindStage = ItinStageMap[ItinStageString];
470 if (FindStage == 0) {
471 // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // indices
472 StageTable += ItinStageString + ", // " + itostr(StageCount);
474 StageTable += "-" + itostr(StageCount + NStages - 1);
476 // Record Itin class number.
477 ItinStageMap[ItinStageString] = FindStage = StageCount;
478 StageCount += NStages;
482 // Check to see if operand cycle already exists and create if it doesn't
483 unsigned FindOperandCycle = 0;
484 if (NOperandCycles > 0) {
485 std::string ItinOperandString = ItinOperandCycleString+ItinBypassString;
486 FindOperandCycle = ItinOperandMap[ItinOperandString];
487 if (FindOperandCycle == 0) {
488 // Emit as cycle, // index
489 OperandCycleTable += ItinOperandCycleString + ", // ";
490 std::string OperandIdxComment = itostr(OperandCycleCount);
491 if (NOperandCycles > 1)
492 OperandIdxComment += "-"
493 + itostr(OperandCycleCount + NOperandCycles - 1);
494 OperandCycleTable += OperandIdxComment + "\n";
495 // Record Itin class number.
496 ItinOperandMap[ItinOperandCycleString] =
497 FindOperandCycle = OperandCycleCount;
498 // Emit as bypass, // index
499 BypassTable += ItinBypassString + ", // " + OperandIdxComment + "\n";
500 OperandCycleCount += NOperandCycles;
504 // Set up itinerary as location and location + stage count
505 int NumUOps = ItinData ? ItinData->getValueAsInt("NumMicroOps") : 0;
506 InstrItinerary Intinerary = { NumUOps, FindStage, FindStage + NStages,
508 FindOperandCycle + NOperandCycles};
510 // Inject - empty slots will be 0, 0
511 ItinList[SchedClassIdx] = Intinerary;
516 StageTable += " { 0, 0, 0, llvm::InstrStage::Required } // End stages\n";
517 StageTable += "};\n";
519 // Closing operand cycles
520 OperandCycleTable += " 0 // End operand cycles\n";
521 OperandCycleTable += "};\n";
523 BypassTable += " 0 // End bypass tables\n";
524 BypassTable += "};\n";
528 OS << OperandCycleTable;
533 // EmitProcessorData - Generate data for processor itineraries that were
534 // computed during EmitStageAndOperandCycleData(). ProcItinLists lists all
535 // Itineraries for each processor. The Itinerary lists are indexed on
536 // CodeGenSchedClass::Index.
538 void SubtargetEmitter::
539 EmitItineraries(raw_ostream &OS,
540 std::vector<std::vector<InstrItinerary> > &ProcItinLists) {
542 // Multiple processor models may share an itinerary record. Emit it once.
543 SmallPtrSet<Record*, 8> ItinsDefSet;
545 // For each processor's machine model
546 std::vector<std::vector<InstrItinerary> >::iterator
547 ProcItinListsIter = ProcItinLists.begin();
548 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
549 PE = SchedModels.procModelEnd(); PI != PE; ++PI, ++ProcItinListsIter) {
551 Record *ItinsDef = PI->ItinsDef;
552 if (!ItinsDefSet.insert(ItinsDef).second)
555 // Get processor itinerary name
556 const std::string &Name = ItinsDef->getName();
558 // Get the itinerary list for the processor.
559 assert(ProcItinListsIter != ProcItinLists.end() && "bad iterator");
560 std::vector<InstrItinerary> &ItinList = *ProcItinListsIter;
562 // Empty itineraries aren't referenced anywhere in the tablegen output
563 // so don't emit them.
564 if (ItinList.empty())
568 OS << "static const llvm::InstrItinerary ";
570 // Begin processor itinerary table
571 OS << Name << "[] = {\n";
573 // For each itinerary class in CodeGenSchedClass::Index order.
574 for (unsigned j = 0, M = ItinList.size(); j < M; ++j) {
575 InstrItinerary &Intinerary = ItinList[j];
577 // Emit Itinerary in the form of
578 // { firstStage, lastStage, firstCycle, lastCycle } // index
580 Intinerary.NumMicroOps << ", " <<
581 Intinerary.FirstStage << ", " <<
582 Intinerary.LastStage << ", " <<
583 Intinerary.FirstOperandCycle << ", " <<
584 Intinerary.LastOperandCycle << " }" <<
585 ", // " << j << " " << SchedModels.getSchedClass(j).Name << "\n";
587 // End processor itinerary table
588 OS << " { 0, ~0U, ~0U, ~0U, ~0U } // end marker\n";
593 // Emit either the value defined in the TableGen Record, or the default
594 // value defined in the C++ header. The Record is null if the processor does not
596 void SubtargetEmitter::EmitProcessorProp(raw_ostream &OS, const Record *R,
597 const char *Name, char Separator) {
599 int V = R ? R->getValueAsInt(Name) : -1;
601 OS << V << Separator << " // " << Name;
603 OS << "MCSchedModel::Default" << Name << Separator;
607 void SubtargetEmitter::EmitProcessorResources(const CodeGenProcModel &ProcModel,
609 char Sep = ProcModel.ProcResourceDefs.empty() ? ' ' : ',';
611 OS << "\n// {Name, NumUnits, SuperIdx, IsBuffered}\n";
612 OS << "static const llvm::MCProcResourceDesc "
613 << ProcModel.ModelName << "ProcResources" << "[] = {\n"
614 << " {DBGFIELD(\"InvalidUnit\") 0, 0, 0}" << Sep << "\n";
616 for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) {
617 Record *PRDef = ProcModel.ProcResourceDefs[i];
619 Record *SuperDef = nullptr;
620 unsigned SuperIdx = 0;
621 unsigned NumUnits = 0;
622 int BufferSize = PRDef->getValueAsInt("BufferSize");
623 if (PRDef->isSubClassOf("ProcResGroup")) {
624 RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources");
625 for (RecIter RUI = ResUnits.begin(), RUE = ResUnits.end();
627 NumUnits += (*RUI)->getValueAsInt("NumUnits");
632 if (PRDef->getValueInit("Super")->isComplete()) {
633 SuperDef = SchedModels.findProcResUnits(
634 PRDef->getValueAsDef("Super"), ProcModel);
635 SuperIdx = ProcModel.getProcResourceIdx(SuperDef);
637 NumUnits = PRDef->getValueAsInt("NumUnits");
639 // Emit the ProcResourceDesc
642 OS << " {DBGFIELD(\"" << PRDef->getName() << "\") ";
643 if (PRDef->getName().size() < 15)
644 OS.indent(15 - PRDef->getName().size());
645 OS << NumUnits << ", " << SuperIdx << ", "
646 << BufferSize << "}" << Sep << " // #" << i+1;
648 OS << ", Super=" << SuperDef->getName();
654 // Find the WriteRes Record that defines processor resources for this
656 Record *SubtargetEmitter::FindWriteResources(
657 const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) {
659 // Check if the SchedWrite is already subtarget-specific and directly
660 // specifies a set of processor resources.
661 if (SchedWrite.TheDef->isSubClassOf("SchedWriteRes"))
662 return SchedWrite.TheDef;
664 Record *AliasDef = nullptr;
665 for (RecIter AI = SchedWrite.Aliases.begin(), AE = SchedWrite.Aliases.end();
667 const CodeGenSchedRW &AliasRW =
668 SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
669 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
670 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
671 if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
675 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
676 "defined for processor " + ProcModel.ModelName +
677 " Ensure only one SchedAlias exists per RW.");
678 AliasDef = AliasRW.TheDef;
680 if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes"))
683 // Check this processor's list of write resources.
684 Record *ResDef = nullptr;
685 for (RecIter WRI = ProcModel.WriteResDefs.begin(),
686 WRE = ProcModel.WriteResDefs.end(); WRI != WRE; ++WRI) {
687 if (!(*WRI)->isSubClassOf("WriteRes"))
689 if (AliasDef == (*WRI)->getValueAsDef("WriteType")
690 || SchedWrite.TheDef == (*WRI)->getValueAsDef("WriteType")) {
692 PrintFatalError((*WRI)->getLoc(), "Resources are defined for both "
693 "SchedWrite and its alias on processor " +
694 ProcModel.ModelName);
699 // TODO: If ProcModel has a base model (previous generation processor),
700 // then call FindWriteResources recursively with that model here.
702 PrintFatalError(ProcModel.ModelDef->getLoc(),
703 std::string("Processor does not define resources for ")
704 + SchedWrite.TheDef->getName());
709 /// Find the ReadAdvance record for the given SchedRead on this processor or
711 Record *SubtargetEmitter::FindReadAdvance(const CodeGenSchedRW &SchedRead,
712 const CodeGenProcModel &ProcModel) {
713 // Check for SchedReads that directly specify a ReadAdvance.
714 if (SchedRead.TheDef->isSubClassOf("SchedReadAdvance"))
715 return SchedRead.TheDef;
717 // Check this processor's list of aliases for SchedRead.
718 Record *AliasDef = nullptr;
719 for (RecIter AI = SchedRead.Aliases.begin(), AE = SchedRead.Aliases.end();
721 const CodeGenSchedRW &AliasRW =
722 SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
723 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
724 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
725 if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
729 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
730 "defined for processor " + ProcModel.ModelName +
731 " Ensure only one SchedAlias exists per RW.");
732 AliasDef = AliasRW.TheDef;
734 if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance"))
737 // Check this processor's ReadAdvanceList.
738 Record *ResDef = nullptr;
739 for (RecIter RAI = ProcModel.ReadAdvanceDefs.begin(),
740 RAE = ProcModel.ReadAdvanceDefs.end(); RAI != RAE; ++RAI) {
741 if (!(*RAI)->isSubClassOf("ReadAdvance"))
743 if (AliasDef == (*RAI)->getValueAsDef("ReadType")
744 || SchedRead.TheDef == (*RAI)->getValueAsDef("ReadType")) {
746 PrintFatalError((*RAI)->getLoc(), "Resources are defined for both "
747 "SchedRead and its alias on processor " +
748 ProcModel.ModelName);
753 // TODO: If ProcModel has a base model (previous generation processor),
754 // then call FindReadAdvance recursively with that model here.
755 if (!ResDef && SchedRead.TheDef->getName() != "ReadDefault") {
756 PrintFatalError(ProcModel.ModelDef->getLoc(),
757 std::string("Processor does not define resources for ")
758 + SchedRead.TheDef->getName());
763 // Expand an explicit list of processor resources into a full list of implied
764 // resource groups and super resources that cover them.
765 void SubtargetEmitter::ExpandProcResources(RecVec &PRVec,
766 std::vector<int64_t> &Cycles,
767 const CodeGenProcModel &PM) {
768 // Default to 1 resource cycle.
769 Cycles.resize(PRVec.size(), 1);
770 for (unsigned i = 0, e = PRVec.size(); i != e; ++i) {
771 Record *PRDef = PRVec[i];
773 if (PRDef->isSubClassOf("ProcResGroup"))
774 SubResources = PRDef->getValueAsListOfDefs("Resources");
776 SubResources.push_back(PRDef);
777 PRDef = SchedModels.findProcResUnits(PRVec[i], PM);
778 for (Record *SubDef = PRDef;
779 SubDef->getValueInit("Super")->isComplete();) {
780 if (SubDef->isSubClassOf("ProcResGroup")) {
781 // Disallow this for simplicitly.
782 PrintFatalError(SubDef->getLoc(), "Processor resource group "
783 " cannot be a super resources.");
786 SchedModels.findProcResUnits(SubDef->getValueAsDef("Super"), PM);
787 PRVec.push_back(SuperDef);
788 Cycles.push_back(Cycles[i]);
792 for (RecIter PRI = PM.ProcResourceDefs.begin(),
793 PRE = PM.ProcResourceDefs.end();
795 if (*PRI == PRDef || !(*PRI)->isSubClassOf("ProcResGroup"))
797 RecVec SuperResources = (*PRI)->getValueAsListOfDefs("Resources");
798 RecIter SubI = SubResources.begin(), SubE = SubResources.end();
799 for( ; SubI != SubE; ++SubI) {
800 if (std::find(SuperResources.begin(), SuperResources.end(), *SubI)
801 == SuperResources.end()) {
806 PRVec.push_back(*PRI);
807 Cycles.push_back(Cycles[i]);
813 // Generate the SchedClass table for this processor and update global
814 // tables. Must be called for each processor in order.
815 void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel,
816 SchedClassTables &SchedTables) {
817 SchedTables.ProcSchedClasses.resize(SchedTables.ProcSchedClasses.size() + 1);
818 if (!ProcModel.hasInstrSchedModel())
821 std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back();
822 for (CodeGenSchedModels::SchedClassIter SCI = SchedModels.schedClassBegin(),
823 SCE = SchedModels.schedClassEnd(); SCI != SCE; ++SCI) {
824 DEBUG(SCI->dump(&SchedModels));
826 SCTab.resize(SCTab.size() + 1);
827 MCSchedClassDesc &SCDesc = SCTab.back();
828 // SCDesc.Name is guarded by NDEBUG
829 SCDesc.NumMicroOps = 0;
830 SCDesc.BeginGroup = false;
831 SCDesc.EndGroup = false;
832 SCDesc.WriteProcResIdx = 0;
833 SCDesc.WriteLatencyIdx = 0;
834 SCDesc.ReadAdvanceIdx = 0;
836 // A Variant SchedClass has no resources of its own.
837 bool HasVariants = false;
838 for (std::vector<CodeGenSchedTransition>::const_iterator
839 TI = SCI->Transitions.begin(), TE = SCI->Transitions.end();
841 if (TI->ProcIndices[0] == 0) {
845 IdxIter PIPos = std::find(TI->ProcIndices.begin(),
846 TI->ProcIndices.end(), ProcModel.Index);
847 if (PIPos != TI->ProcIndices.end()) {
853 SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps;
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(!SCI->ProcIndices.empty() && "expect at least one procidx");
861 if (SCI->ProcIndices[0] != 0) {
862 IdxIter PIPos = std::find(SCI->ProcIndices.begin(),
863 SCI->ProcIndices.end(), ProcModel.Index);
864 if (PIPos == SCI->ProcIndices.end())
867 IdxVec Writes = SCI->Writes;
868 IdxVec Reads = SCI->Reads;
869 if (!SCI->InstRWs.empty()) {
870 // This class has a default ReadWrite list which can be overriden by
871 // InstRW definitions.
872 Record *RWDef = nullptr;
873 for (RecIter RWI = SCI->InstRWs.begin(), RWE = SCI->InstRWs.end();
875 Record *RWModelDef = (*RWI)->getValueAsDef("SchedModel");
876 if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) {
884 SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
888 if (Writes.empty()) {
889 // Check this processor's itinerary class resources.
890 for (RecIter II = ProcModel.ItinRWDefs.begin(),
891 IE = ProcModel.ItinRWDefs.end(); II != IE; ++II) {
892 RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
893 if (std::find(Matched.begin(), Matched.end(), SCI->ItinClassDef)
895 SchedModels.findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"),
900 if (Writes.empty()) {
901 DEBUG(dbgs() << ProcModel.ModelName
902 << " does not have resources for class " << SCI->Name << '\n');
905 // Sum resources across all operand writes.
906 std::vector<MCWriteProcResEntry> WriteProcResources;
907 std::vector<MCWriteLatencyEntry> WriteLatencies;
908 std::vector<std::string> WriterNames;
909 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries;
910 for (IdxIter WI = Writes.begin(), WE = Writes.end(); WI != WE; ++WI) {
912 SchedModels.expandRWSeqForProc(*WI, WriteSeq, /*IsRead=*/false,
915 // For each operand, create a latency entry.
916 MCWriteLatencyEntry WLEntry;
918 unsigned WriteID = WriteSeq.back();
919 WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name);
920 // If this Write is not referenced by a ReadAdvance, don't distinguish it
921 // from other WriteLatency entries.
922 if (!SchedModels.hasReadOfWrite(
923 SchedModels.getSchedWrite(WriteID).TheDef)) {
926 WLEntry.WriteResourceID = WriteID;
928 for (IdxIter WSI = WriteSeq.begin(), WSE = WriteSeq.end();
932 FindWriteResources(SchedModels.getSchedWrite(*WSI), ProcModel);
934 // Mark the parent class as invalid for unsupported write types.
935 if (WriteRes->getValueAsBit("Unsupported")) {
936 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
939 WLEntry.Cycles += WriteRes->getValueAsInt("Latency");
940 SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps");
941 SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup");
942 SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup");
944 // Create an entry for each ProcResource listed in WriteRes.
945 RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources");
946 std::vector<int64_t> Cycles =
947 WriteRes->getValueAsListOfInts("ResourceCycles");
949 ExpandProcResources(PRVec, Cycles, ProcModel);
951 for (unsigned PRIdx = 0, PREnd = PRVec.size();
952 PRIdx != PREnd; ++PRIdx) {
953 MCWriteProcResEntry WPREntry;
954 WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]);
955 assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx");
956 WPREntry.Cycles = Cycles[PRIdx];
957 // If this resource is already used in this sequence, add the current
958 // entry's cycles so that the same resource appears to be used
959 // serially, rather than multiple parallel uses. This is important for
960 // in-order machine where the resource consumption is a hazard.
961 unsigned WPRIdx = 0, WPREnd = WriteProcResources.size();
962 for( ; WPRIdx != WPREnd; ++WPRIdx) {
963 if (WriteProcResources[WPRIdx].ProcResourceIdx
964 == WPREntry.ProcResourceIdx) {
965 WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles;
969 if (WPRIdx == WPREnd)
970 WriteProcResources.push_back(WPREntry);
973 WriteLatencies.push_back(WLEntry);
975 // Create an entry for each operand Read in this SchedClass.
976 // Entries must be sorted first by UseIdx then by WriteResourceID.
977 for (unsigned UseIdx = 0, EndIdx = Reads.size();
978 UseIdx != EndIdx; ++UseIdx) {
979 Record *ReadAdvance =
980 FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel);
984 // Mark the parent class as invalid for unsupported write types.
985 if (ReadAdvance->getValueAsBit("Unsupported")) {
986 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
989 RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites");
991 if (ValidWrites.empty())
992 WriteIDs.push_back(0);
994 for (RecIter VWI = ValidWrites.begin(), VWE = ValidWrites.end();
996 WriteIDs.push_back(SchedModels.getSchedRWIdx(*VWI, /*IsRead=*/false));
999 std::sort(WriteIDs.begin(), WriteIDs.end());
1000 for(IdxIter WI = WriteIDs.begin(), WE = WriteIDs.end(); WI != WE; ++WI) {
1001 MCReadAdvanceEntry RAEntry;
1002 RAEntry.UseIdx = UseIdx;
1003 RAEntry.WriteResourceID = *WI;
1004 RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles");
1005 ReadAdvanceEntries.push_back(RAEntry);
1008 if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) {
1009 WriteProcResources.clear();
1010 WriteLatencies.clear();
1011 ReadAdvanceEntries.clear();
1013 // Add the information for this SchedClass to the global tables using basic
1016 // WritePrecRes entries are sorted by ProcResIdx.
1017 std::sort(WriteProcResources.begin(), WriteProcResources.end(),
1018 LessWriteProcResources());
1020 SCDesc.NumWriteProcResEntries = WriteProcResources.size();
1021 std::vector<MCWriteProcResEntry>::iterator WPRPos =
1022 std::search(SchedTables.WriteProcResources.begin(),
1023 SchedTables.WriteProcResources.end(),
1024 WriteProcResources.begin(), WriteProcResources.end());
1025 if (WPRPos != SchedTables.WriteProcResources.end())
1026 SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin();
1028 SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size();
1029 SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(),
1030 WriteProcResources.end());
1032 // Latency entries must remain in operand order.
1033 SCDesc.NumWriteLatencyEntries = WriteLatencies.size();
1034 std::vector<MCWriteLatencyEntry>::iterator WLPos =
1035 std::search(SchedTables.WriteLatencies.begin(),
1036 SchedTables.WriteLatencies.end(),
1037 WriteLatencies.begin(), WriteLatencies.end());
1038 if (WLPos != SchedTables.WriteLatencies.end()) {
1039 unsigned idx = WLPos - SchedTables.WriteLatencies.begin();
1040 SCDesc.WriteLatencyIdx = idx;
1041 for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i)
1042 if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) ==
1043 std::string::npos) {
1044 SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i];
1048 SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size();
1049 SchedTables.WriteLatencies.insert(SchedTables.WriteLatencies.end(),
1050 WriteLatencies.begin(),
1051 WriteLatencies.end());
1052 SchedTables.WriterNames.insert(SchedTables.WriterNames.end(),
1053 WriterNames.begin(), WriterNames.end());
1055 // ReadAdvanceEntries must remain in operand order.
1056 SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size();
1057 std::vector<MCReadAdvanceEntry>::iterator RAPos =
1058 std::search(SchedTables.ReadAdvanceEntries.begin(),
1059 SchedTables.ReadAdvanceEntries.end(),
1060 ReadAdvanceEntries.begin(), ReadAdvanceEntries.end());
1061 if (RAPos != SchedTables.ReadAdvanceEntries.end())
1062 SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin();
1064 SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size();
1065 SchedTables.ReadAdvanceEntries.insert(RAPos, ReadAdvanceEntries.begin(),
1066 ReadAdvanceEntries.end());
1071 // Emit SchedClass tables for all processors and associated global tables.
1072 void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables,
1074 // Emit global WriteProcResTable.
1075 OS << "\n// {ProcResourceIdx, Cycles}\n"
1076 << "extern const llvm::MCWriteProcResEntry "
1077 << Target << "WriteProcResTable[] = {\n"
1078 << " { 0, 0}, // Invalid\n";
1079 for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size();
1080 WPRIdx != WPREnd; ++WPRIdx) {
1081 MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx];
1082 OS << " {" << format("%2d", WPREntry.ProcResourceIdx) << ", "
1083 << format("%2d", WPREntry.Cycles) << "}";
1084 if (WPRIdx + 1 < WPREnd)
1086 OS << " // #" << WPRIdx << '\n';
1088 OS << "}; // " << Target << "WriteProcResTable\n";
1090 // Emit global WriteLatencyTable.
1091 OS << "\n// {Cycles, WriteResourceID}\n"
1092 << "extern const llvm::MCWriteLatencyEntry "
1093 << Target << "WriteLatencyTable[] = {\n"
1094 << " { 0, 0}, // Invalid\n";
1095 for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size();
1096 WLIdx != WLEnd; ++WLIdx) {
1097 MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx];
1098 OS << " {" << format("%2d", WLEntry.Cycles) << ", "
1099 << format("%2d", WLEntry.WriteResourceID) << "}";
1100 if (WLIdx + 1 < WLEnd)
1102 OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n';
1104 OS << "}; // " << Target << "WriteLatencyTable\n";
1106 // Emit global ReadAdvanceTable.
1107 OS << "\n// {UseIdx, WriteResourceID, Cycles}\n"
1108 << "extern const llvm::MCReadAdvanceEntry "
1109 << Target << "ReadAdvanceTable[] = {\n"
1110 << " {0, 0, 0}, // Invalid\n";
1111 for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size();
1112 RAIdx != RAEnd; ++RAIdx) {
1113 MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx];
1114 OS << " {" << RAEntry.UseIdx << ", "
1115 << format("%2d", RAEntry.WriteResourceID) << ", "
1116 << format("%2d", RAEntry.Cycles) << "}";
1117 if (RAIdx + 1 < RAEnd)
1119 OS << " // #" << RAIdx << '\n';
1121 OS << "}; // " << Target << "ReadAdvanceTable\n";
1123 // Emit a SchedClass table for each processor.
1124 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
1125 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
1126 if (!PI->hasInstrSchedModel())
1129 std::vector<MCSchedClassDesc> &SCTab =
1130 SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())];
1132 OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup,"
1133 << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n";
1134 OS << "static const llvm::MCSchedClassDesc "
1135 << PI->ModelName << "SchedClasses[] = {\n";
1137 // The first class is always invalid. We no way to distinguish it except by
1138 // name and position.
1139 assert(SchedModels.getSchedClass(0).Name == "NoInstrModel"
1140 && "invalid class not first");
1141 OS << " {DBGFIELD(\"InvalidSchedClass\") "
1142 << MCSchedClassDesc::InvalidNumMicroOps
1143 << ", 0, 0, 0, 0, 0, 0, 0, 0},\n";
1145 for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) {
1146 MCSchedClassDesc &MCDesc = SCTab[SCIdx];
1147 const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx);
1148 OS << " {DBGFIELD(\"" << SchedClass.Name << "\") ";
1149 if (SchedClass.Name.size() < 18)
1150 OS.indent(18 - SchedClass.Name.size());
1151 OS << MCDesc.NumMicroOps
1152 << ", " << MCDesc.BeginGroup << ", " << MCDesc.EndGroup
1153 << ", " << format("%2d", MCDesc.WriteProcResIdx)
1154 << ", " << MCDesc.NumWriteProcResEntries
1155 << ", " << format("%2d", MCDesc.WriteLatencyIdx)
1156 << ", " << MCDesc.NumWriteLatencyEntries
1157 << ", " << format("%2d", MCDesc.ReadAdvanceIdx)
1158 << ", " << MCDesc.NumReadAdvanceEntries << "}";
1159 if (SCIdx + 1 < SCEnd)
1161 OS << " // #" << SCIdx << '\n';
1163 OS << "}; // " << PI->ModelName << "SchedClasses\n";
1167 void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) {
1168 // For each processor model.
1169 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
1170 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
1171 // Emit processor resource table.
1172 if (PI->hasInstrSchedModel())
1173 EmitProcessorResources(*PI, OS);
1174 else if(!PI->ProcResourceDefs.empty())
1175 PrintFatalError(PI->ModelDef->getLoc(), "SchedMachineModel defines "
1176 "ProcResources without defining WriteRes SchedWriteRes");
1178 // Begin processor itinerary properties
1180 OS << "static const llvm::MCSchedModel " << PI->ModelName << " = {\n";
1181 EmitProcessorProp(OS, PI->ModelDef, "IssueWidth", ',');
1182 EmitProcessorProp(OS, PI->ModelDef, "MicroOpBufferSize", ',');
1183 EmitProcessorProp(OS, PI->ModelDef, "LoopMicroOpBufferSize", ',');
1184 EmitProcessorProp(OS, PI->ModelDef, "LoadLatency", ',');
1185 EmitProcessorProp(OS, PI->ModelDef, "HighLatency", ',');
1186 EmitProcessorProp(OS, PI->ModelDef, "MispredictPenalty", ',');
1188 OS << " " << (bool)(PI->ModelDef ?
1189 PI->ModelDef->getValueAsBit("PostRAScheduler") : 0)
1190 << ", // " << "PostRAScheduler\n";
1192 OS << " " << (bool)(PI->ModelDef ?
1193 PI->ModelDef->getValueAsBit("CompleteModel") : 0)
1194 << ", // " << "CompleteModel\n";
1196 OS << " " << PI->Index << ", // Processor ID\n";
1197 if (PI->hasInstrSchedModel())
1198 OS << " " << PI->ModelName << "ProcResources" << ",\n"
1199 << " " << PI->ModelName << "SchedClasses" << ",\n"
1200 << " " << PI->ProcResourceDefs.size()+1 << ",\n"
1201 << " " << (SchedModels.schedClassEnd()
1202 - SchedModels.schedClassBegin()) << ",\n";
1204 OS << " 0, 0, 0, 0, // No instruction-level machine model.\n";
1205 if (PI->hasItineraries())
1206 OS << " " << PI->ItinsDef->getName() << "};\n";
1208 OS << " nullptr}; // No Itinerary\n";
1213 // EmitProcessorLookup - generate cpu name to itinerary lookup table.
1215 void SubtargetEmitter::EmitProcessorLookup(raw_ostream &OS) {
1216 // Gather and sort processor information
1217 std::vector<Record*> ProcessorList =
1218 Records.getAllDerivedDefinitions("Processor");
1219 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
1221 // Begin processor table
1223 OS << "// Sorted (by key) array of itineraries for CPU subtype.\n"
1224 << "extern const llvm::SubtargetInfoKV "
1225 << Target << "ProcSchedKV[] = {\n";
1227 // For each processor
1228 for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
1230 Record *Processor = ProcessorList[i];
1232 const std::string &Name = Processor->getValueAsString("Name");
1233 const std::string &ProcModelName =
1234 SchedModels.getModelForProc(Processor).ModelName;
1236 // Emit as { "cpu", procinit },
1237 OS << " { \"" << Name << "\", (const void *)&" << ProcModelName << " }";
1239 // Depending on ''if more in the list'' emit comma
1240 if (++i < N) OS << ",";
1245 // End processor table
1250 // EmitSchedModel - Emits all scheduling model tables, folding common patterns.
1252 void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) {
1253 OS << "#ifdef DBGFIELD\n"
1254 << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n"
1256 << "#ifndef NDEBUG\n"
1257 << "#define DBGFIELD(x) x,\n"
1259 << "#define DBGFIELD(x)\n"
1262 if (SchedModels.hasItineraries()) {
1263 std::vector<std::vector<InstrItinerary> > ProcItinLists;
1264 // Emit the stage data
1265 EmitStageAndOperandCycleData(OS, ProcItinLists);
1266 EmitItineraries(OS, ProcItinLists);
1268 OS << "\n// ===============================================================\n"
1269 << "// Data tables for the new per-operand machine model.\n";
1271 SchedClassTables SchedTables;
1272 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
1273 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
1274 GenSchedClassTables(*PI, SchedTables);
1276 EmitSchedClassTables(SchedTables, OS);
1278 // Emit the processor machine model
1279 EmitProcessorModels(OS);
1280 // Emit the processor lookup data
1281 EmitProcessorLookup(OS);
1283 OS << "#undef DBGFIELD";
1286 void SubtargetEmitter::EmitSchedModelHelpers(std::string ClassName,
1288 OS << "unsigned " << ClassName
1289 << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI,"
1290 << " const TargetSchedModel *SchedModel) const {\n";
1292 std::vector<Record*> Prologs = Records.getAllDerivedDefinitions("PredicateProlog");
1293 std::sort(Prologs.begin(), Prologs.end(), LessRecord());
1294 for (std::vector<Record*>::const_iterator
1295 PI = Prologs.begin(), PE = Prologs.end(); PI != PE; ++PI) {
1296 OS << (*PI)->getValueAsString("Code") << '\n';
1298 IdxVec VariantClasses;
1299 for (CodeGenSchedModels::SchedClassIter SCI = SchedModels.schedClassBegin(),
1300 SCE = SchedModels.schedClassEnd(); SCI != SCE; ++SCI) {
1301 if (SCI->Transitions.empty())
1303 VariantClasses.push_back(SCI->Index);
1305 if (!VariantClasses.empty()) {
1306 OS << " switch (SchedClass) {\n";
1307 for (IdxIter VCI = VariantClasses.begin(), VCE = VariantClasses.end();
1308 VCI != VCE; ++VCI) {
1309 const CodeGenSchedClass &SC = SchedModels.getSchedClass(*VCI);
1310 OS << " case " << *VCI << ": // " << SC.Name << '\n';
1312 for (std::vector<CodeGenSchedTransition>::const_iterator
1313 TI = SC.Transitions.begin(), TE = SC.Transitions.end();
1316 std::set_union(TI->ProcIndices.begin(), TI->ProcIndices.end(),
1317 ProcIndices.begin(), ProcIndices.end(),
1318 std::back_inserter(PI));
1319 ProcIndices.swap(PI);
1321 for (IdxIter PI = ProcIndices.begin(), PE = ProcIndices.end();
1325 OS << "if (SchedModel->getProcessorID() == " << *PI << ") ";
1326 OS << "{ // " << (SchedModels.procModelBegin() + *PI)->ModelName
1328 for (std::vector<CodeGenSchedTransition>::const_iterator
1329 TI = SC.Transitions.begin(), TE = SC.Transitions.end();
1331 if (*PI != 0 && !std::count(TI->ProcIndices.begin(),
1332 TI->ProcIndices.end(), *PI)) {
1336 for (RecIter RI = TI->PredTerm.begin(), RE = TI->PredTerm.end();
1338 if (RI != TI->PredTerm.begin())
1340 OS << "(" << (*RI)->getValueAsString("Predicate") << ")";
1343 << " return " << TI->ToClassIdx << "; // "
1344 << SchedModels.getSchedClass(TI->ToClassIdx).Name << '\n';
1350 if (SC.isInferred())
1351 OS << " return " << SC.Index << ";\n";
1356 OS << " report_fatal_error(\"Expected a variant SchedClass\");\n"
1357 << "} // " << ClassName << "::resolveSchedClass\n";
1361 // ParseFeaturesFunction - Produces a subtarget specific function for parsing
1362 // the subtarget features string.
1364 void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS,
1365 unsigned NumFeatures,
1366 unsigned NumProcs) {
1367 std::vector<Record*> Features =
1368 Records.getAllDerivedDefinitions("SubtargetFeature");
1369 std::sort(Features.begin(), Features.end(), LessRecord());
1371 OS << "// ParseSubtargetFeatures - Parses features string setting specified\n"
1372 << "// subtarget options.\n"
1375 OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef FS) {\n"
1376 << " DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n"
1377 << " DEBUG(dbgs() << \"\\nCPU:\" << CPU << \"\\n\\n\");\n";
1379 if (Features.empty()) {
1384 OS << " InitMCProcessorInfo(CPU, FS);\n"
1385 << " const FeatureBitset& Bits = getFeatureBits();\n";
1387 for (unsigned i = 0; i < Features.size(); i++) {
1389 Record *R = Features[i];
1390 const std::string &Instance = R->getName();
1391 const std::string &Value = R->getValueAsString("Value");
1392 const std::string &Attribute = R->getValueAsString("Attribute");
1394 if (Value=="true" || Value=="false")
1395 OS << " if (Bits[" << Target << "::"
1396 << Instance << "]) "
1397 << Attribute << " = " << Value << ";\n";
1399 OS << " if (Bits[" << Target << "::"
1400 << Instance << "] && "
1401 << Attribute << " < " << Value << ") "
1402 << Attribute << " = " << Value << ";\n";
1409 // SubtargetEmitter::run - Main subtarget enumeration emitter.
1411 void SubtargetEmitter::run(raw_ostream &OS) {
1412 emitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);
1414 OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n";
1415 OS << "#undef GET_SUBTARGETINFO_ENUM\n";
1417 OS << "namespace llvm {\n";
1418 Enumeration(OS, "SubtargetFeature");
1419 OS << "} // End llvm namespace \n";
1420 OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n";
1422 OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n";
1423 OS << "#undef GET_SUBTARGETINFO_MC_DESC\n";
1425 OS << "namespace llvm {\n";
1427 OS << "namespace {\n";
1429 unsigned NumFeatures = FeatureKeyValues(OS);
1431 unsigned NumProcs = CPUKeyValues(OS);
1439 // MCInstrInfo initialization routine.
1440 OS << "static inline void Init" << Target
1441 << "MCSubtargetInfo(MCSubtargetInfo *II, "
1442 << "StringRef TT, StringRef CPU, StringRef FS) {\n";
1443 OS << " II->InitMCSubtargetInfo(TT, CPU, FS, ";
1445 OS << Target << "FeatureKV, ";
1449 OS << Target << "SubTypeKV, ";
1452 OS << '\n'; OS.indent(22);
1453 OS << Target << "ProcSchedKV, "
1454 << Target << "WriteProcResTable, "
1455 << Target << "WriteLatencyTable, "
1456 << Target << "ReadAdvanceTable, ";
1457 if (SchedModels.hasItineraries()) {
1458 OS << '\n'; OS.indent(22);
1459 OS << Target << "Stages, "
1460 << Target << "OperandCycles, "
1461 << Target << "ForwardingPaths";
1466 OS << "} // End llvm namespace \n";
1468 OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n";
1470 OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n";
1471 OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n";
1473 OS << "#include \"llvm/Support/Debug.h\"\n";
1474 ParseFeaturesFunction(OS, NumFeatures, NumProcs);
1476 OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n";
1478 // Create a TargetSubtargetInfo subclass to hide the MC layer initialization.
1479 OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n";
1480 OS << "#undef GET_SUBTARGETINFO_HEADER\n";
1482 std::string ClassName = Target + "GenSubtargetInfo";
1483 OS << "namespace llvm {\n";
1484 OS << "class DFAPacketizer;\n";
1485 OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n"
1486 << " explicit " << ClassName << "(StringRef TT, StringRef CPU, "
1487 << "StringRef FS);\n"
1489 << " unsigned resolveSchedClass(unsigned SchedClass, const MachineInstr *DefMI,"
1490 << " const TargetSchedModel *SchedModel) const override;\n"
1491 << " DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)"
1494 OS << "} // End llvm namespace \n";
1496 OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n";
1498 OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n";
1499 OS << "#undef GET_SUBTARGETINFO_CTOR\n";
1501 OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n";
1502 OS << "namespace llvm {\n";
1503 OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n";
1504 OS << "extern const llvm::SubtargetFeatureKV " << Target << "SubTypeKV[];\n";
1505 OS << "extern const llvm::SubtargetInfoKV " << Target << "ProcSchedKV[];\n";
1506 OS << "extern const llvm::MCWriteProcResEntry "
1507 << Target << "WriteProcResTable[];\n";
1508 OS << "extern const llvm::MCWriteLatencyEntry "
1509 << Target << "WriteLatencyTable[];\n";
1510 OS << "extern const llvm::MCReadAdvanceEntry "
1511 << Target << "ReadAdvanceTable[];\n";
1513 if (SchedModels.hasItineraries()) {
1514 OS << "extern const llvm::InstrStage " << Target << "Stages[];\n";
1515 OS << "extern const unsigned " << Target << "OperandCycles[];\n";
1516 OS << "extern const unsigned " << Target << "ForwardingPaths[];\n";
1519 OS << ClassName << "::" << ClassName << "(StringRef TT, StringRef CPU, "
1520 << "StringRef FS)\n"
1521 << " : TargetSubtargetInfo() {\n"
1522 << " InitMCSubtargetInfo(TT, CPU, FS, ";
1524 OS << "makeArrayRef(" << Target << "FeatureKV, " << NumFeatures << "), ";
1528 OS << "makeArrayRef(" << Target << "SubTypeKV, " << NumProcs << "), ";
1531 OS << '\n'; OS.indent(22);
1532 OS << Target << "ProcSchedKV, "
1533 << Target << "WriteProcResTable, "
1534 << Target << "WriteLatencyTable, "
1535 << Target << "ReadAdvanceTable, ";
1536 OS << '\n'; OS.indent(22);
1537 if (SchedModels.hasItineraries()) {
1538 OS << Target << "Stages, "
1539 << Target << "OperandCycles, "
1540 << Target << "ForwardingPaths";
1545 EmitSchedModelHelpers(ClassName, OS);
1547 OS << "} // End llvm namespace \n";
1549 OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n";
1554 void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) {
1555 CodeGenTarget CGTarget(RK);
1556 SubtargetEmitter(RK, CGTarget).run(OS);
1559 } // End llvm namespace