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