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