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