Wrap MVT::ValueType in a struct to get type safety
[oota-llvm.git] / utils / TableGen / IntrinsicEmitter.cpp
1 //===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
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 information about intrinsic functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CodeGenTarget.h"
15 #include "IntrinsicEmitter.h"
16 #include "Record.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include <algorithm>
19 using namespace llvm;
20
21 //===----------------------------------------------------------------------===//
22 // IntrinsicEmitter Implementation
23 //===----------------------------------------------------------------------===//
24
25 void IntrinsicEmitter::run(std::ostream &OS) {
26   EmitSourceFileHeader("Intrinsic Function Source Fragment", OS);
27   
28   std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records);
29
30   // Emit the enum information.
31   EmitEnumInfo(Ints, OS);
32
33   // Emit the intrinsic ID -> name table.
34   EmitIntrinsicToNameTable(Ints, OS);
35   
36   // Emit the function name recognizer.
37   EmitFnNameRecognizer(Ints, OS);
38   
39   // Emit the intrinsic verifier.
40   EmitVerifier(Ints, OS);
41   
42   // Emit the intrinsic declaration generator.
43   EmitGenerator(Ints, OS);
44   
45   // Emit the intrinsic parameter attributes.
46   EmitAttributes(Ints, OS);
47
48   // Emit a list of intrinsics with corresponding GCC builtins.
49   EmitGCCBuiltinList(Ints, OS);
50
51   // Emit code to translate GCC builtins into LLVM intrinsics.
52   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
53 }
54
55 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
56                                     std::ostream &OS) {
57   OS << "// Enum values for Intrinsics.h\n";
58   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
59   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
60     OS << "    " << Ints[i].EnumName;
61     OS << ((i != e-1) ? ", " : "  ");
62     OS << std::string(40-Ints[i].EnumName.size(), ' ') 
63       << "// " << Ints[i].Name << "\n";
64   }
65   OS << "#endif\n\n";
66 }
67
68 void IntrinsicEmitter::
69 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, 
70                      std::ostream &OS) {
71   // Build a function name -> intrinsic name mapping.
72   std::map<std::string, unsigned> IntMapping;
73   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
74     IntMapping[Ints[i].Name] = i;
75     
76   OS << "// Function name -> enum value recognizer code.\n";
77   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
78   OS << "  switch (Name[5]) {\n";
79   OS << "  default:\n";
80   // Emit the intrinsics in sorted order.
81   char LastChar = 0;
82   for (std::map<std::string, unsigned>::iterator I = IntMapping.begin(),
83        E = IntMapping.end(); I != E; ++I) {
84     if (I->first[5] != LastChar) {
85       LastChar = I->first[5];
86       OS << "    break;\n";
87       OS << "  case '" << LastChar << "':\n";
88     }
89     
90     // For overloaded intrinsics, only the prefix needs to match
91     if (Ints[I->second].isOverloaded)
92       OS << "    if (Len > " << I->first.size()
93        << " && !memcmp(Name, \"" << I->first << ".\", "
94        << (I->first.size() + 1) << ")) return Intrinsic::"
95        << Ints[I->second].EnumName << ";\n";
96     else 
97       OS << "    if (Len == " << I->first.size()
98          << " && !memcmp(Name, \"" << I->first << "\", "
99          << I->first.size() << ")) return Intrinsic::"
100          << Ints[I->second].EnumName << ";\n";
101   }
102   OS << "  }\n";
103   OS << "#endif\n\n";
104 }
105
106 void IntrinsicEmitter::
107 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, 
108                          std::ostream &OS) {
109   OS << "// Intrinsic ID to name table\n";
110   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
111   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
112   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
113     OS << "  \"" << Ints[i].Name << "\",\n";
114   OS << "#endif\n\n";
115 }
116
117 static void EmitTypeForValueType(std::ostream &OS, MVT::SimpleValueType VT) {
118   if (MVT(VT).isInteger()) {
119     unsigned BitWidth = MVT(VT).getSizeInBits();
120     OS << "IntegerType::get(" << BitWidth << ")";
121   } else if (VT == MVT::Other) {
122     // MVT::OtherVT is used to mean the empty struct type here.
123     OS << "StructType::get(std::vector<const Type *>())";
124   } else if (VT == MVT::f32) {
125     OS << "Type::FloatTy";
126   } else if (VT == MVT::f64) {
127     OS << "Type::DoubleTy";
128   } else if (VT == MVT::f80) {
129     OS << "Type::X86_FP80Ty";
130   } else if (VT == MVT::f128) {
131     OS << "Type::FP128Ty";
132   } else if (VT == MVT::ppcf128) {
133     OS << "Type::PPC_FP128Ty";
134   } else if (VT == MVT::isVoid) {
135     OS << "Type::VoidTy";
136   } else {
137     assert(false && "Unsupported ValueType!");
138   }
139 }
140
141 static void EmitTypeGenerate(std::ostream &OS, Record *ArgType, 
142                              unsigned &ArgNo) {
143   MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
144
145   if (ArgType->isSubClassOf("LLVMMatchType")) {
146     unsigned Number = ArgType->getValueAsInt("Number");
147     assert(Number < ArgNo && "Invalid matching number!");
148     OS << "Tys[" << Number << "]";
149   } else if (VT == MVT::iAny || VT == MVT::fAny) {
150     // NOTE: The ArgNo variable here is not the absolute argument number, it is
151     // the index of the "arbitrary" type in the Tys array passed to the
152     // Intrinsic::getDeclaration function. Consequently, we only want to
153     // increment it when we actually hit an overloaded type. Getting this wrong
154     // leads to very subtle bugs!
155     OS << "Tys[" << ArgNo++ << "]";
156   } else if (MVT(VT).isVector()) {
157     MVT VVT = VT;
158     OS << "VectorType::get(";
159     EmitTypeForValueType(OS, VVT.getVectorElementType().getSimpleVT());
160     OS << ", " << VVT.getVectorNumElements() << ")";
161   } else if (VT == MVT::iPTR) {
162     OS << "PointerType::getUnqual(";
163     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
164     OS << ")";
165   } else if (VT == MVT::isVoid) {
166     if (ArgNo == 0)
167       OS << "Type::VoidTy";
168     else
169       // MVT::isVoid is used to mean varargs here.
170       OS << "...";
171   } else {
172     EmitTypeForValueType(OS, VT);
173   }
174 }
175
176 /// RecordListComparator - Provide a determinstic comparator for lists of
177 /// records.
178 namespace {
179   struct RecordListComparator {
180     bool operator()(const std::vector<Record*> &LHS,
181                     const std::vector<Record*> &RHS) const {
182       unsigned i = 0;
183       do {
184         if (i == RHS.size()) return false;  // RHS is shorter than LHS.
185         if (LHS[i] != RHS[i])
186           return LHS[i]->getName() < RHS[i]->getName();
187       } while (++i != LHS.size());
188       
189       return i != RHS.size();
190     }
191   };
192 }
193
194 void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints, 
195                                     std::ostream &OS) {
196   OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
197   OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
198   OS << "  switch (ID) {\n";
199   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
200   
201   // This checking can emit a lot of very common code.  To reduce the amount of
202   // code that we emit, batch up cases that have identical types.  This avoids
203   // problems where GCC can run out of memory compiling Verifier.cpp.
204   typedef std::map<std::vector<Record*>, std::vector<unsigned>, 
205     RecordListComparator> MapTy;
206   MapTy UniqueArgInfos;
207   
208   // Compute the unique argument type info.
209   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
210     UniqueArgInfos[Ints[i].ArgTypeDefs].push_back(i);
211
212   // Loop through the array, emitting one comparison for each batch.
213   for (MapTy::iterator I = UniqueArgInfos.begin(),
214        E = UniqueArgInfos.end(); I != E; ++I) {
215     for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
216       OS << "  case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
217          << Ints[I->second[i]].Name << "\n";
218     }
219     
220     const std::vector<Record*> &ArgTypes = I->first;
221     OS << "    VerifyIntrinsicPrototype(ID, IF, " << ArgTypes.size() << ", ";
222     for (unsigned j = 0; j != ArgTypes.size(); ++j) {
223       Record *ArgType = ArgTypes[j];
224       if (ArgType->isSubClassOf("LLVMMatchType")) {
225         unsigned Number = ArgType->getValueAsInt("Number");
226         assert(Number < j && "Invalid matching number!");
227         OS << "~" << Number;
228       } else {
229         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
230         OS << getEnumName(VT);
231         if (VT == MVT::isVoid && j != 0 && j != ArgTypes.size()-1)
232           throw "Var arg type not last argument";
233       }
234       if (j != ArgTypes.size()-1)
235         OS << ", ";
236     }
237       
238     OS << ");\n";
239     OS << "    break;\n";
240   }
241   OS << "  }\n";
242   OS << "#endif\n\n";
243 }
244
245 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints, 
246                                      std::ostream &OS) {
247   OS << "// Code for generating Intrinsic function declarations.\n";
248   OS << "#ifdef GET_INTRINSIC_GENERATOR\n";
249   OS << "  switch (id) {\n";
250   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
251   
252   // Similar to GET_INTRINSIC_VERIFIER, batch up cases that have identical
253   // types.
254   typedef std::map<std::vector<Record*>, std::vector<unsigned>, 
255     RecordListComparator> MapTy;
256   MapTy UniqueArgInfos;
257   
258   // Compute the unique argument type info.
259   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
260     UniqueArgInfos[Ints[i].ArgTypeDefs].push_back(i);
261
262   // Loop through the array, emitting one generator for each batch.
263   for (MapTy::iterator I = UniqueArgInfos.begin(),
264        E = UniqueArgInfos.end(); I != E; ++I) {
265     for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
266       OS << "  case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
267          << Ints[I->second[i]].Name << "\n";
268     }
269     
270     const std::vector<Record*> &ArgTypes = I->first;
271     unsigned N = ArgTypes.size();
272
273     if (N > 1 &&
274         getValueType(ArgTypes[N-1]->getValueAsDef("VT")) == MVT::isVoid) {
275       OS << "    IsVarArg = true;\n";
276       --N;
277     }
278     
279     unsigned ArgNo = 0;
280     OS << "    ResultTy = ";
281     EmitTypeGenerate(OS, ArgTypes[0], ArgNo);
282     OS << ";\n";
283     
284     for (unsigned j = 1; j != N; ++j) {
285       OS << "    ArgTys.push_back(";
286       EmitTypeGenerate(OS, ArgTypes[j], ArgNo);
287       OS << ");\n";
288     }
289     OS << "    break;\n";
290   }
291   OS << "  }\n";
292   OS << "#endif\n\n";
293 }
294
295 void IntrinsicEmitter::
296 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) {
297   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
298   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
299   OS << "  switch (id) {\n";
300   OS << "  default: break;\n";
301   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
302     switch (Ints[i].ModRef) {
303     default: break;
304     case CodeGenIntrinsic::NoMem:
305       OS << "  case Intrinsic::" << Ints[i].EnumName << ":\n";
306       break;
307     }
308   }
309   OS << "    Attr |= ParamAttr::ReadNone; // These do not access memory.\n";
310   OS << "    break;\n";
311   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
312     switch (Ints[i].ModRef) {
313     default: break;
314     case CodeGenIntrinsic::ReadArgMem:
315     case CodeGenIntrinsic::ReadMem:
316       OS << "  case Intrinsic::" << Ints[i].EnumName << ":\n";
317       break;
318     }
319   }
320   OS << "    Attr |= ParamAttr::ReadOnly; // These do not write memory.\n";
321   OS << "    break;\n";
322   OS << "  }\n";
323   OS << "#endif\n\n";
324 }
325
326 void IntrinsicEmitter::
327 EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
328   OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
329   OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
330   OS << "  switch (F->getIntrinsicID()) {\n";
331   OS << "  default: BuiltinName = \"\"; break;\n";
332   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
333     if (!Ints[i].GCCBuiltinName.empty()) {
334       OS << "  case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
335          << Ints[i].GCCBuiltinName << "\"; break;\n";
336     }
337   }
338   OS << "  }\n";
339   OS << "#endif\n\n";
340 }
341
342 /// EmitBuiltinComparisons - Emit comparisons to determine whether the specified
343 /// sorted range of builtin names is equal to the current builtin.  This breaks
344 /// it down into a simple tree.
345 ///
346 /// At this point, we know that all the builtins in the range have the same name
347 /// for the first 'CharStart' characters.  Only the end of the name needs to be
348 /// discriminated.
349 typedef std::map<std::string, std::string>::const_iterator StrMapIterator;
350 static void EmitBuiltinComparisons(StrMapIterator Start, StrMapIterator End,
351                                    unsigned CharStart, unsigned Indent,
352                                    std::ostream &OS) {
353   if (Start == End) return; // empty range.
354   
355   // Determine what, if anything, is the same about all these strings.
356   std::string CommonString = Start->first;
357   unsigned NumInRange = 0;
358   for (StrMapIterator I = Start; I != End; ++I, ++NumInRange) {
359     // Find the first character that doesn't match.
360     const std::string &ThisStr = I->first;
361     unsigned NonMatchChar = CharStart;
362     while (NonMatchChar < CommonString.size() && 
363            NonMatchChar < ThisStr.size() &&
364            CommonString[NonMatchChar] == ThisStr[NonMatchChar])
365       ++NonMatchChar;
366     // Truncate off pieces that don't match.
367     CommonString.resize(NonMatchChar);
368   }
369   
370   // Just compare the rest of the string.
371   if (NumInRange == 1) {
372     if (CharStart != CommonString.size()) {
373       OS << std::string(Indent*2, ' ') << "if (!memcmp(BuiltinName";
374       if (CharStart) OS << "+" << CharStart;
375       OS << ", \"" << (CommonString.c_str()+CharStart) << "\", ";
376       OS << CommonString.size() - CharStart << "))\n";
377       ++Indent;
378     }
379     OS << std::string(Indent*2, ' ') << "IntrinsicID = Intrinsic::";
380     OS << Start->second << ";\n";
381     return;
382   }
383
384   // At this point, we potentially have a common prefix for these builtins, emit
385   // a check for this common prefix.
386   if (CommonString.size() != CharStart) {
387     OS << std::string(Indent*2, ' ') << "if (!memcmp(BuiltinName";
388     if (CharStart) OS << "+" << CharStart;
389     OS << ", \"" << (CommonString.c_str()+CharStart) << "\", ";
390     OS << CommonString.size()-CharStart << ")) {\n";
391     
392     EmitBuiltinComparisons(Start, End, CommonString.size(), Indent+1, OS);
393     OS << std::string(Indent*2, ' ') << "}\n";
394     return;
395   }
396   
397   // Output a switch on the character that differs across the set.
398   OS << std::string(Indent*2, ' ') << "switch (BuiltinName[" << CharStart
399       << "]) {";
400   if (CharStart)
401     OS << "  // \"" << std::string(Start->first.begin(), 
402                                    Start->first.begin()+CharStart) << "\"";
403   OS << "\n";
404   
405   for (StrMapIterator I = Start; I != End; ) {
406     char ThisChar = I->first[CharStart];
407     OS << std::string(Indent*2, ' ') << "case '" << ThisChar << "':\n";
408     // Figure out the range that has this common character.
409     StrMapIterator NextChar = I;
410     for (++NextChar; NextChar != End && NextChar->first[CharStart] == ThisChar;
411          ++NextChar)
412       /*empty*/;
413     EmitBuiltinComparisons(I, NextChar, CharStart+1, Indent+1, OS);
414     OS << std::string(Indent*2, ' ') << "  break;\n";
415     I = NextChar;
416   }
417   OS << std::string(Indent*2, ' ') << "}\n";
418 }
419
420 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
421 /// same target, and we already checked it.
422 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
423                                std::ostream &OS) {
424   // Rearrange the builtins by length.
425   std::vector<std::map<std::string, std::string> > BuiltinsByLen;
426   BuiltinsByLen.reserve(100);
427   
428   for (StrMapIterator I = BIM.begin(), E = BIM.end(); I != E; ++I) {
429     if (I->first.size() >= BuiltinsByLen.size())
430       BuiltinsByLen.resize(I->first.size()+1);
431     BuiltinsByLen[I->first.size()].insert(*I);
432   }
433   
434   // Now that we have all the builtins by their length, emit a switch stmt.
435   OS << "    switch (strlen(BuiltinName)) {\n";
436   OS << "    default: break;\n";
437   for (unsigned i = 0, e = BuiltinsByLen.size(); i != e; ++i) {
438     if (BuiltinsByLen[i].empty()) continue;
439     OS << "    case " << i << ":\n";
440     EmitBuiltinComparisons(BuiltinsByLen[i].begin(), BuiltinsByLen[i].end(),
441                            0, 3, OS);
442     OS << "      break;\n";
443   }
444   OS << "    }\n";
445 }
446
447         
448 void IntrinsicEmitter::
449 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, 
450                              std::ostream &OS) {
451   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
452   BIMTy BuiltinMap;
453   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
454     if (!Ints[i].GCCBuiltinName.empty()) {
455       // Get the map for this target prefix.
456       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
457       
458       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
459                                      Ints[i].EnumName)).second)
460         throw "Intrinsic '" + Ints[i].TheDef->getName() +
461               "': duplicate GCC builtin name!";
462     }
463   }
464   
465   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
466   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
467   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
468   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
469   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
470   OS << "  IntrinsicID = Intrinsic::not_intrinsic;\n";
471   
472   // Note: this could emit significantly better code if we cared.
473   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
474     OS << "  ";
475     if (!I->first.empty())
476       OS << "if (!strcmp(TargetPrefix, \"" << I->first << "\")) ";
477     else
478       OS << "/* Target Independent Builtins */ ";
479     OS << "{\n";
480
481     // Emit the comparisons for this target prefix.
482     EmitTargetBuiltins(I->second, OS);
483     OS << "  }\n";
484   }
485   OS << "#endif\n\n";
486 }