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