]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/utils/TableGen/SubtargetEmitter.cpp
MFV r337210: 9577 remove zfs_dbuf_evict_key tsd
[FreeBSD/FreeBSD.git] / contrib / llvm / utils / TableGen / SubtargetEmitter.cpp
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 =
605             SchedModels.findProcResUnits(PRDef->getValueAsDef("Super"),
606                                          ProcModel, PRDef->getLoc());
607         SuperIdx = ProcModel.getProcResourceIdx(SuperDef);
608       }
609       NumUnits = PRDef->getValueAsInt("NumUnits");
610     }
611     // Emit the ProcResourceDesc
612     OS << "  {DBGFIELD(\"" << PRDef->getName() << "\") ";
613     if (PRDef->getName().size() < 15)
614       OS.indent(15 - PRDef->getName().size());
615     OS << NumUnits << ", " << SuperIdx << ", "
616        << BufferSize << "}, // #" << i+1;
617     if (SuperDef)
618       OS << ", Super=" << SuperDef->getName();
619     OS << "\n";
620   }
621   OS << "};\n";
622 }
623
624 // Find the WriteRes Record that defines processor resources for this
625 // SchedWrite.
626 Record *SubtargetEmitter::FindWriteResources(
627   const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) {
628
629   // Check if the SchedWrite is already subtarget-specific and directly
630   // specifies a set of processor resources.
631   if (SchedWrite.TheDef->isSubClassOf("SchedWriteRes"))
632     return SchedWrite.TheDef;
633
634   Record *AliasDef = nullptr;
635   for (Record *A : SchedWrite.Aliases) {
636     const CodeGenSchedRW &AliasRW =
637       SchedModels.getSchedRW(A->getValueAsDef("AliasRW"));
638     if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
639       Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
640       if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
641         continue;
642     }
643     if (AliasDef)
644       PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
645                     "defined for processor " + ProcModel.ModelName +
646                     " Ensure only one SchedAlias exists per RW.");
647     AliasDef = AliasRW.TheDef;
648   }
649   if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes"))
650     return AliasDef;
651
652   // Check this processor's list of write resources.
653   Record *ResDef = nullptr;
654   for (Record *WR : ProcModel.WriteResDefs) {
655     if (!WR->isSubClassOf("WriteRes"))
656       continue;
657     if (AliasDef == WR->getValueAsDef("WriteType")
658         || SchedWrite.TheDef == WR->getValueAsDef("WriteType")) {
659       if (ResDef) {
660         PrintFatalError(WR->getLoc(), "Resources are defined for both "
661                       "SchedWrite and its alias on processor " +
662                       ProcModel.ModelName);
663       }
664       ResDef = WR;
665     }
666   }
667   // TODO: If ProcModel has a base model (previous generation processor),
668   // then call FindWriteResources recursively with that model here.
669   if (!ResDef) {
670     PrintFatalError(ProcModel.ModelDef->getLoc(),
671                     Twine("Processor does not define resources for ") +
672                     SchedWrite.TheDef->getName());
673   }
674   return ResDef;
675 }
676
677 /// Find the ReadAdvance record for the given SchedRead on this processor or
678 /// return NULL.
679 Record *SubtargetEmitter::FindReadAdvance(const CodeGenSchedRW &SchedRead,
680                                           const CodeGenProcModel &ProcModel) {
681   // Check for SchedReads that directly specify a ReadAdvance.
682   if (SchedRead.TheDef->isSubClassOf("SchedReadAdvance"))
683     return SchedRead.TheDef;
684
685   // Check this processor's list of aliases for SchedRead.
686   Record *AliasDef = nullptr;
687   for (Record *A : SchedRead.Aliases) {
688     const CodeGenSchedRW &AliasRW =
689       SchedModels.getSchedRW(A->getValueAsDef("AliasRW"));
690     if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
691       Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
692       if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
693         continue;
694     }
695     if (AliasDef)
696       PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
697                     "defined for processor " + ProcModel.ModelName +
698                     " Ensure only one SchedAlias exists per RW.");
699     AliasDef = AliasRW.TheDef;
700   }
701   if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance"))
702     return AliasDef;
703
704   // Check this processor's ReadAdvanceList.
705   Record *ResDef = nullptr;
706   for (Record *RA : ProcModel.ReadAdvanceDefs) {
707     if (!RA->isSubClassOf("ReadAdvance"))
708       continue;
709     if (AliasDef == RA->getValueAsDef("ReadType")
710         || SchedRead.TheDef == RA->getValueAsDef("ReadType")) {
711       if (ResDef) {
712         PrintFatalError(RA->getLoc(), "Resources are defined for both "
713                       "SchedRead and its alias on processor " +
714                       ProcModel.ModelName);
715       }
716       ResDef = RA;
717     }
718   }
719   // TODO: If ProcModel has a base model (previous generation processor),
720   // then call FindReadAdvance recursively with that model here.
721   if (!ResDef && SchedRead.TheDef->getName() != "ReadDefault") {
722     PrintFatalError(ProcModel.ModelDef->getLoc(),
723                     Twine("Processor does not define resources for ") +
724                     SchedRead.TheDef->getName());
725   }
726   return ResDef;
727 }
728
729 // Expand an explicit list of processor resources into a full list of implied
730 // resource groups and super resources that cover them.
731 void SubtargetEmitter::ExpandProcResources(RecVec &PRVec,
732                                            std::vector<int64_t> &Cycles,
733                                            const CodeGenProcModel &PM) {
734   // Default to 1 resource cycle.
735   Cycles.resize(PRVec.size(), 1);
736   for (unsigned i = 0, e = PRVec.size(); i != e; ++i) {
737     Record *PRDef = PRVec[i];
738     RecVec SubResources;
739     if (PRDef->isSubClassOf("ProcResGroup"))
740       SubResources = PRDef->getValueAsListOfDefs("Resources");
741     else {
742       SubResources.push_back(PRDef);
743       PRDef = SchedModels.findProcResUnits(PRDef, PM, PRDef->getLoc());
744       for (Record *SubDef = PRDef;
745            SubDef->getValueInit("Super")->isComplete();) {
746         if (SubDef->isSubClassOf("ProcResGroup")) {
747           // Disallow this for simplicitly.
748           PrintFatalError(SubDef->getLoc(), "Processor resource group "
749                           " cannot be a super resources.");
750         }
751         Record *SuperDef =
752             SchedModels.findProcResUnits(SubDef->getValueAsDef("Super"), PM,
753                                          SubDef->getLoc());
754         PRVec.push_back(SuperDef);
755         Cycles.push_back(Cycles[i]);
756         SubDef = SuperDef;
757       }
758     }
759     for (Record *PR : PM.ProcResourceDefs) {
760       if (PR == PRDef || !PR->isSubClassOf("ProcResGroup"))
761         continue;
762       RecVec SuperResources = PR->getValueAsListOfDefs("Resources");
763       RecIter SubI = SubResources.begin(), SubE = SubResources.end();
764       for( ; SubI != SubE; ++SubI) {
765         if (!is_contained(SuperResources, *SubI)) {
766           break;
767         }
768       }
769       if (SubI == SubE) {
770         PRVec.push_back(PR);
771         Cycles.push_back(Cycles[i]);
772       }
773     }
774   }
775 }
776
777 // Generate the SchedClass table for this processor and update global
778 // tables. Must be called for each processor in order.
779 void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel,
780                                            SchedClassTables &SchedTables) {
781   SchedTables.ProcSchedClasses.resize(SchedTables.ProcSchedClasses.size() + 1);
782   if (!ProcModel.hasInstrSchedModel())
783     return;
784
785   std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back();
786   DEBUG(dbgs() << "\n+++ SCHED CLASSES (GenSchedClassTables) +++\n");
787   for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) {
788     DEBUG(SC.dump(&SchedModels));
789
790     SCTab.resize(SCTab.size() + 1);
791     MCSchedClassDesc &SCDesc = SCTab.back();
792     // SCDesc.Name is guarded by NDEBUG
793     SCDesc.NumMicroOps = 0;
794     SCDesc.BeginGroup = false;
795     SCDesc.EndGroup = false;
796     SCDesc.WriteProcResIdx = 0;
797     SCDesc.WriteLatencyIdx = 0;
798     SCDesc.ReadAdvanceIdx = 0;
799
800     // A Variant SchedClass has no resources of its own.
801     bool HasVariants = false;
802     for (const CodeGenSchedTransition &CGT :
803            make_range(SC.Transitions.begin(), SC.Transitions.end())) {
804       if (CGT.ProcIndices[0] == 0 ||
805           is_contained(CGT.ProcIndices, ProcModel.Index)) {
806         HasVariants = true;
807         break;
808       }
809     }
810     if (HasVariants) {
811       SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps;
812       continue;
813     }
814
815     // Determine if the SchedClass is actually reachable on this processor. If
816     // not don't try to locate the processor resources, it will fail.
817     // If ProcIndices contains 0, this class applies to all processors.
818     assert(!SC.ProcIndices.empty() && "expect at least one procidx");
819     if (SC.ProcIndices[0] != 0) {
820       if (!is_contained(SC.ProcIndices, ProcModel.Index))
821         continue;
822     }
823     IdxVec Writes = SC.Writes;
824     IdxVec Reads = SC.Reads;
825     if (!SC.InstRWs.empty()) {
826       // This class has a default ReadWrite list which can be overriden by
827       // InstRW definitions.
828       Record *RWDef = nullptr;
829       for (Record *RW : SC.InstRWs) {
830         Record *RWModelDef = RW->getValueAsDef("SchedModel");
831         if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) {
832           RWDef = RW;
833           break;
834         }
835       }
836       if (RWDef) {
837         Writes.clear();
838         Reads.clear();
839         SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
840                             Writes, Reads);
841       }
842     }
843     if (Writes.empty()) {
844       // Check this processor's itinerary class resources.
845       for (Record *I : ProcModel.ItinRWDefs) {
846         RecVec Matched = I->getValueAsListOfDefs("MatchedItinClasses");
847         if (is_contained(Matched, SC.ItinClassDef)) {
848           SchedModels.findRWs(I->getValueAsListOfDefs("OperandReadWrites"),
849                               Writes, Reads);
850           break;
851         }
852       }
853       if (Writes.empty()) {
854         DEBUG(dbgs() << ProcModel.ModelName
855               << " does not have resources for class " << SC.Name << '\n');
856       }
857     }
858     // Sum resources across all operand writes.
859     std::vector<MCWriteProcResEntry> WriteProcResources;
860     std::vector<MCWriteLatencyEntry> WriteLatencies;
861     std::vector<std::string> WriterNames;
862     std::vector<MCReadAdvanceEntry> ReadAdvanceEntries;
863     for (unsigned W : Writes) {
864       IdxVec WriteSeq;
865       SchedModels.expandRWSeqForProc(W, WriteSeq, /*IsRead=*/false,
866                                      ProcModel);
867
868       // For each operand, create a latency entry.
869       MCWriteLatencyEntry WLEntry;
870       WLEntry.Cycles = 0;
871       unsigned WriteID = WriteSeq.back();
872       WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name);
873       // If this Write is not referenced by a ReadAdvance, don't distinguish it
874       // from other WriteLatency entries.
875       if (!SchedModels.hasReadOfWrite(
876             SchedModels.getSchedWrite(WriteID).TheDef)) {
877         WriteID = 0;
878       }
879       WLEntry.WriteResourceID = WriteID;
880
881       for (unsigned WS : WriteSeq) {
882
883         Record *WriteRes =
884           FindWriteResources(SchedModels.getSchedWrite(WS), ProcModel);
885
886         // Mark the parent class as invalid for unsupported write types.
887         if (WriteRes->getValueAsBit("Unsupported")) {
888           SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
889           break;
890         }
891         WLEntry.Cycles += WriteRes->getValueAsInt("Latency");
892         SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps");
893         SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup");
894         SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup");
895         SCDesc.BeginGroup |= WriteRes->getValueAsBit("SingleIssue");
896         SCDesc.EndGroup |= WriteRes->getValueAsBit("SingleIssue");
897
898         // Create an entry for each ProcResource listed in WriteRes.
899         RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources");
900         std::vector<int64_t> Cycles =
901           WriteRes->getValueAsListOfInts("ResourceCycles");
902
903         ExpandProcResources(PRVec, Cycles, ProcModel);
904
905         for (unsigned PRIdx = 0, PREnd = PRVec.size();
906              PRIdx != PREnd; ++PRIdx) {
907           MCWriteProcResEntry WPREntry;
908           WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]);
909           assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx");
910           WPREntry.Cycles = Cycles[PRIdx];
911           // If this resource is already used in this sequence, add the current
912           // entry's cycles so that the same resource appears to be used
913           // serially, rather than multiple parallel uses. This is important for
914           // in-order machine where the resource consumption is a hazard.
915           unsigned WPRIdx = 0, WPREnd = WriteProcResources.size();
916           for( ; WPRIdx != WPREnd; ++WPRIdx) {
917             if (WriteProcResources[WPRIdx].ProcResourceIdx
918                 == WPREntry.ProcResourceIdx) {
919               WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles;
920               break;
921             }
922           }
923           if (WPRIdx == WPREnd)
924             WriteProcResources.push_back(WPREntry);
925         }
926       }
927       WriteLatencies.push_back(WLEntry);
928     }
929     // Create an entry for each operand Read in this SchedClass.
930     // Entries must be sorted first by UseIdx then by WriteResourceID.
931     for (unsigned UseIdx = 0, EndIdx = Reads.size();
932          UseIdx != EndIdx; ++UseIdx) {
933       Record *ReadAdvance =
934         FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel);
935       if (!ReadAdvance)
936         continue;
937
938       // Mark the parent class as invalid for unsupported write types.
939       if (ReadAdvance->getValueAsBit("Unsupported")) {
940         SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
941         break;
942       }
943       RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites");
944       IdxVec WriteIDs;
945       if (ValidWrites.empty())
946         WriteIDs.push_back(0);
947       else {
948         for (Record *VW : ValidWrites) {
949           WriteIDs.push_back(SchedModels.getSchedRWIdx(VW, /*IsRead=*/false));
950         }
951       }
952       std::sort(WriteIDs.begin(), WriteIDs.end());
953       for(unsigned W : WriteIDs) {
954         MCReadAdvanceEntry RAEntry;
955         RAEntry.UseIdx = UseIdx;
956         RAEntry.WriteResourceID = W;
957         RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles");
958         ReadAdvanceEntries.push_back(RAEntry);
959       }
960     }
961     if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) {
962       WriteProcResources.clear();
963       WriteLatencies.clear();
964       ReadAdvanceEntries.clear();
965     }
966     // Add the information for this SchedClass to the global tables using basic
967     // compression.
968     //
969     // WritePrecRes entries are sorted by ProcResIdx.
970     std::sort(WriteProcResources.begin(), WriteProcResources.end(),
971               LessWriteProcResources());
972
973     SCDesc.NumWriteProcResEntries = WriteProcResources.size();
974     std::vector<MCWriteProcResEntry>::iterator WPRPos =
975       std::search(SchedTables.WriteProcResources.begin(),
976                   SchedTables.WriteProcResources.end(),
977                   WriteProcResources.begin(), WriteProcResources.end());
978     if (WPRPos != SchedTables.WriteProcResources.end())
979       SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin();
980     else {
981       SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size();
982       SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(),
983                                             WriteProcResources.end());
984     }
985     // Latency entries must remain in operand order.
986     SCDesc.NumWriteLatencyEntries = WriteLatencies.size();
987     std::vector<MCWriteLatencyEntry>::iterator WLPos =
988       std::search(SchedTables.WriteLatencies.begin(),
989                   SchedTables.WriteLatencies.end(),
990                   WriteLatencies.begin(), WriteLatencies.end());
991     if (WLPos != SchedTables.WriteLatencies.end()) {
992       unsigned idx = WLPos - SchedTables.WriteLatencies.begin();
993       SCDesc.WriteLatencyIdx = idx;
994       for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i)
995         if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) ==
996             std::string::npos) {
997           SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i];
998         }
999     }
1000     else {
1001       SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size();
1002       SchedTables.WriteLatencies.insert(SchedTables.WriteLatencies.end(),
1003                                         WriteLatencies.begin(),
1004                                         WriteLatencies.end());
1005       SchedTables.WriterNames.insert(SchedTables.WriterNames.end(),
1006                                      WriterNames.begin(), WriterNames.end());
1007     }
1008     // ReadAdvanceEntries must remain in operand order.
1009     SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size();
1010     std::vector<MCReadAdvanceEntry>::iterator RAPos =
1011       std::search(SchedTables.ReadAdvanceEntries.begin(),
1012                   SchedTables.ReadAdvanceEntries.end(),
1013                   ReadAdvanceEntries.begin(), ReadAdvanceEntries.end());
1014     if (RAPos != SchedTables.ReadAdvanceEntries.end())
1015       SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin();
1016     else {
1017       SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size();
1018       SchedTables.ReadAdvanceEntries.insert(RAPos, ReadAdvanceEntries.begin(),
1019                                             ReadAdvanceEntries.end());
1020     }
1021   }
1022 }
1023
1024 // Emit SchedClass tables for all processors and associated global tables.
1025 void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables,
1026                                             raw_ostream &OS) {
1027   // Emit global WriteProcResTable.
1028   OS << "\n// {ProcResourceIdx, Cycles}\n"
1029      << "extern const llvm::MCWriteProcResEntry "
1030      << Target << "WriteProcResTable[] = {\n"
1031      << "  { 0,  0}, // Invalid\n";
1032   for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size();
1033        WPRIdx != WPREnd; ++WPRIdx) {
1034     MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx];
1035     OS << "  {" << format("%2d", WPREntry.ProcResourceIdx) << ", "
1036        << format("%2d", WPREntry.Cycles) << "}";
1037     if (WPRIdx + 1 < WPREnd)
1038       OS << ',';
1039     OS << " // #" << WPRIdx << '\n';
1040   }
1041   OS << "}; // " << Target << "WriteProcResTable\n";
1042
1043   // Emit global WriteLatencyTable.
1044   OS << "\n// {Cycles, WriteResourceID}\n"
1045      << "extern const llvm::MCWriteLatencyEntry "
1046      << Target << "WriteLatencyTable[] = {\n"
1047      << "  { 0,  0}, // Invalid\n";
1048   for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size();
1049        WLIdx != WLEnd; ++WLIdx) {
1050     MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx];
1051     OS << "  {" << format("%2d", WLEntry.Cycles) << ", "
1052        << format("%2d", WLEntry.WriteResourceID) << "}";
1053     if (WLIdx + 1 < WLEnd)
1054       OS << ',';
1055     OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n';
1056   }
1057   OS << "}; // " << Target << "WriteLatencyTable\n";
1058
1059   // Emit global ReadAdvanceTable.
1060   OS << "\n// {UseIdx, WriteResourceID, Cycles}\n"
1061      << "extern const llvm::MCReadAdvanceEntry "
1062      << Target << "ReadAdvanceTable[] = {\n"
1063      << "  {0,  0,  0}, // Invalid\n";
1064   for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size();
1065        RAIdx != RAEnd; ++RAIdx) {
1066     MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx];
1067     OS << "  {" << RAEntry.UseIdx << ", "
1068        << format("%2d", RAEntry.WriteResourceID) << ", "
1069        << format("%2d", RAEntry.Cycles) << "}";
1070     if (RAIdx + 1 < RAEnd)
1071       OS << ',';
1072     OS << " // #" << RAIdx << '\n';
1073   }
1074   OS << "}; // " << Target << "ReadAdvanceTable\n";
1075
1076   // Emit a SchedClass table for each processor.
1077   for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
1078          PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
1079     if (!PI->hasInstrSchedModel())
1080       continue;
1081
1082     std::vector<MCSchedClassDesc> &SCTab =
1083       SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())];
1084
1085     OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup,"
1086        << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n";
1087     OS << "static const llvm::MCSchedClassDesc "
1088        << PI->ModelName << "SchedClasses[] = {\n";
1089
1090     // The first class is always invalid. We no way to distinguish it except by
1091     // name and position.
1092     assert(SchedModels.getSchedClass(0).Name == "NoInstrModel"
1093            && "invalid class not first");
1094     OS << "  {DBGFIELD(\"InvalidSchedClass\")  "
1095        << MCSchedClassDesc::InvalidNumMicroOps
1096        << ", false, false,  0, 0,  0, 0,  0, 0},\n";
1097
1098     for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) {
1099       MCSchedClassDesc &MCDesc = SCTab[SCIdx];
1100       const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx);
1101       OS << "  {DBGFIELD(\"" << SchedClass.Name << "\") ";
1102       if (SchedClass.Name.size() < 18)
1103         OS.indent(18 - SchedClass.Name.size());
1104       OS << MCDesc.NumMicroOps
1105          << ", " << ( MCDesc.BeginGroup ? "true" : "false" )
1106          << ", " << ( MCDesc.EndGroup ? "true" : "false" )
1107          << ", " << format("%2d", MCDesc.WriteProcResIdx)
1108          << ", " << MCDesc.NumWriteProcResEntries
1109          << ", " << format("%2d", MCDesc.WriteLatencyIdx)
1110          << ", " << MCDesc.NumWriteLatencyEntries
1111          << ", " << format("%2d", MCDesc.ReadAdvanceIdx)
1112          << ", " << MCDesc.NumReadAdvanceEntries
1113          << "}, // #" << SCIdx << '\n';
1114     }
1115     OS << "}; // " << PI->ModelName << "SchedClasses\n";
1116   }
1117 }
1118
1119 void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) {
1120   // For each processor model.
1121   for (const CodeGenProcModel &PM : SchedModels.procModels()) {
1122     // Emit processor resource table.
1123     if (PM.hasInstrSchedModel())
1124       EmitProcessorResources(PM, OS);
1125     else if(!PM.ProcResourceDefs.empty())
1126       PrintFatalError(PM.ModelDef->getLoc(), "SchedMachineModel defines "
1127                     "ProcResources without defining WriteRes SchedWriteRes");
1128
1129     // Begin processor itinerary properties
1130     OS << "\n";
1131     OS << "static const llvm::MCSchedModel " << PM.ModelName << " = {\n";
1132     EmitProcessorProp(OS, PM.ModelDef, "IssueWidth", ',');
1133     EmitProcessorProp(OS, PM.ModelDef, "MicroOpBufferSize", ',');
1134     EmitProcessorProp(OS, PM.ModelDef, "LoopMicroOpBufferSize", ',');
1135     EmitProcessorProp(OS, PM.ModelDef, "LoadLatency", ',');
1136     EmitProcessorProp(OS, PM.ModelDef, "HighLatency", ',');
1137     EmitProcessorProp(OS, PM.ModelDef, "MispredictPenalty", ',');
1138
1139     bool PostRAScheduler =
1140       (PM.ModelDef ? PM.ModelDef->getValueAsBit("PostRAScheduler") : false);
1141
1142     OS << "  " << (PostRAScheduler ? "true" : "false")  << ", // "
1143        << "PostRAScheduler\n";
1144
1145     bool CompleteModel =
1146       (PM.ModelDef ? PM.ModelDef->getValueAsBit("CompleteModel") : false);
1147
1148     OS << "  " << (CompleteModel ? "true" : "false") << ", // "
1149        << "CompleteModel\n";
1150
1151     OS << "  " << PM.Index << ", // Processor ID\n";
1152     if (PM.hasInstrSchedModel())
1153       OS << "  " << PM.ModelName << "ProcResources" << ",\n"
1154          << "  " << PM.ModelName << "SchedClasses" << ",\n"
1155          << "  " << PM.ProcResourceDefs.size()+1 << ",\n"
1156          << "  " << (SchedModels.schedClassEnd()
1157                      - SchedModels.schedClassBegin()) << ",\n";
1158     else
1159       OS << "  nullptr, nullptr, 0, 0,"
1160          << " // No instruction-level machine model.\n";
1161     if (PM.hasItineraries())
1162       OS << "  " << PM.ItinsDef->getName() << "\n";
1163     else
1164       OS << "  nullptr // No Itinerary\n";
1165     OS << "};\n";
1166   }
1167 }
1168
1169 //
1170 // EmitProcessorLookup - generate cpu name to itinerary lookup table.
1171 //
1172 void SubtargetEmitter::EmitProcessorLookup(raw_ostream &OS) {
1173   // Gather and sort processor information
1174   std::vector<Record*> ProcessorList =
1175                           Records.getAllDerivedDefinitions("Processor");
1176   std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
1177
1178   // Begin processor table
1179   OS << "\n";
1180   OS << "// Sorted (by key) array of itineraries for CPU subtype.\n"
1181      << "extern const llvm::SubtargetInfoKV "
1182      << Target << "ProcSchedKV[] = {\n";
1183
1184   // For each processor
1185   for (Record *Processor : ProcessorList) {
1186     StringRef Name = Processor->getValueAsString("Name");
1187     const std::string &ProcModelName =
1188       SchedModels.getModelForProc(Processor).ModelName;
1189
1190     // Emit as { "cpu", procinit },
1191     OS << "  { \"" << Name << "\", (const void *)&" << ProcModelName << " },\n";
1192   }
1193
1194   // End processor table
1195   OS << "};\n";
1196 }
1197
1198 //
1199 // EmitSchedModel - Emits all scheduling model tables, folding common patterns.
1200 //
1201 void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) {
1202   OS << "#ifdef DBGFIELD\n"
1203      << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n"
1204      << "#endif\n"
1205      << "#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)\n"
1206      << "#define DBGFIELD(x) x,\n"
1207      << "#else\n"
1208      << "#define DBGFIELD(x)\n"
1209      << "#endif\n";
1210
1211   if (SchedModels.hasItineraries()) {
1212     std::vector<std::vector<InstrItinerary>> ProcItinLists;
1213     // Emit the stage data
1214     EmitStageAndOperandCycleData(OS, ProcItinLists);
1215     EmitItineraries(OS, ProcItinLists);
1216   }
1217   OS << "\n// ===============================================================\n"
1218      << "// Data tables for the new per-operand machine model.\n";
1219
1220   SchedClassTables SchedTables;
1221   for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
1222     GenSchedClassTables(ProcModel, SchedTables);
1223   }
1224   EmitSchedClassTables(SchedTables, OS);
1225
1226   // Emit the processor machine model
1227   EmitProcessorModels(OS);
1228   // Emit the processor lookup data
1229   EmitProcessorLookup(OS);
1230
1231   OS << "\n#undef DBGFIELD";
1232 }
1233
1234 void SubtargetEmitter::EmitSchedModelHelpers(const std::string &ClassName,
1235                                              raw_ostream &OS) {
1236   OS << "unsigned " << ClassName
1237      << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI,"
1238      << " const TargetSchedModel *SchedModel) const {\n";
1239
1240   std::vector<Record*> Prologs = Records.getAllDerivedDefinitions("PredicateProlog");
1241   std::sort(Prologs.begin(), Prologs.end(), LessRecord());
1242   for (Record *P : Prologs) {
1243     OS << P->getValueAsString("Code") << '\n';
1244   }
1245   IdxVec VariantClasses;
1246   for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) {
1247     if (SC.Transitions.empty())
1248       continue;
1249     VariantClasses.push_back(SC.Index);
1250   }
1251   if (!VariantClasses.empty()) {
1252     OS << "  switch (SchedClass) {\n";
1253     for (unsigned VC : VariantClasses) {
1254       const CodeGenSchedClass &SC = SchedModels.getSchedClass(VC);
1255       OS << "  case " << VC << ": // " << SC.Name << '\n';
1256       IdxVec ProcIndices;
1257       for (const CodeGenSchedTransition &T : SC.Transitions) {
1258         IdxVec PI;
1259         std::set_union(T.ProcIndices.begin(), T.ProcIndices.end(),
1260                        ProcIndices.begin(), ProcIndices.end(),
1261                        std::back_inserter(PI));
1262         ProcIndices.swap(PI);
1263       }
1264       for (unsigned PI : ProcIndices) {
1265         OS << "    ";
1266         if (PI != 0)
1267           OS << "if (SchedModel->getProcessorID() == " << PI << ") ";
1268         OS << "{ // " << (SchedModels.procModelBegin() + PI)->ModelName
1269            << '\n';
1270         for (const CodeGenSchedTransition &T : SC.Transitions) {
1271           if (PI != 0 && !std::count(T.ProcIndices.begin(),
1272                                      T.ProcIndices.end(), PI)) {
1273               continue;
1274           }
1275           OS << "      if (";
1276           for (RecIter RI = T.PredTerm.begin(), RE = T.PredTerm.end();
1277                RI != RE; ++RI) {
1278             if (RI != T.PredTerm.begin())
1279               OS << "\n          && ";
1280             OS << "(" << (*RI)->getValueAsString("Predicate") << ")";
1281           }
1282           OS << ")\n"
1283              << "        return " << T.ToClassIdx << "; // "
1284              << SchedModels.getSchedClass(T.ToClassIdx).Name << '\n';
1285         }
1286         OS << "    }\n";
1287         if (PI == 0)
1288           break;
1289       }
1290       if (SC.isInferred())
1291         OS << "    return " << SC.Index << ";\n";
1292       OS << "    break;\n";
1293     }
1294     OS << "  };\n";
1295   }
1296   OS << "  report_fatal_error(\"Expected a variant SchedClass\");\n"
1297      << "} // " << ClassName << "::resolveSchedClass\n";
1298 }
1299
1300 void SubtargetEmitter::EmitHwModeCheck(const std::string &ClassName,
1301                                        raw_ostream &OS) {
1302   const CodeGenHwModes &CGH = TGT.getHwModes();
1303   assert(CGH.getNumModeIds() > 0);
1304   if (CGH.getNumModeIds() == 1)
1305     return;
1306
1307   OS << "unsigned " << ClassName << "::getHwMode() const {\n";
1308   for (unsigned M = 1, NumModes = CGH.getNumModeIds(); M != NumModes; ++M) {
1309     const HwMode &HM = CGH.getMode(M);
1310     OS << "  if (checkFeatures(\"" << HM.Features
1311        << "\")) return " << M << ";\n";
1312   }
1313   OS << "  return 0;\n}\n";
1314 }
1315
1316 //
1317 // ParseFeaturesFunction - Produces a subtarget specific function for parsing
1318 // the subtarget features string.
1319 //
1320 void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS,
1321                                              unsigned NumFeatures,
1322                                              unsigned NumProcs) {
1323   std::vector<Record*> Features =
1324                        Records.getAllDerivedDefinitions("SubtargetFeature");
1325   std::sort(Features.begin(), Features.end(), LessRecord());
1326
1327   OS << "// ParseSubtargetFeatures - Parses features string setting specified\n"
1328      << "// subtarget options.\n"
1329      << "void llvm::";
1330   OS << Target;
1331   OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef FS) {\n"
1332      << "  DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n"
1333      << "  DEBUG(dbgs() << \"\\nCPU:\" << CPU << \"\\n\\n\");\n";
1334
1335   if (Features.empty()) {
1336     OS << "}\n";
1337     return;
1338   }
1339
1340   OS << "  InitMCProcessorInfo(CPU, FS);\n"
1341      << "  const FeatureBitset& Bits = getFeatureBits();\n";
1342
1343   for (Record *R : Features) {
1344     // Next record
1345     StringRef Instance = R->getName();
1346     StringRef Value = R->getValueAsString("Value");
1347     StringRef Attribute = R->getValueAsString("Attribute");
1348
1349     if (Value=="true" || Value=="false")
1350       OS << "  if (Bits[" << Target << "::"
1351          << Instance << "]) "
1352          << Attribute << " = " << Value << ";\n";
1353     else
1354       OS << "  if (Bits[" << Target << "::"
1355          << Instance << "] && "
1356          << Attribute << " < " << Value << ") "
1357          << Attribute << " = " << Value << ";\n";
1358   }
1359
1360   OS << "}\n";
1361 }
1362
1363 //
1364 // SubtargetEmitter::run - Main subtarget enumeration emitter.
1365 //
1366 void SubtargetEmitter::run(raw_ostream &OS) {
1367   emitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);
1368
1369   OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n";
1370   OS << "#undef GET_SUBTARGETINFO_ENUM\n\n";
1371
1372   OS << "namespace llvm {\n";
1373   Enumeration(OS);
1374   OS << "} // end namespace llvm\n\n";
1375   OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n";
1376
1377   OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n";
1378   OS << "#undef GET_SUBTARGETINFO_MC_DESC\n\n";
1379
1380   OS << "namespace llvm {\n";
1381 #if 0
1382   OS << "namespace {\n";
1383 #endif
1384   unsigned NumFeatures = FeatureKeyValues(OS);
1385   OS << "\n";
1386   unsigned NumProcs = CPUKeyValues(OS);
1387   OS << "\n";
1388   EmitSchedModel(OS);
1389   OS << "\n";
1390 #if 0
1391   OS << "} // end anonymous namespace\n\n";
1392 #endif
1393
1394   // MCInstrInfo initialization routine.
1395   OS << "\nstatic inline MCSubtargetInfo *create" << Target
1396      << "MCSubtargetInfoImpl("
1397      << "const Triple &TT, StringRef CPU, StringRef FS) {\n";
1398   OS << "  return new MCSubtargetInfo(TT, CPU, FS, ";
1399   if (NumFeatures)
1400     OS << Target << "FeatureKV, ";
1401   else
1402     OS << "None, ";
1403   if (NumProcs)
1404     OS << Target << "SubTypeKV, ";
1405   else
1406     OS << "None, ";
1407   OS << '\n'; OS.indent(22);
1408   OS << Target << "ProcSchedKV, "
1409      << Target << "WriteProcResTable, "
1410      << Target << "WriteLatencyTable, "
1411      << Target << "ReadAdvanceTable, ";
1412   OS << '\n'; OS.indent(22);
1413   if (SchedModels.hasItineraries()) {
1414     OS << Target << "Stages, "
1415        << Target << "OperandCycles, "
1416        << Target << "ForwardingPaths";
1417   } else
1418     OS << "nullptr, nullptr, nullptr";
1419   OS << ");\n}\n\n";
1420
1421   OS << "} // end namespace llvm\n\n";
1422
1423   OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n";
1424
1425   OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n";
1426   OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n\n";
1427
1428   OS << "#include \"llvm/Support/Debug.h\"\n";
1429   OS << "#include \"llvm/Support/raw_ostream.h\"\n\n";
1430   ParseFeaturesFunction(OS, NumFeatures, NumProcs);
1431
1432   OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n";
1433
1434   // Create a TargetSubtargetInfo subclass to hide the MC layer initialization.
1435   OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n";
1436   OS << "#undef GET_SUBTARGETINFO_HEADER\n\n";
1437
1438   std::string ClassName = Target + "GenSubtargetInfo";
1439   OS << "namespace llvm {\n";
1440   OS << "class DFAPacketizer;\n";
1441   OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n"
1442      << "  explicit " << ClassName << "(const Triple &TT, StringRef CPU, "
1443      << "StringRef FS);\n"
1444      << "public:\n"
1445      << "  unsigned resolveSchedClass(unsigned SchedClass, "
1446      << " const MachineInstr *DefMI,"
1447      << " const TargetSchedModel *SchedModel) const override;\n"
1448      << "  DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)"
1449      << " const;\n";
1450   if (TGT.getHwModes().getNumModeIds() > 1)
1451     OS << "  unsigned getHwMode() const override;\n";
1452   OS << "};\n"
1453      << "} // end namespace llvm\n\n";
1454
1455   OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n";
1456
1457   OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n";
1458   OS << "#undef GET_SUBTARGETINFO_CTOR\n\n";
1459
1460   OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n\n";
1461   OS << "namespace llvm {\n";
1462   OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n";
1463   OS << "extern const llvm::SubtargetFeatureKV " << Target << "SubTypeKV[];\n";
1464   OS << "extern const llvm::SubtargetInfoKV " << Target << "ProcSchedKV[];\n";
1465   OS << "extern const llvm::MCWriteProcResEntry "
1466      << Target << "WriteProcResTable[];\n";
1467   OS << "extern const llvm::MCWriteLatencyEntry "
1468      << Target << "WriteLatencyTable[];\n";
1469   OS << "extern const llvm::MCReadAdvanceEntry "
1470      << Target << "ReadAdvanceTable[];\n";
1471
1472   if (SchedModels.hasItineraries()) {
1473     OS << "extern const llvm::InstrStage " << Target << "Stages[];\n";
1474     OS << "extern const unsigned " << Target << "OperandCycles[];\n";
1475     OS << "extern const unsigned " << Target << "ForwardingPaths[];\n";
1476   }
1477
1478   OS << ClassName << "::" << ClassName << "(const Triple &TT, StringRef CPU, "
1479      << "StringRef FS)\n"
1480      << "  : TargetSubtargetInfo(TT, CPU, FS, ";
1481   if (NumFeatures)
1482     OS << "makeArrayRef(" << Target << "FeatureKV, " << NumFeatures << "), ";
1483   else
1484     OS << "None, ";
1485   if (NumProcs)
1486     OS << "makeArrayRef(" << Target << "SubTypeKV, " << NumProcs << "), ";
1487   else
1488     OS << "None, ";
1489   OS << '\n'; OS.indent(24);
1490   OS << Target << "ProcSchedKV, "
1491      << Target << "WriteProcResTable, "
1492      << Target << "WriteLatencyTable, "
1493      << Target << "ReadAdvanceTable, ";
1494   OS << '\n'; OS.indent(24);
1495   if (SchedModels.hasItineraries()) {
1496     OS << Target << "Stages, "
1497        << Target << "OperandCycles, "
1498        << Target << "ForwardingPaths";
1499   } else
1500     OS << "nullptr, nullptr, nullptr";
1501   OS << ") {}\n\n";
1502
1503   EmitSchedModelHelpers(ClassName, OS);
1504   EmitHwModeCheck(ClassName, OS);
1505
1506   OS << "} // end namespace llvm\n\n";
1507
1508   OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n";
1509 }
1510
1511 namespace llvm {
1512
1513 void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) {
1514   CodeGenTarget CGTarget(RK);
1515   SubtargetEmitter(RK, CGTarget).run(OS);
1516 }
1517
1518 } // end namespace llvm