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