Allow itineraries to be passed through the Target Machine.
[oota-llvm.git] / utils / TableGen / SubtargetEmitter.cpp
1 //===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits subtarget enumerations.  The format is in a state
11 // flux and will be tightened up when integration to scheduling is complete.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SubtargetEmitter.h"
16 #include "CodeGenTarget.h"
17 #include "Record.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Support/Debug.h"
20 #include <algorithm>
21 using namespace llvm;
22
23 //
24 // Record sort by name function.
25 //
26 struct LessRecord {
27   bool operator()(const Record *Rec1, const Record *Rec2) const {
28     return Rec1->getName() < Rec2->getName();
29   }
30 };
31
32 //
33 // Record sort by field "Name" function.
34 //
35 struct LessRecordFieldName {
36   bool operator()(const Record *Rec1, const Record *Rec2) const {
37     return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
38   }
39 };
40
41 //
42 // Enumeration - Emit the specified class as an enumeration.
43 //
44 void SubtargetEmitter::Enumeration(std::ostream &OS,
45                                    const char *ClassName,
46                                    bool isBits) {
47   // Get all records of class and sort
48   std::vector<Record*> DefList = Records.getAllDerivedDefinitions(ClassName);
49   sort(DefList.begin(), DefList.end(), LessRecord());
50
51   // Open enumeration
52   OS << "enum {\n";
53   
54   // For each record
55   for (unsigned i = 0, N = DefList.size(); i < N;) {
56     // Next record
57     Record *Def = DefList[i];
58     
59     // Get and emit name
60     std::string Name = Def->getName();
61     OS << "  " << Name;
62     
63     // If bit flags then emit expression (1 << i)
64     if (isBits)  OS << " = " << " 1 << " << i;
65
66     // Depending on 'if more in the list' emit comma
67     if (++i < N) OS << ",";
68     
69     OS << "\n";
70   }
71   
72   // Close enumeration
73   OS << "};\n";
74 }
75
76 //
77 // FeatureKeyValues - Emit data of all the subtarget features.  Used by command
78 // line.
79 //
80 void SubtargetEmitter::FeatureKeyValues(std::ostream &OS) {
81   // Gather and sort all the features
82   std::vector<Record*> FeatureList =
83                            Records.getAllDerivedDefinitions("SubtargetFeature");
84   sort(FeatureList.begin(), FeatureList.end(), LessRecord());
85
86   // Begin feature table
87   OS << "// Sorted (by key) array of values for CPU features.\n"
88      << "static llvm::SubtargetFeatureKV FeatureKV[] = {\n";
89   
90   // For each feature
91   for (unsigned i = 0, N = FeatureList.size(); i < N;) {
92     // Next feature
93     Record *Feature = FeatureList[i];
94
95     std::string Name = Feature->getName();
96     std::string CommandLineName = Feature->getValueAsString("Name");
97     std::string Desc = Feature->getValueAsString("Desc");
98     
99     // Emit as { "feature", "decription", feactureEnum }
100     OS << "  { "
101        << "\"" << CommandLineName << "\", "
102        << "\"" << Desc << "\", "
103        << Name
104        << " }";
105     
106     // Depending on 'if more in the list' emit comma
107     if (++i < N) OS << ",";
108     
109     OS << "\n";
110   }
111   
112   // End feature table
113   OS << "};\n";
114
115   // Emit size of table
116   OS<<"\nenum {\n";
117   OS<<"  FeatureKVSize = sizeof(FeatureKV)/sizeof(llvm::SubtargetFeatureKV)\n";
118   OS<<"};\n";
119 }
120
121 //
122 // CPUKeyValues - Emit data of all the subtarget processors.  Used by command
123 // line.
124 //
125 void SubtargetEmitter::CPUKeyValues(std::ostream &OS) {
126   // Gather and sort processor information
127   std::vector<Record*> ProcessorList =
128                           Records.getAllDerivedDefinitions("Processor");
129   sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
130
131   // Begin processor table
132   OS << "// Sorted (by key) array of values for CPU subtype.\n"
133      << "static const llvm::SubtargetFeatureKV SubTypeKV[] = {\n";
134      
135   // For each processor
136   for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
137     // Next processor
138     Record *Processor = ProcessorList[i];
139
140     std::string Name = Processor->getValueAsString("Name");
141     std::vector<Record*> FeatureList = 
142       Processor->getValueAsListOfDefs("Features");
143     
144     // Emit as { "cpu", "description", f1 | f2 | ... fn },
145     OS << "  { "
146        << "\"" << Name << "\", "
147        << "\"Select the " << Name << " processor\", ";
148     
149     if (FeatureList.empty()) {
150       OS << "0";
151     } else {
152       for (unsigned j = 0, M = FeatureList.size(); j < M;) {
153         Record *Feature = FeatureList[j];
154         std::string Name = Feature->getName();
155         OS << Name;
156         if (++j < M) OS << " | ";
157       }
158     }
159     
160     OS << " }";
161     
162     // Depending on 'if more in the list' emit comma
163     if (++i < N) OS << ",";
164     
165     OS << "\n";
166   }
167   
168   // End processor table
169   OS << "};\n";
170
171   // Emit size of table
172   OS<<"\nenum {\n";
173   OS<<"  SubTypeKVSize = sizeof(SubTypeKV)/sizeof(llvm::SubtargetFeatureKV)\n";
174   OS<<"};\n";
175 }
176
177 //
178 // CollectAllItinClasses - Gathers and enumerates all the itinerary classes.
179 // Returns itinerary class count.
180 //
181 unsigned SubtargetEmitter::CollectAllItinClasses(std::ostream &OS,
182                               std::map<std::string, unsigned> &ItinClassesMap) {
183   // Gather and sort all itinerary classes
184   std::vector<Record*> ItinClassList =
185                             Records.getAllDerivedDefinitions("InstrItinClass");
186   sort(ItinClassList.begin(), ItinClassList.end(), LessRecord());
187
188   // For each itinerary class
189   unsigned N = ItinClassList.size();
190   for (unsigned i = 0; i < N; i++) {
191     // Next itinerary class
192     Record *ItinClass = ItinClassList[i];
193     // Get name of itinerary class
194     std::string Name = ItinClass->getName();
195     // Assign itinerary class a unique number
196     ItinClassesMap[Name] = i;
197   }
198   
199   // Emit size of table
200   OS<<"\nenum {\n";
201   OS<<"  ItinClassesSize = " << N << "\n";
202   OS<<"};\n";
203
204   // Return itinerary class count
205   return N;
206 }
207
208 //
209 // FormItineraryString - Compose a string containing the data initialization
210 // for the specified itinerary.  N is the number of stages.
211 //
212 void SubtargetEmitter::FormItineraryString(Record *ItinData,
213                                            std::string &ItinString,
214                                            unsigned &NStages) {
215   // Get states list
216   std::vector<Record*> StageList = ItinData->getValueAsListOfDefs("Stages");
217
218   // For each stage
219   unsigned N = NStages = StageList.size();
220   for (unsigned i = 0; i < N; i++) {
221     // Next stage
222     Record *Stage = StageList[i];
223   
224     // Form string as ,{ cycles, u1 | u2 | ... | un }
225     int Cycles = Stage->getValueAsInt("Cycles");
226     ItinString += "  ,{ " + itostr(Cycles) + ", ";
227     
228     // Get unit list
229     std::vector<Record*> UnitList = Stage->getValueAsListOfDefs("Units");
230     
231     // For each unit
232     for (unsigned j = 0, M = UnitList.size(); j < M;) {
233       // Next unit
234       Record *Unit = UnitList[j];
235       
236       // Add name and bitwise or
237       ItinString += Unit->getName();
238       if (++j < M) ItinString += " | ";
239     }
240     
241     // Close off stage
242     ItinString += " }";
243   }
244 }
245
246 //
247 // EmitStageData - Generate unique itinerary stages.  Record itineraries for 
248 // processors.
249 //
250 void SubtargetEmitter::EmitStageData(std::ostream &OS,
251        unsigned NItinClasses,
252        std::map<std::string, unsigned> &ItinClassesMap, 
253        std::vector<std::vector<InstrItinerary> > &ProcList) {
254   // Gather processor iteraries
255   std::vector<Record*> ProcItinList =
256                        Records.getAllDerivedDefinitions("ProcessorItineraries");
257   
258   // If just no itinerary then don't bother
259   if (ProcItinList.size() < 2) return;
260
261   // Begin stages table
262   OS << "static llvm::InstrStage Stages[] = {\n"
263         "  { 0, 0 } // No itinerary\n";
264         
265   unsigned ItinEnum = 1;
266   std::map<std::string, unsigned> ItinMap;
267   for (unsigned i = 0, N = ProcItinList.size(); i < N; i++) {
268     // Next record
269     Record *Proc = ProcItinList[i];
270     
271     // Get processor itinerary name
272     std::string Name = Proc->getName();
273     
274     // Skip default
275     if (Name == "NoItineraries") continue;
276     
277     // Create and expand processor itinerary to cover all itinerary classes
278     std::vector<InstrItinerary> ItinList;
279     ItinList.resize(NItinClasses);
280     
281     // Get itinerary data list
282     std::vector<Record*> ItinDataList = Proc->getValueAsListOfDefs("IID");
283     
284     // For each itinerary data
285     for (unsigned j = 0, M = ItinDataList.size(); j < M; j++) {
286       // Next itinerary data
287       Record *ItinData = ItinDataList[j];
288       
289       // Get string and stage count
290       std::string ItinString;
291       unsigned NStages;
292       FormItineraryString(ItinData, ItinString, NStages);
293
294       // Check to see if it already exists
295       unsigned Find = ItinMap[ItinString];
296       
297       // If new itinerary
298       if (Find == 0) {
299         // Emit as ,{ cycles, u1 | u2 | ... | un } // index
300         OS << ItinString << " // " << ItinEnum << "\n";
301         ItinMap[ItinString] = Find = ItinEnum++;
302       }
303       
304       // Set up itinerary as location and location + stage count
305       InstrItinerary Intinerary = { Find, Find + NStages };
306
307       // Locate where to inject into processor itinerary table
308       std::string Name = ItinData->getValueAsDef("TheClass")->getName();
309       Find = ItinClassesMap[Name];
310       
311       // Inject - empty slots will be 0, 0
312       ItinList[Find] = Intinerary;
313     }
314     
315     // Add process itinerary to list
316     ProcList.push_back(ItinList);
317   }
318   
319   // End stages table
320   OS << "};\n";
321   
322   // Emit size of table
323   OS<<"\nenum {\n";
324   OS<<"  StagesSize = sizeof(Stages)/sizeof(llvm::InstrStage)\n";
325   OS<<"};\n";
326 }
327
328 //
329 // EmitProcessorData - Generate data for processor itineraries.
330 //
331 void SubtargetEmitter::EmitProcessorData(std::ostream &OS,
332       std::vector<std::vector<InstrItinerary> > &ProcList) {
333   // Get an iterator for processor itinerary stages
334   std::vector<std::vector<InstrItinerary> >::iterator
335       ProcListIter = ProcList.begin();
336   
337   // For each processor itinerary
338   std::vector<Record*> Itins =
339                        Records.getAllDerivedDefinitions("ProcessorItineraries");
340   for (unsigned i = 0, N = Itins.size(); i < N; i++) {
341     // Next record
342     Record *Itin = Itins[i];
343
344     // Get processor itinerary name
345     std::string Name = Itin->getName();
346     
347     // Skip default
348     if (Name == "NoItineraries") continue;
349
350     // Begin processor itinerary table
351     OS << "\n";
352     OS << "static llvm::InstrItinerary " << Name << "[] = {\n";
353     
354     // For each itinerary class
355     std::vector<InstrItinerary> &ItinList = *ProcListIter++;
356     unsigned ItinIndex = 0;
357     for (unsigned j = 0, M = ItinList.size(); j < M;) {
358       InstrItinerary &Intinerary = ItinList[j];
359       
360       // Emit in the form of { first, last } // index
361       if (Intinerary.First == 0) {
362         OS << "  { 0, 0 }";
363       } else {
364         OS << "  { " << Intinerary.First << ", " << Intinerary.Last << " }";
365       }
366       
367       // If more in list add comma
368       if (++j < M) OS << ",";
369       
370       OS << " // " << (j - 1) << "\n";
371     }
372     
373     // End processor itinerary table
374     OS << "};\n";
375   }
376   
377     OS << "\n";
378     OS << "static llvm::InstrItinerary NoItineraries[] = {};\n";
379 }
380
381 //
382 // EmitProcessorLookup - generate cpu name to itinerary lookup table.
383 //
384 void SubtargetEmitter::EmitProcessorLookup(std::ostream &OS) {
385   // Gather and sort processor information
386   std::vector<Record*> ProcessorList =
387                           Records.getAllDerivedDefinitions("Processor");
388   sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());
389
390   // Begin processor table
391   OS << "\n";
392   OS << "// Sorted (by key) array of itineraries for CPU subtype.\n"
393      << "static const llvm::SubtargetInfoKV SubTypeInfoKV[] = {\n";
394      
395   // For each processor
396   for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
397     // Next processor
398     Record *Processor = ProcessorList[i];
399
400     std::string Name = Processor->getValueAsString("Name");
401     std::string ProcItin = Processor->getValueAsDef("ProcItin")->getName();
402     
403     // Emit as { "cpu", procinit },
404     OS << "  { "
405        << "\"" << Name << "\", "
406        << "(void *)&" << ProcItin;
407         
408     OS << " }";
409     
410     // Depending on ''if more in the list'' emit comma
411     if (++i < N) OS << ",";
412     
413     OS << "\n";
414   }
415   
416   // End processor table
417   OS << "};\n";
418
419   // Emit size of table
420   OS<<"\nenum {\n";
421   OS<<"  SubTypeInfoKVSize = sizeof(SubTypeInfoKV)/"
422                             "sizeof(llvm::SubtargetInfoKV)\n";
423   OS<<"};\n";
424 }
425
426 //
427 // EmitData - Emits all stages and itineries, folding common patterns.
428 //
429 void SubtargetEmitter::EmitData(std::ostream &OS) {
430   std::map<std::string, unsigned> ItinClassesMap;
431   std::vector<std::vector<InstrItinerary> > ProcList;
432   
433   // Enumerate all the itinerary classes
434   unsigned NItinClasses = CollectAllItinClasses(OS, ItinClassesMap);
435   // Make sure the rest is worth the effort
436   HasItineraries = NItinClasses != 0;
437   
438   if (HasItineraries) {
439     // Emit the stage data
440     EmitStageData(OS, NItinClasses, ItinClassesMap, ProcList);
441     // Emit the processor itinerary data
442     EmitProcessorData(OS, ProcList);
443     // Emit the processor lookup data
444     EmitProcessorLookup(OS);
445   }
446 }
447
448 //
449 // ParseFeaturesFunction - Produces a subtarget specific function for parsing
450 // the subtarget features string.
451 //
452 void SubtargetEmitter::ParseFeaturesFunction(std::ostream &OS) {
453   std::vector<Record*> Features =
454                        Records.getAllDerivedDefinitions("SubtargetFeature");
455   sort(Features.begin(), Features.end(), LessRecord());
456
457   OS << "// ParseSubtargetFeatures - Parses features string setting specified\n" 
458         "// subtarget options.\n" 
459         "void llvm::";
460   OS << Target;
461   OS << "Subtarget::ParseSubtargetFeatures(const std::string &FS,\n"
462         "                                  const std::string &CPU) {\n"
463         "  SubtargetFeatures Features(FS);\n"
464         "  Features.setCPUIfNone(CPU);\n"
465         "  uint32_t Bits =  Features.getBits(SubTypeKV, SubTypeKVSize,\n"
466         "                                    FeatureKV, FeatureKVSize);\n";
467         
468   for (unsigned i = 0; i < Features.size(); i++) {
469     // Next record
470     Record *R = Features[i];
471     std::string Instance = R->getName();
472     std::string Name = R->getValueAsString("Name");
473     std::string Type = R->getValueAsString("Type");
474     std::string Attribute = R->getValueAsString("Attribute");
475     
476     OS << "  " << Attribute << " = (Bits & " << Instance << ") != 0;\n";
477   }
478   
479   if (HasItineraries) {
480     OS << "\n"
481        << "  InstrItinerary *Itinerary = (InstrItinerary *)"
482                         "Features.getInfo(SubTypeInfoKV, SubTypeInfoKVSize);\n"
483           "  InstrItins = InstrItineraryData(Stages, StagesSize, "
484                                              "Itinerary, ItinClassesSize);\n";
485   }
486   
487   OS << "}\n";
488 }
489
490 // 
491 // SubtargetEmitter::run - Main subtarget enumeration emitter.
492 //
493 void SubtargetEmitter::run(std::ostream &OS) {
494   Target = CodeGenTarget().getName();
495
496   EmitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);
497
498   OS << "#include \"llvm/Target/SubtargetFeature.h\"\n";
499   OS << "#include \"llvm/Target/TargetInstrItineraries.h\"\n\n";
500   
501   Enumeration(OS, "FuncUnit", true);
502   OS<<"\n";
503 //  Enumeration(OS, "InstrItinClass", false);
504 //  OS<<"\n";
505   Enumeration(OS, "SubtargetFeature", true);
506   OS<<"\n";
507   FeatureKeyValues(OS);
508   OS<<"\n";
509   CPUKeyValues(OS);
510   OS<<"\n";
511   EmitData(OS);
512   OS<<"\n";
513   ParseFeaturesFunction(OS);
514 }