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