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 #define DEBUG_TYPE "subtarget-emitter"
16 #include "CodeGenTarget.h"
17 #include "CodeGenSchedule.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/MC/MCInstrItineraries.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
25 #include "llvm/TableGen/TableGenBackend.h"
33 class SubtargetEmitter {
34 // Each processor has a SchedClassDesc table with an entry for each SchedClass.
35 // The SchedClassDesc table indexes into a global write resource table, write
36 // latency table, and read advance table.
37 struct SchedClassTables {
38 std::vector<std::vector<MCSchedClassDesc> > ProcSchedClasses;
39 std::vector<MCWriteProcResEntry> WriteProcResources;
40 std::vector<MCWriteLatencyEntry> WriteLatencies;
41 std::vector<std::string> WriterNames;
42 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries;
44 // Reserve an invalid entry at index 0
46 ProcSchedClasses.resize(1);
47 WriteProcResources.resize(1);
48 WriteLatencies.resize(1);
49 WriterNames.push_back("InvalidWrite");
50 ReadAdvanceEntries.resize(1);
54 struct LessWriteProcResources {
55 bool operator()(const MCWriteProcResEntry &LHS,
56 const MCWriteProcResEntry &RHS) {
57 return LHS.ProcResourceIdx < RHS.ProcResourceIdx;
61 RecordKeeper &Records;
62 CodeGenSchedModels &SchedModels;
65 void Enumeration(raw_ostream &OS, const char *ClassName, bool isBits);
66 unsigned FeatureKeyValues(raw_ostream &OS);
67 unsigned CPUKeyValues(raw_ostream &OS);
68 void FormItineraryStageString(const std::string &Names,
69 Record *ItinData, std::string &ItinString,
71 void FormItineraryOperandCycleString(Record *ItinData, std::string &ItinString,
72 unsigned &NOperandCycles);
73 void FormItineraryBypassString(const std::string &Names,
75 std::string &ItinString, unsigned NOperandCycles);
76 void EmitStageAndOperandCycleData(raw_ostream &OS,
77 std::vector<std::vector<InstrItinerary> >
79 void EmitItineraries(raw_ostream &OS,
80 std::vector<std::vector<InstrItinerary> >
82 void EmitProcessorProp(raw_ostream &OS, const Record *R, const char *Name,
84 void EmitProcessorResources(const CodeGenProcModel &ProcModel,
86 Record *FindWriteResources(const CodeGenSchedRW &SchedWrite,
87 const CodeGenProcModel &ProcModel);
88 Record *FindReadAdvance(const CodeGenSchedRW &SchedRead,
89 const CodeGenProcModel &ProcModel);
90 void ExpandProcResources(RecVec &PRVec, std::vector<int64_t> &Cycles,
91 const CodeGenProcModel &ProcModel);
92 void GenSchedClassTables(const CodeGenProcModel &ProcModel,
93 SchedClassTables &SchedTables);
94 void EmitSchedClassTables(SchedClassTables &SchedTables, raw_ostream &OS);
95 void EmitProcessorModels(raw_ostream &OS);
96 void EmitProcessorLookup(raw_ostream &OS);
97 void EmitSchedModelHelpers(std::string ClassName, raw_ostream &OS);
98 void EmitSchedModel(raw_ostream &OS);
99 void ParseFeaturesFunction(raw_ostream &OS, unsigned NumFeatures,
103 SubtargetEmitter(RecordKeeper &R, CodeGenTarget &TGT):
104 Records(R), SchedModels(TGT.getSchedModels()), Target(TGT.getName()) {}
106 void run(raw_ostream &o);
109 } // End anonymous namespace
112 // Enumeration - Emit the specified class as an enumeration.
114 void SubtargetEmitter::Enumeration(raw_ostream &OS,
115 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();
125 errs() << "Too many (> 64) subtarget features!\n";
129 OS << "namespace " << Target << " {\n";
131 // For bit flag enumerations with more than 32 items, emit constants.
132 // Emit an enum for everything else.
133 if (isBits && N > 32) {
135 for (unsigned i = 0; i < N; i++) {
137 Record *Def = DefList[i];
139 // Get and emit name and expression (1 << i)
140 OS << " const uint64_t " << Def->getName() << " = 1ULL << " << i << ";\n";
147 for (unsigned i = 0; i < N;) {
149 Record *Def = DefList[i];
152 OS << " " << Def->getName();
154 // If bit flags then emit expression (1 << i)
155 if (isBits) OS << " = " << " 1ULL << " << i;
157 // Depending on 'if more in the list' emit comma
158 if (++i < N) OS << ",";
171 // FeatureKeyValues - Emit data of all the subtarget features. Used by the
174 unsigned SubtargetEmitter::FeatureKeyValues(raw_ostream &OS) {
175 // Gather and sort all the features
176 std::vector<Record*> FeatureList =
177 Records.getAllDerivedDefinitions("SubtargetFeature");
179 if (FeatureList.empty())
182 std::sort(FeatureList.begin(), FeatureList.end(), LessRecordFieldName());
184 // Begin feature table
185 OS << "// Sorted (by key) array of values for CPU features.\n"
186 << "extern const llvm::SubtargetFeatureKV " << Target
187 << "FeatureKV[] = {\n";
190 unsigned NumFeatures = 0;
191 for (unsigned i = 0, N = FeatureList.size(); i < N; ++i) {
193 Record *Feature = FeatureList[i];
195 const std::string &Name = Feature->getName();
196 const std::string &CommandLineName = Feature->getValueAsString("Name");
197 const std::string &Desc = Feature->getValueAsString("Desc");
199 if (CommandLineName.empty()) continue;
201 // Emit as { "feature", "description", featureEnum, i1 | i2 | ... | in }
203 << "\"" << CommandLineName << "\", "
204 << "\"" << Desc << "\", "
205 << Target << "::" << Name << ", ";
207 const std::vector<Record*> &ImpliesList =
208 Feature->getValueAsListOfDefs("Implies");
210 if (ImpliesList.empty()) {
213 for (unsigned j = 0, M = ImpliesList.size(); j < M;) {
214 OS << Target << "::" << ImpliesList[j]->getName();
215 if (++j < M) OS << " | ";
222 // Depending on 'if more in the list' emit comma
223 if ((i + 1) < N) OS << ",";
235 // CPUKeyValues - Emit data of all the subtarget processors. Used by command
238 unsigned SubtargetEmitter::CPUKeyValues(raw_ostream &OS) {
239 // Gather and sort processor information
240 std::vector<Record*> ProcessorList =
241 Records.getAllDerivedDefinitions("Processor");
242 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
244 // Begin processor table
245 OS << "// Sorted (by key) array of values for CPU subtype.\n"
246 << "extern const llvm::SubtargetFeatureKV " << Target
247 << "SubTypeKV[] = {\n";
249 // For each processor
250 for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
252 Record *Processor = ProcessorList[i];
254 const std::string &Name = Processor->getValueAsString("Name");
255 const std::vector<Record*> &FeatureList =
256 Processor->getValueAsListOfDefs("Features");
258 // Emit as { "cpu", "description", f1 | f2 | ... fn },
260 << "\"" << Name << "\", "
261 << "\"Select the " << Name << " processor\", ";
263 if (FeatureList.empty()) {
266 for (unsigned j = 0, M = FeatureList.size(); j < M;) {
267 OS << Target << "::" << FeatureList[j]->getName();
268 if (++j < M) OS << " | ";
272 // The "0" is for the "implies" section of this data structure.
275 // Depending on 'if more in the list' emit comma
276 if (++i < N) OS << ",";
281 // End processor table
284 return ProcessorList.size();
288 // FormItineraryStageString - Compose a string containing the stage
289 // data initialization for the specified itinerary. N is the number
292 void SubtargetEmitter::FormItineraryStageString(const std::string &Name,
294 std::string &ItinString,
297 const std::vector<Record*> &StageList =
298 ItinData->getValueAsListOfDefs("Stages");
301 unsigned N = NStages = StageList.size();
302 for (unsigned i = 0; i < N;) {
304 const Record *Stage = StageList[i];
306 // Form string as ,{ cycles, u1 | u2 | ... | un, timeinc, kind }
307 int Cycles = Stage->getValueAsInt("Cycles");
308 ItinString += " { " + itostr(Cycles) + ", ";
311 const std::vector<Record*> &UnitList = Stage->getValueAsListOfDefs("Units");
314 for (unsigned j = 0, M = UnitList.size(); j < M;) {
315 // Add name and bitwise or
316 ItinString += Name + "FU::" + UnitList[j]->getName();
317 if (++j < M) ItinString += " | ";
320 int TimeInc = Stage->getValueAsInt("TimeInc");
321 ItinString += ", " + itostr(TimeInc);
323 int Kind = Stage->getValueAsInt("Kind");
324 ItinString += ", (llvm::InstrStage::ReservationKinds)" + itostr(Kind);
328 if (++i < N) ItinString += ", ";
333 // FormItineraryOperandCycleString - Compose a string containing the
334 // operand cycle initialization for the specified itinerary. N is the
335 // number of operands that has cycles specified.
337 void SubtargetEmitter::FormItineraryOperandCycleString(Record *ItinData,
338 std::string &ItinString, unsigned &NOperandCycles) {
339 // Get operand cycle list
340 const std::vector<int64_t> &OperandCycleList =
341 ItinData->getValueAsListOfInts("OperandCycles");
343 // For each operand cycle
344 unsigned N = NOperandCycles = OperandCycleList.size();
345 for (unsigned i = 0; i < N;) {
346 // Next operand cycle
347 const int OCycle = OperandCycleList[i];
349 ItinString += " " + itostr(OCycle);
350 if (++i < N) ItinString += ", ";
354 void SubtargetEmitter::FormItineraryBypassString(const std::string &Name,
356 std::string &ItinString,
357 unsigned NOperandCycles) {
358 const std::vector<Record*> &BypassList =
359 ItinData->getValueAsListOfDefs("Bypasses");
360 unsigned N = BypassList.size();
363 ItinString += Name + "Bypass::" + BypassList[i]->getName();
364 if (++i < NOperandCycles) ItinString += ", ";
366 for (; i < NOperandCycles;) {
368 if (++i < NOperandCycles) ItinString += ", ";
373 // EmitStageAndOperandCycleData - Generate unique itinerary stages and operand
374 // cycle tables. Create a list of InstrItinerary objects (ProcItinLists) indexed
375 // by CodeGenSchedClass::Index.
377 void SubtargetEmitter::
378 EmitStageAndOperandCycleData(raw_ostream &OS,
379 std::vector<std::vector<InstrItinerary> >
382 // Multiple processor models may share an itinerary record. Emit it once.
383 SmallPtrSet<Record*, 8> ItinsDefSet;
385 // Emit functional units for all the itineraries.
386 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
387 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
389 if (!ItinsDefSet.insert(PI->ItinsDef))
392 std::vector<Record*> FUs = PI->ItinsDef->getValueAsListOfDefs("FU");
396 const std::string &Name = PI->ItinsDef->getName();
397 OS << "\n// Functional units for \"" << Name << "\"\n"
398 << "namespace " << Name << "FU {\n";
400 for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j)
401 OS << " const unsigned " << FUs[j]->getName()
402 << " = 1 << " << j << ";\n";
406 std::vector<Record*> BPs = PI->ItinsDef->getValueAsListOfDefs("BP");
408 OS << "\n// Pipeline forwarding pathes for itineraries \"" << Name
409 << "\"\n" << "namespace " << Name << "Bypass {\n";
411 OS << " const unsigned NoBypass = 0;\n";
412 for (unsigned j = 0, BPN = BPs.size(); j < BPN; ++j)
413 OS << " const unsigned " << BPs[j]->getName()
414 << " = 1 << " << j << ";\n";
420 // Begin stages table
421 std::string StageTable = "\nextern const llvm::InstrStage " + Target +
423 StageTable += " { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n";
425 // Begin operand cycle table
426 std::string OperandCycleTable = "extern const unsigned " + Target +
427 "OperandCycles[] = {\n";
428 OperandCycleTable += " 0, // No itinerary\n";
430 // Begin pipeline bypass table
431 std::string BypassTable = "extern const unsigned " + Target +
432 "ForwardingPaths[] = {\n";
433 BypassTable += " 0, // No itinerary\n";
435 // For each Itinerary across all processors, add a unique entry to the stages,
436 // operand cycles, and pipepine bypess tables. Then add the new Itinerary
437 // object with computed offsets to the ProcItinLists result.
438 unsigned StageCount = 1, OperandCycleCount = 1;
439 std::map<std::string, unsigned> ItinStageMap, ItinOperandMap;
440 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
441 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
442 const CodeGenProcModel &ProcModel = *PI;
444 // Add process itinerary to the list.
445 ProcItinLists.resize(ProcItinLists.size()+1);
447 // If this processor defines no itineraries, then leave the itinerary list
449 std::vector<InstrItinerary> &ItinList = ProcItinLists.back();
450 if (ProcModel.ItinDefList.empty())
453 // Reserve index==0 for NoItinerary.
454 ItinList.resize(SchedModels.numItineraryClasses()+1);
456 const std::string &Name = ProcModel.ItinsDef->getName();
458 // For each itinerary data
459 for (unsigned SchedClassIdx = 0,
460 SchedClassEnd = ProcModel.ItinDefList.size();
461 SchedClassIdx < SchedClassEnd; ++SchedClassIdx) {
463 // Next itinerary data
464 Record *ItinData = ProcModel.ItinDefList[SchedClassIdx];
466 // Get string and stage count
467 std::string ItinStageString;
468 unsigned NStages = 0;
470 FormItineraryStageString(Name, ItinData, ItinStageString, NStages);
472 // Get string and operand cycle count
473 std::string ItinOperandCycleString;
474 unsigned NOperandCycles = 0;
475 std::string ItinBypassString;
477 FormItineraryOperandCycleString(ItinData, ItinOperandCycleString,
480 FormItineraryBypassString(Name, ItinData, ItinBypassString,
484 // Check to see if stage already exists and create if it doesn't
485 unsigned FindStage = 0;
487 FindStage = ItinStageMap[ItinStageString];
488 if (FindStage == 0) {
489 // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // indices
490 StageTable += ItinStageString + ", // " + itostr(StageCount);
492 StageTable += "-" + itostr(StageCount + NStages - 1);
494 // Record Itin class number.
495 ItinStageMap[ItinStageString] = FindStage = StageCount;
496 StageCount += NStages;
500 // Check to see if operand cycle already exists and create if it doesn't
501 unsigned FindOperandCycle = 0;
502 if (NOperandCycles > 0) {
503 std::string ItinOperandString = ItinOperandCycleString+ItinBypassString;
504 FindOperandCycle = ItinOperandMap[ItinOperandString];
505 if (FindOperandCycle == 0) {
506 // Emit as cycle, // index
507 OperandCycleTable += ItinOperandCycleString + ", // ";
508 std::string OperandIdxComment = itostr(OperandCycleCount);
509 if (NOperandCycles > 1)
510 OperandIdxComment += "-"
511 + itostr(OperandCycleCount + NOperandCycles - 1);
512 OperandCycleTable += OperandIdxComment + "\n";
513 // Record Itin class number.
514 ItinOperandMap[ItinOperandCycleString] =
515 FindOperandCycle = OperandCycleCount;
516 // Emit as bypass, // index
517 BypassTable += ItinBypassString + ", // " + OperandIdxComment + "\n";
518 OperandCycleCount += NOperandCycles;
522 // Set up itinerary as location and location + stage count
523 int NumUOps = ItinData ? ItinData->getValueAsInt("NumMicroOps") : 0;
524 InstrItinerary Intinerary = { NumUOps, FindStage, FindStage + NStages,
526 FindOperandCycle + NOperandCycles};
528 // Inject - empty slots will be 0, 0
529 ItinList[SchedClassIdx] = Intinerary;
534 StageTable += " { 0, 0, 0, llvm::InstrStage::Required } // End stages\n";
535 StageTable += "};\n";
537 // Closing operand cycles
538 OperandCycleTable += " 0 // End operand cycles\n";
539 OperandCycleTable += "};\n";
541 BypassTable += " 0 // End bypass tables\n";
542 BypassTable += "};\n";
546 OS << OperandCycleTable;
551 // EmitProcessorData - Generate data for processor itineraries that were
552 // computed during EmitStageAndOperandCycleData(). ProcItinLists lists all
553 // Itineraries for each processor. The Itinerary lists are indexed on
554 // CodeGenSchedClass::Index.
556 void SubtargetEmitter::
557 EmitItineraries(raw_ostream &OS,
558 std::vector<std::vector<InstrItinerary> > &ProcItinLists) {
560 // Multiple processor models may share an itinerary record. Emit it once.
561 SmallPtrSet<Record*, 8> ItinsDefSet;
563 // For each processor's machine model
564 std::vector<std::vector<InstrItinerary> >::iterator
565 ProcItinListsIter = ProcItinLists.begin();
566 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
567 PE = SchedModels.procModelEnd(); PI != PE; ++PI, ++ProcItinListsIter) {
569 Record *ItinsDef = PI->ItinsDef;
570 if (!ItinsDefSet.insert(ItinsDef))
573 // Get processor itinerary name
574 const std::string &Name = ItinsDef->getName();
576 // Get the itinerary list for the processor.
577 assert(ProcItinListsIter != ProcItinLists.end() && "bad iterator");
578 std::vector<InstrItinerary> &ItinList = *ProcItinListsIter;
581 OS << "static const llvm::InstrItinerary ";
582 if (ItinList.empty()) {
583 OS << '*' << Name << " = 0;\n";
587 // Begin processor itinerary table
588 OS << Name << "[] = {\n";
590 // For each itinerary class in CodeGenSchedClass::Index order.
591 for (unsigned j = 0, M = ItinList.size(); j < M; ++j) {
592 InstrItinerary &Intinerary = ItinList[j];
594 // Emit Itinerary in the form of
595 // { firstStage, lastStage, firstCycle, lastCycle } // index
597 Intinerary.NumMicroOps << ", " <<
598 Intinerary.FirstStage << ", " <<
599 Intinerary.LastStage << ", " <<
600 Intinerary.FirstOperandCycle << ", " <<
601 Intinerary.LastOperandCycle << " }" <<
602 ", // " << j << " " << SchedModels.getSchedClass(j).Name << "\n";
604 // End processor itinerary table
605 OS << " { 0, ~0U, ~0U, ~0U, ~0U } // end marker\n";
610 // Emit either the value defined in the TableGen Record, or the default
611 // value defined in the C++ header. The Record is null if the processor does not
613 void SubtargetEmitter::EmitProcessorProp(raw_ostream &OS, const Record *R,
614 const char *Name, char Separator) {
616 int V = R ? R->getValueAsInt(Name) : -1;
618 OS << V << Separator << " // " << Name;
620 OS << "MCSchedModel::Default" << Name << Separator;
624 void SubtargetEmitter::EmitProcessorResources(const CodeGenProcModel &ProcModel,
626 char Sep = ProcModel.ProcResourceDefs.empty() ? ' ' : ',';
628 OS << "\n// {Name, NumUnits, SuperIdx, IsBuffered}\n";
629 OS << "static const llvm::MCProcResourceDesc "
630 << ProcModel.ModelName << "ProcResources" << "[] = {\n"
631 << " {DBGFIELD(\"InvalidUnit\") 0, 0, 0}" << Sep << "\n";
633 for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) {
634 Record *PRDef = ProcModel.ProcResourceDefs[i];
636 Record *SuperDef = 0;
637 unsigned SuperIdx = 0;
638 unsigned NumUnits = 0;
639 bool IsBuffered = true;
640 if (PRDef->isSubClassOf("ProcResGroup")) {
641 RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources");
642 for (RecIter RUI = ResUnits.begin(), RUE = ResUnits.end();
645 IsBuffered = (*RUI)->getValueAsBit("Buffered");
646 else if(IsBuffered != (*RUI)->getValueAsBit("Buffered"))
647 PrintFatalError(PRDef->getLoc(),
648 "Mixing buffered and unbuffered resources.");
649 NumUnits += (*RUI)->getValueAsInt("NumUnits");
654 if (PRDef->getValueInit("Super")->isComplete()) {
655 SuperDef = SchedModels.findProcResUnits(
656 PRDef->getValueAsDef("Super"), ProcModel);
657 SuperIdx = ProcModel.getProcResourceIdx(SuperDef);
659 NumUnits = PRDef->getValueAsInt("NumUnits");
660 IsBuffered = PRDef->getValueAsBit("Buffered");
662 // Emit the ProcResourceDesc
665 OS << " {DBGFIELD(\"" << PRDef->getName() << "\") ";
666 if (PRDef->getName().size() < 15)
667 OS.indent(15 - PRDef->getName().size());
668 OS << NumUnits << ", " << SuperIdx << ", "
669 << IsBuffered << "}" << Sep << " // #" << i+1;
671 OS << ", Super=" << SuperDef->getName();
677 // Find the WriteRes Record that defines processor resources for this
679 Record *SubtargetEmitter::FindWriteResources(
680 const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) {
682 // Check if the SchedWrite is already subtarget-specific and directly
683 // specifies a set of processor resources.
684 if (SchedWrite.TheDef->isSubClassOf("SchedWriteRes"))
685 return SchedWrite.TheDef;
687 Record *AliasDef = 0;
688 for (RecIter AI = SchedWrite.Aliases.begin(), AE = SchedWrite.Aliases.end();
690 const CodeGenSchedRW &AliasRW =
691 SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
692 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
693 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
694 if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
698 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
699 "defined for processor " + ProcModel.ModelName +
700 " Ensure only one SchedAlias exists per RW.");
701 AliasDef = AliasRW.TheDef;
703 if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes"))
706 // Check this processor's list of write resources.
708 for (RecIter WRI = ProcModel.WriteResDefs.begin(),
709 WRE = ProcModel.WriteResDefs.end(); WRI != WRE; ++WRI) {
710 if (!(*WRI)->isSubClassOf("WriteRes"))
712 if (AliasDef == (*WRI)->getValueAsDef("WriteType")
713 || SchedWrite.TheDef == (*WRI)->getValueAsDef("WriteType")) {
715 PrintFatalError((*WRI)->getLoc(), "Resources are defined for both "
716 "SchedWrite and its alias on processor " +
717 ProcModel.ModelName);
722 // TODO: If ProcModel has a base model (previous generation processor),
723 // then call FindWriteResources recursively with that model here.
725 PrintFatalError(ProcModel.ModelDef->getLoc(),
726 std::string("Processor does not define resources for ")
727 + SchedWrite.TheDef->getName());
732 /// Find the ReadAdvance record for the given SchedRead on this processor or
734 Record *SubtargetEmitter::FindReadAdvance(const CodeGenSchedRW &SchedRead,
735 const CodeGenProcModel &ProcModel) {
736 // Check for SchedReads that directly specify a ReadAdvance.
737 if (SchedRead.TheDef->isSubClassOf("SchedReadAdvance"))
738 return SchedRead.TheDef;
740 // Check this processor's list of aliases for SchedRead.
741 Record *AliasDef = 0;
742 for (RecIter AI = SchedRead.Aliases.begin(), AE = SchedRead.Aliases.end();
744 const CodeGenSchedRW &AliasRW =
745 SchedModels.getSchedRW((*AI)->getValueAsDef("AliasRW"));
746 if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
747 Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
748 if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
752 PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
753 "defined for processor " + ProcModel.ModelName +
754 " Ensure only one SchedAlias exists per RW.");
755 AliasDef = AliasRW.TheDef;
757 if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance"))
760 // Check this processor's ReadAdvanceList.
762 for (RecIter RAI = ProcModel.ReadAdvanceDefs.begin(),
763 RAE = ProcModel.ReadAdvanceDefs.end(); RAI != RAE; ++RAI) {
764 if (!(*RAI)->isSubClassOf("ReadAdvance"))
766 if (AliasDef == (*RAI)->getValueAsDef("ReadType")
767 || SchedRead.TheDef == (*RAI)->getValueAsDef("ReadType")) {
769 PrintFatalError((*RAI)->getLoc(), "Resources are defined for both "
770 "SchedRead and its alias on processor " +
771 ProcModel.ModelName);
776 // TODO: If ProcModel has a base model (previous generation processor),
777 // then call FindReadAdvance recursively with that model here.
778 if (!ResDef && SchedRead.TheDef->getName() != "ReadDefault") {
779 PrintFatalError(ProcModel.ModelDef->getLoc(),
780 std::string("Processor does not define resources for ")
781 + SchedRead.TheDef->getName());
786 // Expand an explicit list of processor resources into a full list of implied
787 // resource groups that cover them.
789 // FIXME: Effectively consider a super-resource a group that include all of its
790 // subresources to allow mixing and matching super-resources and groups.
792 // FIXME: Warn if two overlapping groups don't have a common supergroup.
793 void SubtargetEmitter::ExpandProcResources(RecVec &PRVec,
794 std::vector<int64_t> &Cycles,
795 const CodeGenProcModel &ProcModel) {
796 // Default to 1 resource cycle.
797 Cycles.resize(PRVec.size(), 1);
798 for (unsigned i = 0, e = PRVec.size(); i != e; ++i) {
800 if (PRVec[i]->isSubClassOf("ProcResGroup")) {
801 SubResources = PRVec[i]->getValueAsListOfDefs("Resources");
802 std::sort(SubResources.begin(), SubResources.end(), LessRecord());
805 SubResources.push_back(PRVec[i]);
807 for (RecIter PRI = ProcModel.ProcResourceDefs.begin(),
808 PRE = ProcModel.ProcResourceDefs.end();
810 if (*PRI == PRVec[i] || !(*PRI)->isSubClassOf("ProcResGroup"))
812 RecVec SuperResources = (*PRI)->getValueAsListOfDefs("Resources");
813 std::sort(SuperResources.begin(), SuperResources.end(), LessRecord());
814 RecIter SubI = SubResources.begin(), SubE = SubResources.end();
815 RecIter SuperI = SuperResources.begin(), SuperE = SuperResources.end();
816 for ( ; SubI != SubE && SuperI != SuperE; ++SuperI) {
819 else if (*SuperI < *SubI)
824 PRVec.push_back(*PRI);
825 Cycles.push_back(Cycles[i]);
831 // Generate the SchedClass table for this processor and update global
832 // tables. Must be called for each processor in order.
833 void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel,
834 SchedClassTables &SchedTables) {
835 SchedTables.ProcSchedClasses.resize(SchedTables.ProcSchedClasses.size() + 1);
836 if (!ProcModel.hasInstrSchedModel())
839 std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back();
840 for (CodeGenSchedModels::SchedClassIter SCI = SchedModels.schedClassBegin(),
841 SCE = SchedModels.schedClassEnd(); SCI != SCE; ++SCI) {
842 DEBUG(SCI->dump(&SchedModels));
844 SCTab.resize(SCTab.size() + 1);
845 MCSchedClassDesc &SCDesc = SCTab.back();
846 // SCDesc.Name is guarded by NDEBUG
847 SCDesc.NumMicroOps = 0;
848 SCDesc.BeginGroup = false;
849 SCDesc.EndGroup = false;
850 SCDesc.WriteProcResIdx = 0;
851 SCDesc.WriteLatencyIdx = 0;
852 SCDesc.ReadAdvanceIdx = 0;
854 // A Variant SchedClass has no resources of its own.
855 if (!SCI->Transitions.empty()) {
856 SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps;
860 // Determine if the SchedClass is actually reachable on this processor. If
861 // not don't try to locate the processor resources, it will fail.
862 // If ProcIndices contains 0, this class applies to all processors.
863 assert(!SCI->ProcIndices.empty() && "expect at least one procidx");
864 if (SCI->ProcIndices[0] != 0) {
865 IdxIter PIPos = std::find(SCI->ProcIndices.begin(),
866 SCI->ProcIndices.end(), ProcModel.Index);
867 if (PIPos == SCI->ProcIndices.end())
870 IdxVec Writes = SCI->Writes;
871 IdxVec Reads = SCI->Reads;
872 if (SCI->ItinClassDef) {
873 assert(SCI->InstRWs.empty() && "ItinClass should not have InstRWs");
874 // Check this processor's itinerary class resources.
875 for (RecIter II = ProcModel.ItinRWDefs.begin(),
876 IE = ProcModel.ItinRWDefs.end(); II != IE; ++II) {
877 RecVec Matched = (*II)->getValueAsListOfDefs("MatchedItinClasses");
878 if (std::find(Matched.begin(), Matched.end(), SCI->ItinClassDef)
880 SchedModels.findRWs((*II)->getValueAsListOfDefs("OperandReadWrites"),
885 if (Writes.empty()) {
886 DEBUG(dbgs() << ProcModel.ModelName
887 << " does not have resources for itinerary class "
888 << SCI->ItinClassDef->getName() << '\n');
891 else if (!SCI->InstRWs.empty()) {
892 // This class may have a default ReadWrite list which can be overriden by
893 // InstRW definitions.
895 for (RecIter RWI = SCI->InstRWs.begin(), RWE = SCI->InstRWs.end();
897 Record *RWModelDef = (*RWI)->getValueAsDef("SchedModel");
898 if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) {
906 SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
910 // Sum resources across all operand writes.
911 std::vector<MCWriteProcResEntry> WriteProcResources;
912 std::vector<MCWriteLatencyEntry> WriteLatencies;
913 std::vector<std::string> WriterNames;
914 std::vector<MCReadAdvanceEntry> ReadAdvanceEntries;
915 for (IdxIter WI = Writes.begin(), WE = Writes.end(); WI != WE; ++WI) {
917 SchedModels.expandRWSeqForProc(*WI, WriteSeq, /*IsRead=*/false,
920 // For each operand, create a latency entry.
921 MCWriteLatencyEntry WLEntry;
923 unsigned WriteID = WriteSeq.back();
924 WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name);
925 // If this Write is not referenced by a ReadAdvance, don't distinguish it
926 // from other WriteLatency entries.
927 if (!SchedModels.hasReadOfWrite(SchedModels.getSchedWrite(WriteID).TheDef)) {
930 WLEntry.WriteResourceID = WriteID;
932 for (IdxIter WSI = WriteSeq.begin(), WSE = WriteSeq.end();
936 FindWriteResources(SchedModels.getSchedWrite(*WSI), ProcModel);
938 // Mark the parent class as invalid for unsupported write types.
939 if (WriteRes->getValueAsBit("Unsupported")) {
940 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
943 WLEntry.Cycles += WriteRes->getValueAsInt("Latency");
944 SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps");
945 SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup");
946 SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup");
948 // Create an entry for each ProcResource listed in WriteRes.
949 RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources");
950 std::vector<int64_t> Cycles =
951 WriteRes->getValueAsListOfInts("ResourceCycles");
953 ExpandProcResources(PRVec, Cycles, ProcModel);
955 for (unsigned PRIdx = 0, PREnd = PRVec.size();
956 PRIdx != PREnd; ++PRIdx) {
957 MCWriteProcResEntry WPREntry;
958 WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]);
959 assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx");
960 WPREntry.Cycles = Cycles[PRIdx];
961 // If this resource is already used in this sequence, add the current
962 // entry's cycles so that the same resource appears to be used
963 // serially, rather than multiple parallel uses. This is important for
964 // in-order machine where the resource consumption is a hazard.
965 unsigned WPRIdx = 0, WPREnd = WriteProcResources.size();
966 for( ; WPRIdx != WPREnd; ++WPRIdx) {
967 if (WriteProcResources[WPRIdx].ProcResourceIdx
968 == WPREntry.ProcResourceIdx) {
969 WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles;
973 if (WPRIdx == WPREnd)
974 WriteProcResources.push_back(WPREntry);
977 WriteLatencies.push_back(WLEntry);
979 // Create an entry for each operand Read in this SchedClass.
980 // Entries must be sorted first by UseIdx then by WriteResourceID.
981 for (unsigned UseIdx = 0, EndIdx = Reads.size();
982 UseIdx != EndIdx; ++UseIdx) {
983 Record *ReadAdvance =
984 FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel);
988 // Mark the parent class as invalid for unsupported write types.
989 if (ReadAdvance->getValueAsBit("Unsupported")) {
990 SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
993 RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites");
995 if (ValidWrites.empty())
996 WriteIDs.push_back(0);
998 for (RecIter VWI = ValidWrites.begin(), VWE = ValidWrites.end();
1000 WriteIDs.push_back(SchedModels.getSchedRWIdx(*VWI, /*IsRead=*/false));
1003 std::sort(WriteIDs.begin(), WriteIDs.end());
1004 for(IdxIter WI = WriteIDs.begin(), WE = WriteIDs.end(); WI != WE; ++WI) {
1005 MCReadAdvanceEntry RAEntry;
1006 RAEntry.UseIdx = UseIdx;
1007 RAEntry.WriteResourceID = *WI;
1008 RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles");
1009 ReadAdvanceEntries.push_back(RAEntry);
1012 if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) {
1013 WriteProcResources.clear();
1014 WriteLatencies.clear();
1015 ReadAdvanceEntries.clear();
1017 // Add the information for this SchedClass to the global tables using basic
1020 // WritePrecRes entries are sorted by ProcResIdx.
1021 std::sort(WriteProcResources.begin(), WriteProcResources.end(),
1022 LessWriteProcResources());
1024 SCDesc.NumWriteProcResEntries = WriteProcResources.size();
1025 std::vector<MCWriteProcResEntry>::iterator WPRPos =
1026 std::search(SchedTables.WriteProcResources.begin(),
1027 SchedTables.WriteProcResources.end(),
1028 WriteProcResources.begin(), WriteProcResources.end());
1029 if (WPRPos != SchedTables.WriteProcResources.end())
1030 SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin();
1032 SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size();
1033 SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(),
1034 WriteProcResources.end());
1036 // Latency entries must remain in operand order.
1037 SCDesc.NumWriteLatencyEntries = WriteLatencies.size();
1038 std::vector<MCWriteLatencyEntry>::iterator WLPos =
1039 std::search(SchedTables.WriteLatencies.begin(),
1040 SchedTables.WriteLatencies.end(),
1041 WriteLatencies.begin(), WriteLatencies.end());
1042 if (WLPos != SchedTables.WriteLatencies.end()) {
1043 unsigned idx = WLPos - SchedTables.WriteLatencies.begin();
1044 SCDesc.WriteLatencyIdx = idx;
1045 for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i)
1046 if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) ==
1047 std::string::npos) {
1048 SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i];
1052 SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size();
1053 SchedTables.WriteLatencies.insert(SchedTables.WriteLatencies.end(),
1054 WriteLatencies.begin(),
1055 WriteLatencies.end());
1056 SchedTables.WriterNames.insert(SchedTables.WriterNames.end(),
1057 WriterNames.begin(), WriterNames.end());
1059 // ReadAdvanceEntries must remain in operand order.
1060 SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size();
1061 std::vector<MCReadAdvanceEntry>::iterator RAPos =
1062 std::search(SchedTables.ReadAdvanceEntries.begin(),
1063 SchedTables.ReadAdvanceEntries.end(),
1064 ReadAdvanceEntries.begin(), ReadAdvanceEntries.end());
1065 if (RAPos != SchedTables.ReadAdvanceEntries.end())
1066 SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin();
1068 SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size();
1069 SchedTables.ReadAdvanceEntries.insert(RAPos, ReadAdvanceEntries.begin(),
1070 ReadAdvanceEntries.end());
1075 // Emit SchedClass tables for all processors and associated global tables.
1076 void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables,
1078 // Emit global WriteProcResTable.
1079 OS << "\n// {ProcResourceIdx, Cycles}\n"
1080 << "extern const llvm::MCWriteProcResEntry "
1081 << Target << "WriteProcResTable[] = {\n"
1082 << " { 0, 0}, // Invalid\n";
1083 for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size();
1084 WPRIdx != WPREnd; ++WPRIdx) {
1085 MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx];
1086 OS << " {" << format("%2d", WPREntry.ProcResourceIdx) << ", "
1087 << format("%2d", WPREntry.Cycles) << "}";
1088 if (WPRIdx + 1 < WPREnd)
1090 OS << " // #" << WPRIdx << '\n';
1092 OS << "}; // " << Target << "WriteProcResTable\n";
1094 // Emit global WriteLatencyTable.
1095 OS << "\n// {Cycles, WriteResourceID}\n"
1096 << "extern const llvm::MCWriteLatencyEntry "
1097 << Target << "WriteLatencyTable[] = {\n"
1098 << " { 0, 0}, // Invalid\n";
1099 for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size();
1100 WLIdx != WLEnd; ++WLIdx) {
1101 MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx];
1102 OS << " {" << format("%2d", WLEntry.Cycles) << ", "
1103 << format("%2d", WLEntry.WriteResourceID) << "}";
1104 if (WLIdx + 1 < WLEnd)
1106 OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n';
1108 OS << "}; // " << Target << "WriteLatencyTable\n";
1110 // Emit global ReadAdvanceTable.
1111 OS << "\n// {UseIdx, WriteResourceID, Cycles}\n"
1112 << "extern const llvm::MCReadAdvanceEntry "
1113 << Target << "ReadAdvanceTable[] = {\n"
1114 << " {0, 0, 0}, // Invalid\n";
1115 for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size();
1116 RAIdx != RAEnd; ++RAIdx) {
1117 MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx];
1118 OS << " {" << RAEntry.UseIdx << ", "
1119 << format("%2d", RAEntry.WriteResourceID) << ", "
1120 << format("%2d", RAEntry.Cycles) << "}";
1121 if (RAIdx + 1 < RAEnd)
1123 OS << " // #" << RAIdx << '\n';
1125 OS << "}; // " << Target << "ReadAdvanceTable\n";
1127 // Emit a SchedClass table for each processor.
1128 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
1129 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
1130 if (!PI->hasInstrSchedModel())
1133 std::vector<MCSchedClassDesc> &SCTab =
1134 SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())];
1136 OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup,"
1137 << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n";
1138 OS << "static const llvm::MCSchedClassDesc "
1139 << PI->ModelName << "SchedClasses[] = {\n";
1141 // The first class is always invalid. We no way to distinguish it except by
1142 // name and position.
1143 assert(SchedModels.getSchedClass(0).Name == "NoItinerary"
1144 && "invalid class not first");
1145 OS << " {DBGFIELD(\"InvalidSchedClass\") "
1146 << MCSchedClassDesc::InvalidNumMicroOps
1147 << ", 0, 0, 0, 0, 0, 0, 0, 0},\n";
1149 for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) {
1150 MCSchedClassDesc &MCDesc = SCTab[SCIdx];
1151 const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx);
1152 OS << " {DBGFIELD(\"" << SchedClass.Name << "\") ";
1153 if (SchedClass.Name.size() < 18)
1154 OS.indent(18 - SchedClass.Name.size());
1155 OS << MCDesc.NumMicroOps
1156 << ", " << MCDesc.BeginGroup << ", " << MCDesc.EndGroup
1157 << ", " << format("%2d", MCDesc.WriteProcResIdx)
1158 << ", " << MCDesc.NumWriteProcResEntries
1159 << ", " << format("%2d", MCDesc.WriteLatencyIdx)
1160 << ", " << MCDesc.NumWriteLatencyEntries
1161 << ", " << format("%2d", MCDesc.ReadAdvanceIdx)
1162 << ", " << MCDesc.NumReadAdvanceEntries << "}";
1163 if (SCIdx + 1 < SCEnd)
1165 OS << " // #" << SCIdx << '\n';
1167 OS << "}; // " << PI->ModelName << "SchedClasses\n";
1171 void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) {
1172 // For each processor model.
1173 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
1174 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
1175 // Emit processor resource table.
1176 if (PI->hasInstrSchedModel())
1177 EmitProcessorResources(*PI, OS);
1178 else if(!PI->ProcResourceDefs.empty())
1179 PrintFatalError(PI->ModelDef->getLoc(), "SchedMachineModel defines "
1180 "ProcResources without defining WriteRes SchedWriteRes");
1182 // Begin processor itinerary properties
1184 OS << "static const llvm::MCSchedModel " << PI->ModelName << "(\n";
1185 EmitProcessorProp(OS, PI->ModelDef, "IssueWidth", ',');
1186 EmitProcessorProp(OS, PI->ModelDef, "MinLatency", ',');
1187 EmitProcessorProp(OS, PI->ModelDef, "LoadLatency", ',');
1188 EmitProcessorProp(OS, PI->ModelDef, "HighLatency", ',');
1189 EmitProcessorProp(OS, PI->ModelDef, "ILPWindow", ',');
1190 EmitProcessorProp(OS, PI->ModelDef, "MispredictPenalty", ',');
1191 OS << " " << PI->Index << ", // Processor ID\n";
1192 if (PI->hasInstrSchedModel())
1193 OS << " " << PI->ModelName << "ProcResources" << ",\n"
1194 << " " << PI->ModelName << "SchedClasses" << ",\n"
1195 << " " << PI->ProcResourceDefs.size()+1 << ",\n"
1196 << " " << (SchedModels.schedClassEnd()
1197 - SchedModels.schedClassBegin()) << ",\n";
1199 OS << " 0, 0, 0, 0, // No instruction-level machine model.\n";
1200 if (SchedModels.hasItineraryClasses())
1201 OS << " " << PI->ItinsDef->getName() << ");\n";
1203 OS << " 0); // No Itinerary\n";
1208 // EmitProcessorLookup - generate cpu name to itinerary lookup table.
1210 void SubtargetEmitter::EmitProcessorLookup(raw_ostream &OS) {
1211 // Gather and sort processor information
1212 std::vector<Record*> ProcessorList =
1213 Records.getAllDerivedDefinitions("Processor");
1214 std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
1216 // Begin processor table
1218 OS << "// Sorted (by key) array of itineraries for CPU subtype.\n"
1219 << "extern const llvm::SubtargetInfoKV "
1220 << Target << "ProcSchedKV[] = {\n";
1222 // For each processor
1223 for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
1225 Record *Processor = ProcessorList[i];
1227 const std::string &Name = Processor->getValueAsString("Name");
1228 const std::string &ProcModelName =
1229 SchedModels.getModelForProc(Processor).ModelName;
1231 // Emit as { "cpu", procinit },
1232 OS << " { \"" << Name << "\", (const void *)&" << ProcModelName << " }";
1234 // Depending on ''if more in the list'' emit comma
1235 if (++i < N) OS << ",";
1240 // End processor table
1245 // EmitSchedModel - Emits all scheduling model tables, folding common patterns.
1247 void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) {
1248 OS << "#ifdef DBGFIELD\n"
1249 << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n"
1251 << "#ifndef NDEBUG\n"
1252 << "#define DBGFIELD(x) x,\n"
1254 << "#define DBGFIELD(x)\n"
1257 if (SchedModels.hasItineraryClasses()) {
1258 std::vector<std::vector<InstrItinerary> > ProcItinLists;
1259 // Emit the stage data
1260 EmitStageAndOperandCycleData(OS, ProcItinLists);
1261 EmitItineraries(OS, ProcItinLists);
1263 OS << "\n// ===============================================================\n"
1264 << "// Data tables for the new per-operand machine model.\n";
1266 SchedClassTables SchedTables;
1267 for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
1268 PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
1269 GenSchedClassTables(*PI, SchedTables);
1271 EmitSchedClassTables(SchedTables, OS);
1273 // Emit the processor machine model
1274 EmitProcessorModels(OS);
1275 // Emit the processor lookup data
1276 EmitProcessorLookup(OS);
1278 OS << "#undef DBGFIELD";
1281 void SubtargetEmitter::EmitSchedModelHelpers(std::string ClassName,
1283 OS << "unsigned " << ClassName
1284 << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI,"
1285 << " const TargetSchedModel *SchedModel) const {\n";
1287 std::vector<Record*> Prologs = Records.getAllDerivedDefinitions("PredicateProlog");
1288 std::sort(Prologs.begin(), Prologs.end(), LessRecord());
1289 for (std::vector<Record*>::const_iterator
1290 PI = Prologs.begin(), PE = Prologs.end(); PI != PE; ++PI) {
1291 OS << (*PI)->getValueAsString("Code") << '\n';
1293 IdxVec VariantClasses;
1294 for (CodeGenSchedModels::SchedClassIter SCI = SchedModels.schedClassBegin(),
1295 SCE = SchedModels.schedClassEnd(); SCI != SCE; ++SCI) {
1296 if (SCI->Transitions.empty())
1298 VariantClasses.push_back(SCI - SchedModels.schedClassBegin());
1300 if (!VariantClasses.empty()) {
1301 OS << " switch (SchedClass) {\n";
1302 for (IdxIter VCI = VariantClasses.begin(), VCE = VariantClasses.end();
1303 VCI != VCE; ++VCI) {
1304 const CodeGenSchedClass &SC = SchedModels.getSchedClass(*VCI);
1305 OS << " case " << *VCI << ": // " << SC.Name << '\n';
1307 for (std::vector<CodeGenSchedTransition>::const_iterator
1308 TI = SC.Transitions.begin(), TE = SC.Transitions.end();
1311 std::set_union(TI->ProcIndices.begin(), TI->ProcIndices.end(),
1312 ProcIndices.begin(), ProcIndices.end(),
1313 std::back_inserter(PI));
1314 ProcIndices.swap(PI);
1316 for (IdxIter PI = ProcIndices.begin(), PE = ProcIndices.end();
1320 OS << "if (SchedModel->getProcessorID() == " << *PI << ") ";
1321 OS << "{ // " << (SchedModels.procModelBegin() + *PI)->ModelName
1323 for (std::vector<CodeGenSchedTransition>::const_iterator
1324 TI = SC.Transitions.begin(), TE = SC.Transitions.end();
1327 if (*PI != 0 && !std::count(TI->ProcIndices.begin(),
1328 TI->ProcIndices.end(), *PI)) {
1331 for (RecIter RI = TI->PredTerm.begin(), RE = TI->PredTerm.end();
1333 if (RI != TI->PredTerm.begin())
1335 OS << "(" << (*RI)->getValueAsString("Predicate") << ")";
1338 << " return " << TI->ToClassIdx << "; // "
1339 << SchedModels.getSchedClass(TI->ToClassIdx).Name << '\n';
1346 if (SC.ItinClassDef)
1347 SCIdx = SchedModels.getSchedClassIdxForItin(SC.ItinClassDef);
1349 SCIdx = SchedModels.findSchedClassIdx(SC.Writes, SC.Reads);
1351 OS << " return " << SCIdx << ";\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 << " uint64_t 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 << ") != 0) "
1397 << Attribute << " = " << Value << ";\n";
1399 OS << " if ((Bits & " << Target << "::"
1400 << Instance << ") != 0 && "
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", true);
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.hasItineraryClasses()) {
1458 OS << '\n'; OS.indent(22);
1459 OS << Target << "Stages, "
1460 << Target << "OperandCycles, "
1461 << Target << "ForwardingPaths, ";
1464 OS << NumFeatures << ", " << NumProcs << ");\n}\n\n";
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 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
1475 ParseFeaturesFunction(OS, NumFeatures, NumProcs);
1477 OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n";
1479 // Create a TargetSubtargetInfo subclass to hide the MC layer initialization.
1480 OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n";
1481 OS << "#undef GET_SUBTARGETINFO_HEADER\n";
1483 std::string ClassName = Target + "GenSubtargetInfo";
1484 OS << "namespace llvm {\n";
1485 OS << "class DFAPacketizer;\n";
1486 OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n"
1487 << " explicit " << ClassName << "(StringRef TT, StringRef CPU, "
1488 << "StringRef FS);\n"
1490 << " unsigned resolveSchedClass(unsigned SchedClass, const MachineInstr *DefMI,"
1491 << " const TargetSchedModel *SchedModel) const;\n"
1492 << " DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)"
1495 OS << "} // End llvm namespace \n";
1497 OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n";
1499 OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n";
1500 OS << "#undef GET_SUBTARGETINFO_CTOR\n";
1502 OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n";
1503 OS << "namespace llvm {\n";
1504 OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n";
1505 OS << "extern const llvm::SubtargetFeatureKV " << Target << "SubTypeKV[];\n";
1506 OS << "extern const llvm::SubtargetInfoKV " << Target << "ProcSchedKV[];\n";
1507 OS << "extern const llvm::MCWriteProcResEntry "
1508 << Target << "WriteProcResTable[];\n";
1509 OS << "extern const llvm::MCWriteLatencyEntry "
1510 << Target << "WriteLatencyTable[];\n";
1511 OS << "extern const llvm::MCReadAdvanceEntry "
1512 << Target << "ReadAdvanceTable[];\n";
1514 if (SchedModels.hasItineraryClasses()) {
1515 OS << "extern const llvm::InstrStage " << Target << "Stages[];\n";
1516 OS << "extern const unsigned " << Target << "OperandCycles[];\n";
1517 OS << "extern const unsigned " << Target << "ForwardingPaths[];\n";
1520 OS << ClassName << "::" << ClassName << "(StringRef TT, StringRef CPU, "
1521 << "StringRef FS)\n"
1522 << " : TargetSubtargetInfo() {\n"
1523 << " InitMCSubtargetInfo(TT, CPU, FS, ";
1525 OS << Target << "FeatureKV, ";
1529 OS << Target << "SubTypeKV, ";
1532 OS << '\n'; OS.indent(22);
1533 OS << Target << "ProcSchedKV, "
1534 << Target << "WriteProcResTable, "
1535 << Target << "WriteLatencyTable, "
1536 << Target << "ReadAdvanceTable, ";
1537 OS << '\n'; OS.indent(22);
1538 if (SchedModels.hasItineraryClasses()) {
1539 OS << Target << "Stages, "
1540 << Target << "OperandCycles, "
1541 << Target << "ForwardingPaths, ";
1544 OS << NumFeatures << ", " << NumProcs << ");\n}\n\n";
1546 EmitSchedModelHelpers(ClassName, OS);
1548 OS << "} // End llvm namespace \n";
1550 OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n";
1555 void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) {
1556 CodeGenTarget CGTarget(RK);
1557 SubtargetEmitter(RK, CGTarget).run(OS);
1560 } // End llvm namespace