21870b1f5b1123f0fbe214686982b0fbff0b4032
[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 "SubtargetEmitter.h"
15 #include "CodeGenTarget.h"
16 #include "Record.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include <algorithm>
20 using namespace llvm;
21
22 //
23 // Enumeration - Emit the specified class as an enumeration.
24 //
25 void SubtargetEmitter::Enumeration(raw_ostream &OS,
26                                    const char *ClassName,
27                                    bool isBits) {
28   // Get all records of class and sort
29   std::vector<Record*> DefList = Records.getAllDerivedDefinitions(ClassName);
30   std::sort(DefList.begin(), DefList.end(), LessRecord());
31
32   // Open enumeration
33   OS << "enum {\n";
34   
35   // For each record
36   for (unsigned i = 0, N = DefList.size(); i < N;) {
37     // Next record
38     Record *Def = DefList[i];
39     
40     // Get and emit name
41     OS << "  " << Def->getName();
42     
43     // If bit flags then emit expression (1 << i)
44     if (isBits)  OS << " = " << " 1 << " << i;
45
46     // Depending on 'if more in the list' emit comma
47     if (++i < N) OS << ",";
48     
49     OS << "\n";
50   }
51   
52   // Close enumeration
53   OS << "};\n";
54 }
55
56 //
57 // FeatureKeyValues - Emit data of all the subtarget features.  Used by the
58 // command line.
59 //
60 void SubtargetEmitter::FeatureKeyValues(raw_ostream &OS) {
61   // Gather and sort all the features
62   std::vector<Record*> FeatureList =
63                            Records.getAllDerivedDefinitions("SubtargetFeature");
64   std::sort(FeatureList.begin(), FeatureList.end(), LessRecordFieldName());
65
66   // Begin feature table
67   OS << "// Sorted (by key) array of values for CPU features.\n"
68      << "static const llvm::SubtargetFeatureKV FeatureKV[] = {\n";
69   
70   // For each feature
71   for (unsigned i = 0, N = FeatureList.size(); i < N; ++i) {
72     // Next feature
73     Record *Feature = FeatureList[i];
74
75     const std::string &Name = Feature->getName();
76     const std::string &CommandLineName = Feature->getValueAsString("Name");
77     const std::string &Desc = Feature->getValueAsString("Desc");
78     
79     if (CommandLineName.empty()) continue;
80     
81     // Emit as { "feature", "description", featureEnum, i1 | i2 | ... | in }
82     OS << "  { "
83        << "\"" << CommandLineName << "\", "
84        << "\"" << Desc << "\", "
85        << Name << ", ";
86
87     const std::vector<Record*> &ImpliesList = 
88       Feature->getValueAsListOfDefs("Implies");
89     
90     if (ImpliesList.empty()) {
91       OS << "0";
92     } else {
93       for (unsigned j = 0, M = ImpliesList.size(); j < M;) {
94         OS << ImpliesList[j]->getName();
95         if (++j < M) OS << " | ";
96       }
97     }
98
99     OS << " }";
100     
101     // Depending on 'if more in the list' emit comma
102     if ((i + 1) < N) OS << ",";
103     
104     OS << "\n";
105   }
106   
107   // End feature table
108   OS << "};\n";
109
110   // Emit size of table
111   OS<<"\nenum {\n";
112   OS<<"  FeatureKVSize = sizeof(FeatureKV)/sizeof(llvm::SubtargetFeatureKV)\n";
113   OS<<"};\n";
114 }
115
116 //
117 // CPUKeyValues - Emit data of all the subtarget processors.  Used by command
118 // line.
119 //
120 void SubtargetEmitter::CPUKeyValues(raw_ostream &OS) {
121   // Gather and sort processor information
122   std::vector<Record*> ProcessorList =
123                           Records.getAllDerivedDefinitions("Processor");
124   std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
125
126   // Begin processor table
127   OS << "// Sorted (by key) array of values for CPU subtype.\n"
128      << "static const llvm::SubtargetFeatureKV SubTypeKV[] = {\n";
129      
130   // For each processor
131   for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
132     // Next processor
133     Record *Processor = ProcessorList[i];
134
135     const std::string &Name = Processor->getValueAsString("Name");
136     const std::vector<Record*> &FeatureList = 
137       Processor->getValueAsListOfDefs("Features");
138     
139     // Emit as { "cpu", "description", f1 | f2 | ... fn },
140     OS << "  { "
141        << "\"" << Name << "\", "
142        << "\"Select the " << Name << " processor\", ";
143     
144     if (FeatureList.empty()) {
145       OS << "0";
146     } else {
147       for (unsigned j = 0, M = FeatureList.size(); j < M;) {
148         OS << FeatureList[j]->getName();
149         if (++j < M) OS << " | ";
150       }
151     }
152     
153     // The "0" is for the "implies" section of this data structure.
154     OS << ", 0 }";
155     
156     // Depending on 'if more in the list' emit comma
157     if (++i < N) OS << ",";
158     
159     OS << "\n";
160   }
161   
162   // End processor table
163   OS << "};\n";
164
165   // Emit size of table
166   OS<<"\nenum {\n";
167   OS<<"  SubTypeKVSize = sizeof(SubTypeKV)/sizeof(llvm::SubtargetFeatureKV)\n";
168   OS<<"};\n";
169 }
170
171 //
172 // CollectAllItinClasses - Gathers and enumerates all the itinerary classes.
173 // Returns itinerary class count.
174 //
175 unsigned SubtargetEmitter::
176 CollectAllItinClasses(raw_ostream &OS,
177                       std::map<std::string, unsigned> &ItinClassesMap,
178                       std::vector<Record*> &ItinClassList) {
179   // For each itinerary class
180   unsigned N = ItinClassList.size();
181   for (unsigned i = 0; i < N; i++) {
182     // Next itinerary class
183     const Record *ItinClass = ItinClassList[i];
184     // Get name of itinerary class
185     // Assign itinerary class a unique number
186     ItinClassesMap[ItinClass->getName()] = i;
187   }
188   
189   // Emit size of table
190   OS<<"\nenum {\n";
191   OS<<"  ItinClassesSize = " << N << "\n";
192   OS<<"};\n";
193
194   // Return itinerary class count
195   return N;
196 }
197
198 //
199 // FormItineraryStageString - Compose a string containing the stage
200 // data initialization for the specified itinerary.  N is the number
201 // of stages.
202 //
203 void SubtargetEmitter::FormItineraryStageString(const std::string &Name,
204                                                 Record *ItinData,
205                                                 std::string &ItinString,
206                                                 unsigned &NStages) {
207   // Get states list
208   const std::vector<Record*> &StageList =
209     ItinData->getValueAsListOfDefs("Stages");
210
211   // For each stage
212   unsigned N = NStages = StageList.size();
213   for (unsigned i = 0; i < N;) {
214     // Next stage
215     const Record *Stage = StageList[i];
216   
217     // Form string as ,{ cycles, u1 | u2 | ... | un, timeinc, kind }
218     int Cycles = Stage->getValueAsInt("Cycles");
219     ItinString += "  { " + itostr(Cycles) + ", ";
220     
221     // Get unit list
222     const std::vector<Record*> &UnitList = Stage->getValueAsListOfDefs("Units");
223     
224     // For each unit
225     for (unsigned j = 0, M = UnitList.size(); j < M;) {
226       // Add name and bitwise or
227       ItinString += Name + "FU::" + UnitList[j]->getName();
228       if (++j < M) ItinString += " | ";
229     }
230     
231     int TimeInc = Stage->getValueAsInt("TimeInc");
232     ItinString += ", " + itostr(TimeInc);
233
234     int Kind = Stage->getValueAsInt("Kind");
235     ItinString += ", (llvm::InstrStage::ReservationKinds)" + itostr(Kind);
236
237     // Close off stage
238     ItinString += " }";
239     if (++i < N) ItinString += ", ";
240   }
241 }
242
243 //
244 // FormItineraryOperandCycleString - Compose a string containing the
245 // operand cycle initialization for the specified itinerary.  N is the
246 // number of operands that has cycles specified.
247 //
248 void SubtargetEmitter::FormItineraryOperandCycleString(Record *ItinData,
249                          std::string &ItinString, unsigned &NOperandCycles) {
250   // Get operand cycle list
251   const std::vector<int64_t> &OperandCycleList =
252     ItinData->getValueAsListOfInts("OperandCycles");
253
254   // For each operand cycle
255   unsigned N = NOperandCycles = OperandCycleList.size();
256   for (unsigned i = 0; i < N;) {
257     // Next operand cycle
258     const int OCycle = OperandCycleList[i];
259   
260     ItinString += "  " + itostr(OCycle);
261     if (++i < N) ItinString += ", ";
262   }
263 }
264
265 //
266 // EmitStageAndOperandCycleData - Generate unique itinerary stages and
267 // operand cycle tables.  Record itineraries for processors.
268 //
269 void SubtargetEmitter::EmitStageAndOperandCycleData(raw_ostream &OS,
270        unsigned NItinClasses,
271        std::map<std::string, unsigned> &ItinClassesMap,
272        std::vector<Record*> &ItinClassList,
273        std::vector<std::vector<InstrItinerary> > &ProcList) {
274   // Gather processor iteraries
275   std::vector<Record*> ProcItinList =
276                        Records.getAllDerivedDefinitions("ProcessorItineraries");
277   
278   // If just no itinerary then don't bother
279   if (ProcItinList.size() < 2) return;
280
281   // Emit functional units for all the itineraries.
282   for (unsigned i = 0, N = ProcItinList.size(); i < N; ++i) {
283     // Next record
284     Record *Proc = ProcItinList[i];
285
286     std::vector<Record*> FUs = Proc->getValueAsListOfDefs("FU");
287     if (FUs.empty())
288       continue;
289
290     const std::string &Name = Proc->getName();
291     OS << "\n// Functional units for itineraries \"" << Name << "\"\n"
292        << "namespace " << Name << "FU {\n";
293
294     for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j)
295       OS << "  const unsigned " << FUs[j]->getName()
296          << " = 1 << " << j << ";\n";
297
298     OS << "}\n";
299   }
300
301   // Begin stages table
302   std::string StageTable = "\nstatic const llvm::InstrStage Stages[] = {\n";
303   StageTable += "  { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n";
304         
305   // Begin operand cycle table
306   std::string OperandCycleTable = "static const unsigned OperandCycles[] = {\n";
307   OperandCycleTable += "  0, // No itinerary\n";
308         
309   unsigned StageCount = 1, OperandCycleCount = 1;
310   unsigned ItinStageEnum = 1, ItinOperandCycleEnum = 1;
311   std::map<std::string, unsigned> ItinStageMap, ItinOperandCycleMap;
312   for (unsigned i = 0, N = ProcItinList.size(); i < N; i++) {
313     // Next record
314     Record *Proc = ProcItinList[i];
315     
316     // Get processor itinerary name
317     const std::string &Name = Proc->getName();
318     
319     // Skip default
320     if (Name == "NoItineraries") continue;
321     
322     // Create and expand processor itinerary to cover all itinerary classes
323     std::vector<InstrItinerary> ItinList;
324     ItinList.resize(NItinClasses);
325     
326     // Get itinerary data list
327     std::vector<Record*> ItinDataList = Proc->getValueAsListOfDefs("IID");
328     
329     // For each itinerary data
330     for (unsigned j = 0, M = ItinDataList.size(); j < M; j++) {
331       // Next itinerary data
332       Record *ItinData = ItinDataList[j];
333       
334       // Get string and stage count
335       std::string ItinStageString;
336       unsigned NStages;
337       FormItineraryStageString(Name, ItinData, ItinStageString, NStages);
338
339       // Get string and operand cycle count
340       std::string ItinOperandCycleString;
341       unsigned NOperandCycles;
342       FormItineraryOperandCycleString(ItinData, ItinOperandCycleString,
343                                       NOperandCycles);
344
345       // Check to see if stage already exists and create if it doesn't
346       unsigned FindStage = 0;
347       if (NStages > 0) {
348         FindStage = ItinStageMap[ItinStageString];
349         if (FindStage == 0) {
350           // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // index
351           StageTable += ItinStageString + ", // " + itostr(ItinStageEnum) + "\n";
352           // Record Itin class number.
353           ItinStageMap[ItinStageString] = FindStage = StageCount;
354           StageCount += NStages;
355           ItinStageEnum++;
356         }
357       }
358       
359       // Check to see if operand cycle already exists and create if it doesn't
360       unsigned FindOperandCycle = 0;
361       if (NOperandCycles > 0) {
362         FindOperandCycle = ItinOperandCycleMap[ItinOperandCycleString];
363         if (FindOperandCycle == 0) {
364           // Emit as  cycle, // index
365           OperandCycleTable += ItinOperandCycleString + ", // " + 
366             itostr(ItinOperandCycleEnum) + "\n";
367           // Record Itin class number.
368           ItinOperandCycleMap[ItinOperandCycleString] = 
369             FindOperandCycle = OperandCycleCount;
370           OperandCycleCount += NOperandCycles;
371           ItinOperandCycleEnum++;
372         }
373       }
374       
375       // Locate where to inject into processor itinerary table
376       const std::string &Name = ItinData->getValueAsDef("TheClass")->getName();
377       unsigned Find = ItinClassesMap[Name];
378       
379       // Set up itinerary as location and location + stage count
380       unsigned NumUOps = ItinClassList[Find]->getValueAsInt("NumMicroOps");
381       InstrItinerary Intinerary = { NumUOps, FindStage, FindStage + NStages,
382                                     FindOperandCycle,
383                                     FindOperandCycle + NOperandCycles};
384
385       // Inject - empty slots will be 0, 0
386       ItinList[Find] = Intinerary;
387     }
388     
389     // Add process itinerary to list
390     ProcList.push_back(ItinList);
391   }
392   
393   // Closing stage
394   StageTable += "  { 0, 0, 0, llvm::InstrStage::Required } // End itinerary\n";
395   StageTable += "};\n";
396
397   // Closing operand cycles
398   OperandCycleTable += "  0 // End itinerary\n";
399   OperandCycleTable += "};\n";
400
401   // Emit tables.
402   OS << StageTable;
403   OS << OperandCycleTable;
404   
405   // Emit size of tables
406   OS<<"\nenum {\n";
407   OS<<"  StagesSize = sizeof(Stages)/sizeof(llvm::InstrStage),\n";
408   OS<<"  OperandCyclesSize = sizeof(OperandCycles)/sizeof(unsigned)\n";
409   OS<<"};\n";
410 }
411
412 //
413 // EmitProcessorData - Generate data for processor itineraries.
414 //
415 void SubtargetEmitter::EmitProcessorData(raw_ostream &OS,
416       std::vector<std::vector<InstrItinerary> > &ProcList) {
417   // Get an iterator for processor itinerary stages
418   std::vector<std::vector<InstrItinerary> >::iterator
419       ProcListIter = ProcList.begin();
420   
421   // For each processor itinerary
422   std::vector<Record*> Itins =
423                        Records.getAllDerivedDefinitions("ProcessorItineraries");
424   for (unsigned i = 0, N = Itins.size(); i < N; i++) {
425     // Next record
426     Record *Itin = Itins[i];
427
428     // Get processor itinerary name
429     const std::string &Name = Itin->getName();
430     
431     // Skip default
432     if (Name == "NoItineraries") continue;
433
434     // Begin processor itinerary table
435     OS << "\n";
436     OS << "static const llvm::InstrItinerary " << Name << "[] = {\n";
437     
438     // For each itinerary class
439     std::vector<InstrItinerary> &ItinList = *ProcListIter++;
440     for (unsigned j = 0, M = ItinList.size(); j < M; ++j) {
441       InstrItinerary &Intinerary = ItinList[j];
442       
443       // Emit in the form of 
444       // { firstStage, lastStage, firstCycle, lastCycle } // index
445       if (Intinerary.FirstStage == 0) {
446         OS << "  { 1, 0, 0, 0, 0 }";
447       } else {
448         OS << "  { " <<
449           Intinerary.NumMicroOps << ", " <<
450           Intinerary.FirstStage << ", " << 
451           Intinerary.LastStage << ", " << 
452           Intinerary.FirstOperandCycle << ", " << 
453           Intinerary.LastOperandCycle << " }";
454       }
455       
456       OS << ", // " << j << "\n";
457     }
458     
459     // End processor itinerary table
460     OS << "  { 1, ~0U, ~0U, ~0U, ~0U } // end marker\n";
461     OS << "};\n";
462   }
463 }
464
465 //
466 // EmitProcessorLookup - generate cpu name to itinerary lookup table.
467 //
468 void SubtargetEmitter::EmitProcessorLookup(raw_ostream &OS) {
469   // Gather and sort processor information
470   std::vector<Record*> ProcessorList =
471                           Records.getAllDerivedDefinitions("Processor");
472   std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
473
474   // Begin processor table
475   OS << "\n";
476   OS << "// Sorted (by key) array of itineraries for CPU subtype.\n"
477      << "static const llvm::SubtargetInfoKV ProcItinKV[] = {\n";
478      
479   // For each processor
480   for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
481     // Next processor
482     Record *Processor = ProcessorList[i];
483
484     const std::string &Name = Processor->getValueAsString("Name");
485     const std::string &ProcItin =
486       Processor->getValueAsDef("ProcItin")->getName();
487     
488     // Emit as { "cpu", procinit },
489     OS << "  { "
490        << "\"" << Name << "\", "
491        << "(void *)&" << ProcItin;
492         
493     OS << " }";
494     
495     // Depending on ''if more in the list'' emit comma
496     if (++i < N) OS << ",";
497     
498     OS << "\n";
499   }
500   
501   // End processor table
502   OS << "};\n";
503
504   // Emit size of table
505   OS<<"\nenum {\n";
506   OS<<"  ProcItinKVSize = sizeof(ProcItinKV)/"
507                             "sizeof(llvm::SubtargetInfoKV)\n";
508   OS<<"};\n";
509 }
510
511 //
512 // EmitData - Emits all stages and itineries, folding common patterns.
513 //
514 void SubtargetEmitter::EmitData(raw_ostream &OS) {
515   std::map<std::string, unsigned> ItinClassesMap;
516   // Gather and sort all itinerary classes
517   std::vector<Record*> ItinClassList =
518     Records.getAllDerivedDefinitions("InstrItinClass");
519   std::sort(ItinClassList.begin(), ItinClassList.end(), LessRecord());
520   
521   // Enumerate all the itinerary classes
522   unsigned NItinClasses = CollectAllItinClasses(OS, ItinClassesMap,
523                                                 ItinClassList);
524   // Make sure the rest is worth the effort
525   HasItineraries = NItinClasses != 1;   // Ignore NoItinerary.
526   
527   if (HasItineraries) {
528     std::vector<std::vector<InstrItinerary> > ProcList;
529     // Emit the stage data
530     EmitStageAndOperandCycleData(OS, NItinClasses, ItinClassesMap,
531                                  ItinClassList, ProcList);
532     // Emit the processor itinerary data
533     EmitProcessorData(OS, ProcList);
534     // Emit the processor lookup data
535     EmitProcessorLookup(OS);
536   }
537 }
538
539 //
540 // ParseFeaturesFunction - Produces a subtarget specific function for parsing
541 // the subtarget features string.
542 //
543 void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS) {
544   std::vector<Record*> Features =
545                        Records.getAllDerivedDefinitions("SubtargetFeature");
546   std::sort(Features.begin(), Features.end(), LessRecord());
547
548   OS << "// ParseSubtargetFeatures - Parses features string setting specified\n" 
549      << "// subtarget options.\n" 
550      << "std::string llvm::";
551   OS << Target;
552   OS << "Subtarget::ParseSubtargetFeatures(const std::string &FS,\n"
553      << "                                  const std::string &CPU) {\n"
554      << "  DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n"
555      << "  DEBUG(dbgs() << \"\\nCPU:\" << CPU);\n"
556      << "  SubtargetFeatures Features(FS);\n"
557      << "  Features.setCPUIfNone(CPU);\n"
558      << "  uint32_t Bits =  Features.getBits(SubTypeKV, SubTypeKVSize,\n"
559      << "                                    FeatureKV, FeatureKVSize);\n";
560
561   for (unsigned i = 0; i < Features.size(); i++) {
562     // Next record
563     Record *R = Features[i];
564     const std::string &Instance = R->getName();
565     const std::string &Value = R->getValueAsString("Value");
566     const std::string &Attribute = R->getValueAsString("Attribute");
567
568     if (Value=="true" || Value=="false")
569       OS << "  if ((Bits & " << Instance << ") != 0) "
570          << Attribute << " = " << Value << ";\n";
571     else
572       OS << "  if ((Bits & " << Instance << ") != 0 && " << Attribute << 
573             " < " << Value << ") " << Attribute << " = " << Value << ";\n";
574   }
575
576   if (HasItineraries) {
577     OS << "\n"
578        << "  InstrItinerary *Itinerary = (InstrItinerary *)"
579        <<              "Features.getInfo(ProcItinKV, ProcItinKVSize);\n"
580        << "  InstrItins = InstrItineraryData(Stages, OperandCycles, Itinerary);\n";
581   }
582
583   OS << "  return Features.getCPU();\n"
584      << "}\n";
585 }
586
587 //
588 // SubtargetEmitter::run - Main subtarget enumeration emitter.
589 //
590 void SubtargetEmitter::run(raw_ostream &OS) {
591   Target = CodeGenTarget().getName();
592
593   EmitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);
594
595   OS << "#include \"llvm/Support/Debug.h\"\n";
596   OS << "#include \"llvm/Support/raw_ostream.h\"\n";
597   OS << "#include \"llvm/Target/SubtargetFeature.h\"\n";
598   OS << "#include \"llvm/Target/TargetInstrItineraries.h\"\n\n";
599
600 //  Enumeration(OS, "FuncUnit", true);
601 //  OS<<"\n";
602 //  Enumeration(OS, "InstrItinClass", false);
603 //  OS<<"\n";
604   Enumeration(OS, "SubtargetFeature", true);
605   OS<<"\n";
606   FeatureKeyValues(OS);
607   OS<<"\n";
608   CPUKeyValues(OS);
609   OS<<"\n";
610   EmitData(OS);
611   OS<<"\n";
612   ParseFeaturesFunction(OS);
613 }