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