slightly improve the runtime and code size of the Intrinsics info table by not
[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(raw_ostream &OS) {
26   EmitSourceFileHeader("Intrinsic Function Source Fragment", OS);
27   
28   std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records, TargetOnly);
29   
30   if (TargetOnly && !Ints.empty())
31     TargetPrefix = Ints[0].TargetPrefix;
32
33   EmitPrefix(OS);
34
35   // Emit the enum information.
36   EmitEnumInfo(Ints, OS);
37
38   // Emit the intrinsic ID -> name table.
39   EmitIntrinsicToNameTable(Ints, OS);
40
41   // Emit the intrinsic ID -> overload table.
42   EmitIntrinsicToOverloadTable(Ints, OS);
43
44   // Emit the function name recognizer.
45   EmitFnNameRecognizer(Ints, OS);
46   
47   // Emit the intrinsic verifier.
48   EmitVerifier(Ints, OS);
49   
50   // Emit the intrinsic declaration generator.
51   EmitGenerator(Ints, OS);
52   
53   // Emit the intrinsic parameter attributes.
54   EmitAttributes(Ints, OS);
55
56   // Emit intrinsic alias analysis mod/ref behavior.
57   EmitModRefBehavior(Ints, OS);
58
59   // Emit a list of intrinsics with corresponding GCC builtins.
60   EmitGCCBuiltinList(Ints, OS);
61
62   // Emit code to translate GCC builtins into LLVM intrinsics.
63   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
64
65   EmitSuffix(OS);
66 }
67
68 void IntrinsicEmitter::EmitPrefix(raw_ostream &OS) {
69   OS << "// VisualStudio defines setjmp as _setjmp\n"
70         "#if defined(_MSC_VER) && defined(setjmp)\n"
71         "#define setjmp_undefined_for_visual_studio\n"
72         "#undef setjmp\n"
73         "#endif\n\n";
74 }
75
76 void IntrinsicEmitter::EmitSuffix(raw_ostream &OS) {
77   OS << "#if defined(_MSC_VER) && defined(setjmp_undefined_for_visual_studio)\n"
78         "// let's return it to _setjmp state\n"
79         "#define setjmp _setjmp\n"
80         "#endif\n\n";
81 }
82
83 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
84                                     raw_ostream &OS) {
85   OS << "// Enum values for Intrinsics.h\n";
86   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
87   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
88     OS << "    " << Ints[i].EnumName;
89     OS << ((i != e-1) ? ", " : "  ");
90     OS << std::string(40-Ints[i].EnumName.size(), ' ') 
91       << "// " << Ints[i].Name << "\n";
92   }
93   OS << "#endif\n\n";
94 }
95
96 void IntrinsicEmitter::
97 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, 
98                      raw_ostream &OS) {
99   // Build a function name -> intrinsic name mapping.
100   std::map<std::string, unsigned> IntMapping;
101   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
102     IntMapping[Ints[i].Name.substr(5)] = i;
103     
104   OS << "// Function name -> enum value recognizer code.\n";
105   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
106   OS << "  Name += 5; Len -= 5;  // Skip over 'llvm.'\n";
107   OS << "  switch (*Name) {      // Dispatch on first letter.\n";
108   OS << "  default:\n";
109   // Emit the intrinsics in sorted order.
110   char LastChar = 0;
111   for (std::map<std::string, unsigned>::iterator I = IntMapping.begin(),
112        E = IntMapping.end(); I != E; ++I) {
113     if (I->first[0] != LastChar) {
114       LastChar = I->first[0];
115       OS << "    break;\n";
116       OS << "  case '" << LastChar << "':\n";
117     }
118     
119     // For overloaded intrinsics, only the prefix needs to match
120     std::string TheStr = I->first;
121     if (Ints[I->second].isOverloaded) {
122       TheStr += '.';  // Require "bswap." instead of bswap.
123       OS << "    if (Len > " << I->first.size();
124     } else {
125       OS << "    if (Len == " << I->first.size();
126     }
127       
128     OS << " && !memcmp(Name, \"" << TheStr << "\", "
129        << TheStr.size() << ")) return " << TargetPrefix << "Intrinsic::"
130        << Ints[I->second].EnumName << ";\n";
131   }
132   OS << "  }\n";
133   OS << "#endif\n\n";
134 }
135
136 void IntrinsicEmitter::
137 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, 
138                          raw_ostream &OS) {
139   OS << "// Intrinsic ID to name table\n";
140   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
141   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
142   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
143     OS << "  \"" << Ints[i].Name << "\",\n";
144   OS << "#endif\n\n";
145 }
146
147 void IntrinsicEmitter::
148 EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints, 
149                          raw_ostream &OS) {
150   OS << "// Intrinsic ID to overload table\n";
151   OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
152   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
153   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
154     OS << "  ";
155     if (Ints[i].isOverloaded)
156       OS << "true";
157     else
158       OS << "false";
159     OS << ",\n";
160   }
161   OS << "#endif\n\n";
162 }
163
164 static void EmitTypeForValueType(raw_ostream &OS, MVT::SimpleValueType VT) {
165   if (EVT(VT).isInteger()) {
166     unsigned BitWidth = EVT(VT).getSizeInBits();
167     OS << "IntegerType::get(Context, " << BitWidth << ")";
168   } else if (VT == MVT::Other) {
169     // MVT::OtherVT is used to mean the empty struct type here.
170     OS << "StructType::get(Context)";
171   } else if (VT == MVT::f32) {
172     OS << "Type::getFloatTy(Context)";
173   } else if (VT == MVT::f64) {
174     OS << "Type::getDoubleTy(Context)";
175   } else if (VT == MVT::f80) {
176     OS << "Type::getX86_FP80Ty(Context)";
177   } else if (VT == MVT::f128) {
178     OS << "Type::getFP128Ty(Context)";
179   } else if (VT == MVT::ppcf128) {
180     OS << "Type::getPPC_FP128Ty(Context)";
181   } else if (VT == MVT::isVoid) {
182     OS << "Type::getVoidTy(Context)";
183   } else if (VT == MVT::Metadata) {
184     OS << "Type::getMetadataTy(Context)";
185   } else {
186     assert(false && "Unsupported ValueType!");
187   }
188 }
189
190 static void EmitTypeGenerate(raw_ostream &OS, const Record *ArgType,
191                              unsigned &ArgNo);
192
193 static void EmitTypeGenerate(raw_ostream &OS,
194                              const std::vector<Record*> &ArgTypes,
195                              unsigned &ArgNo) {
196   if (ArgTypes.empty())
197     return EmitTypeForValueType(OS, MVT::isVoid);
198   
199   if (ArgTypes.size() == 1)
200     return EmitTypeGenerate(OS, ArgTypes.front(), ArgNo);
201
202   OS << "StructType::get(Context, ";
203
204   for (std::vector<Record*>::const_iterator
205          I = ArgTypes.begin(), E = ArgTypes.end(); I != E; ++I) {
206     EmitTypeGenerate(OS, *I, ArgNo);
207     OS << ", ";
208   }
209
210   OS << " NULL)";
211 }
212
213 static void EmitTypeGenerate(raw_ostream &OS, const Record *ArgType,
214                              unsigned &ArgNo) {
215   MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
216
217   if (ArgType->isSubClassOf("LLVMMatchType")) {
218     unsigned Number = ArgType->getValueAsInt("Number");
219     assert(Number < ArgNo && "Invalid matching number!");
220     if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
221       OS << "VectorType::getExtendedElementVectorType"
222          << "(dyn_cast<VectorType>(Tys[" << Number << "]))";
223     else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
224       OS << "VectorType::getTruncatedElementVectorType"
225          << "(dyn_cast<VectorType>(Tys[" << Number << "]))";
226     else
227       OS << "Tys[" << Number << "]";
228   } else if (VT == MVT::iAny || VT == MVT::fAny || VT == MVT::vAny) {
229     // NOTE: The ArgNo variable here is not the absolute argument number, it is
230     // the index of the "arbitrary" type in the Tys array passed to the
231     // Intrinsic::getDeclaration function. Consequently, we only want to
232     // increment it when we actually hit an overloaded type. Getting this wrong
233     // leads to very subtle bugs!
234     OS << "Tys[" << ArgNo++ << "]";
235   } else if (EVT(VT).isVector()) {
236     EVT VVT = VT;
237     OS << "VectorType::get(";
238     EmitTypeForValueType(OS, VVT.getVectorElementType().getSimpleVT().SimpleTy);
239     OS << ", " << VVT.getVectorNumElements() << ")";
240   } else if (VT == MVT::iPTR) {
241     OS << "PointerType::getUnqual(";
242     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
243     OS << ")";
244   } else if (VT == MVT::iPTRAny) {
245     // Make sure the user has passed us an argument type to overload. If not,
246     // treat it as an ordinary (not overloaded) intrinsic.
247     OS << "(" << ArgNo << " < numTys) ? Tys[" << ArgNo 
248     << "] : PointerType::getUnqual(";
249     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
250     OS << ")";
251     ++ArgNo;
252   } else if (VT == MVT::isVoid) {
253     if (ArgNo == 0)
254       OS << "Type::getVoidTy(Context)";
255     else
256       // MVT::isVoid is used to mean varargs here.
257       OS << "...";
258   } else {
259     EmitTypeForValueType(OS, VT);
260   }
261 }
262
263 /// RecordListComparator - Provide a deterministic comparator for lists of
264 /// records.
265 namespace {
266   typedef std::pair<std::vector<Record*>, std::vector<Record*> > RecPair;
267   struct RecordListComparator {
268     bool operator()(const RecPair &LHS,
269                     const RecPair &RHS) const {
270       unsigned i = 0;
271       const std::vector<Record*> *LHSVec = &LHS.first;
272       const std::vector<Record*> *RHSVec = &RHS.first;
273       unsigned RHSSize = RHSVec->size();
274       unsigned LHSSize = LHSVec->size();
275
276       for (; i != LHSSize; ++i) {
277         if (i == RHSSize) return false;  // RHS is shorter than LHS.
278         if ((*LHSVec)[i] != (*RHSVec)[i])
279           return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
280       }
281
282       if (i != RHSSize) return true;
283
284       i = 0;
285       LHSVec = &LHS.second;
286       RHSVec = &RHS.second;
287       RHSSize = RHSVec->size();
288       LHSSize = LHSVec->size();
289
290       for (i = 0; i != LHSSize; ++i) {
291         if (i == RHSSize) return false;  // RHS is shorter than LHS.
292         if ((*LHSVec)[i] != (*RHSVec)[i])
293           return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
294       }
295
296       return i != RHSSize;
297     }
298   };
299 }
300
301 void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints, 
302                                     raw_ostream &OS) {
303   OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
304   OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
305   OS << "  switch (ID) {\n";
306   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
307   
308   // This checking can emit a lot of very common code.  To reduce the amount of
309   // code that we emit, batch up cases that have identical types.  This avoids
310   // problems where GCC can run out of memory compiling Verifier.cpp.
311   typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
312   MapTy UniqueArgInfos;
313   
314   // Compute the unique argument type info.
315   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
316     UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
317                              Ints[i].IS.ParamTypeDefs)].push_back(i);
318
319   // Loop through the array, emitting one comparison for each batch.
320   for (MapTy::iterator I = UniqueArgInfos.begin(),
321        E = UniqueArgInfos.end(); I != E; ++I) {
322     for (unsigned i = 0, e = I->second.size(); i != e; ++i)
323       OS << "  case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
324          << Ints[I->second[i]].Name << "\n";
325     
326     const RecPair &ArgTypes = I->first;
327     const std::vector<Record*> &RetTys = ArgTypes.first;
328     const std::vector<Record*> &ParamTys = ArgTypes.second;
329     std::vector<unsigned> OverloadedTypeIndices;
330
331     OS << "    VerifyIntrinsicPrototype(ID, IF, " << RetTys.size() << ", "
332        << ParamTys.size();
333
334     // Emit return types.
335     for (unsigned j = 0, je = RetTys.size(); j != je; ++j) {
336       Record *ArgType = RetTys[j];
337       OS << ", ";
338
339       if (ArgType->isSubClassOf("LLVMMatchType")) {
340         unsigned Number = ArgType->getValueAsInt("Number");
341         assert(Number < OverloadedTypeIndices.size() &&
342                "Invalid matching number!");
343         Number = OverloadedTypeIndices[Number];
344         if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
345           OS << "~(ExtendedElementVectorType | " << Number << ")";
346         else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
347           OS << "~(TruncatedElementVectorType | " << Number << ")";
348         else
349           OS << "~" << Number;
350       } else {
351         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
352         OS << getEnumName(VT);
353
354         if (EVT(VT).isOverloaded())
355           OverloadedTypeIndices.push_back(j);
356
357         if (VT == MVT::isVoid && j != 0 && j != je - 1)
358           throw "Var arg type not last argument";
359       }
360     }
361
362     // Emit the parameter types.
363     for (unsigned j = 0, je = ParamTys.size(); j != je; ++j) {
364       Record *ArgType = ParamTys[j];
365       OS << ", ";
366
367       if (ArgType->isSubClassOf("LLVMMatchType")) {
368         unsigned Number = ArgType->getValueAsInt("Number");
369         assert(Number < OverloadedTypeIndices.size() &&
370                "Invalid matching number!");
371         Number = OverloadedTypeIndices[Number];
372         if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
373           OS << "~(ExtendedElementVectorType | " << Number << ")";
374         else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
375           OS << "~(TruncatedElementVectorType | " << Number << ")";
376         else
377           OS << "~" << Number;
378       } else {
379         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
380         OS << getEnumName(VT);
381
382         if (EVT(VT).isOverloaded())
383           OverloadedTypeIndices.push_back(j + RetTys.size());
384
385         if (VT == MVT::isVoid && j != 0 && j != je - 1)
386           throw "Var arg type not last argument";
387       }
388     }
389       
390     OS << ");\n";
391     OS << "    break;\n";
392   }
393   OS << "  }\n";
394   OS << "#endif\n\n";
395 }
396
397 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints, 
398                                      raw_ostream &OS) {
399   OS << "// Code for generating Intrinsic function declarations.\n";
400   OS << "#ifdef GET_INTRINSIC_GENERATOR\n";
401   OS << "  switch (id) {\n";
402   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
403   
404   // Similar to GET_INTRINSIC_VERIFIER, batch up cases that have identical
405   // types.
406   typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
407   MapTy UniqueArgInfos;
408   
409   // Compute the unique argument type info.
410   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
411     UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
412                              Ints[i].IS.ParamTypeDefs)].push_back(i);
413
414   // Loop through the array, emitting one generator for each batch.
415   std::string IntrinsicStr = TargetPrefix + "Intrinsic::";
416   
417   for (MapTy::iterator I = UniqueArgInfos.begin(),
418        E = UniqueArgInfos.end(); I != E; ++I) {
419     for (unsigned i = 0, e = I->second.size(); i != e; ++i)
420       OS << "  case " << IntrinsicStr << Ints[I->second[i]].EnumName 
421          << ":\t\t// " << Ints[I->second[i]].Name << "\n";
422     
423     const RecPair &ArgTypes = I->first;
424     const std::vector<Record*> &RetTys = ArgTypes.first;
425     const std::vector<Record*> &ParamTys = ArgTypes.second;
426
427     unsigned N = ParamTys.size();
428
429     if (N > 1 &&
430         getValueType(ParamTys[N - 1]->getValueAsDef("VT")) == MVT::isVoid) {
431       OS << "    IsVarArg = true;\n";
432       --N;
433     }
434
435     unsigned ArgNo = 0;
436     OS << "    ResultTy = ";
437     EmitTypeGenerate(OS, RetTys, ArgNo);
438     OS << ";\n";
439     
440     for (unsigned j = 0; j != N; ++j) {
441       OS << "    ArgTys.push_back(";
442       EmitTypeGenerate(OS, ParamTys[j], ArgNo);
443       OS << ");\n";
444     }
445
446     OS << "    break;\n";
447   }
448
449   OS << "  }\n";
450   OS << "#endif\n\n";
451 }
452
453 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
454 void IntrinsicEmitter::
455 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) {
456   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
457   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
458   if (TargetOnly)
459     OS << "static AttrListPtr getAttributes(" << TargetPrefix 
460        << "Intrinsic::ID id) {";
461   else
462     OS << "AttrListPtr Intrinsic::getAttributes(ID id) {";
463   OS << "  // No intrinsic can throw exceptions.\n";
464   OS << "  Attributes Attr = Attribute::NoUnwind;\n";
465   OS << "  switch (id) {\n";
466   OS << "  default: break;\n";
467   unsigned MaxArgAttrs = 0;
468   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
469     MaxArgAttrs =
470       std::max(MaxArgAttrs, unsigned(Ints[i].ArgumentAttributes.size()));
471     switch (Ints[i].ModRef) {
472     default: break;
473     case CodeGenIntrinsic::NoMem:
474       OS << "  case " << TargetPrefix << "Intrinsic::" << Ints[i].EnumName 
475          << ":\n";
476       break;
477     }
478   }
479   OS << "    Attr |= Attribute::ReadNone; // These do not access memory.\n";
480   OS << "    break;\n";
481   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
482     switch (Ints[i].ModRef) {
483     default: break;
484     case CodeGenIntrinsic::ReadArgMem:
485     case CodeGenIntrinsic::ReadMem:
486       OS << "  case " << TargetPrefix << "Intrinsic::" << Ints[i].EnumName 
487          << ":\n";
488       break;
489     }
490   }
491   OS << "    Attr |= Attribute::ReadOnly; // These do not write memory.\n";
492   OS << "    break;\n";
493   OS << "  }\n";
494   OS << "  AttributeWithIndex AWI[" << MaxArgAttrs+1 << "];\n";
495   OS << "  unsigned NumAttrs = 0;\n";
496   OS << "  switch (id) {\n";
497   OS << "  default: break;\n";
498   
499   // Add argument attributes for any intrinsics that have them.
500   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
501     if (Ints[i].ArgumentAttributes.empty()) continue;
502     
503     OS << "  case " << TargetPrefix << "Intrinsic::" << Ints[i].EnumName 
504        << ":\n";
505
506     std::vector<std::pair<unsigned, CodeGenIntrinsic::ArgAttribute> > ArgAttrs =
507       Ints[i].ArgumentAttributes;
508     // Sort by argument index.
509     std::sort(ArgAttrs.begin(), ArgAttrs.end());
510
511     unsigned NumArgsWithAttrs = 0;
512
513     while (!ArgAttrs.empty()) {
514       unsigned ArgNo = ArgAttrs[0].first;
515       
516       OS << "    AWI[" << NumArgsWithAttrs++ << "] = AttributeWithIndex::get("
517          << ArgNo+1 << ", 0";
518
519       while (!ArgAttrs.empty() && ArgAttrs[0].first == ArgNo) {
520         switch (ArgAttrs[0].second) {
521         default: assert(0 && "Unknown arg attribute");
522         case CodeGenIntrinsic::NoCapture:
523           OS << "|Attribute::NoCapture";
524           break;
525         }
526         ArgAttrs.erase(ArgAttrs.begin());
527       }
528       OS << ");\n";
529     }
530     
531     OS << "    NumAttrs = " << NumArgsWithAttrs << ";\n";
532     OS << "    break;\n";
533   }
534   
535   OS << "  }\n";
536   OS << "  AWI[NumAttrs] = AttributeWithIndex::get(~0, Attr);\n";
537   OS << "  return AttrListPtr::get(AWI, NumAttrs+1);\n";
538   OS << "}\n";
539   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
540 }
541
542 /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavior.
543 void IntrinsicEmitter::
544 EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
545   OS << "// Determine intrinsic alias analysis mod/ref behavior.\n";
546   OS << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n";
547   OS << "switch (iid) {\n";
548   OS << "default:\n    return UnknownModRefBehavior;\n";
549   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
550     if (Ints[i].ModRef == CodeGenIntrinsic::ReadWriteMem)
551       continue;
552     OS << "case " << TargetPrefix << "Intrinsic::" << Ints[i].EnumName
553       << ":\n";
554     switch (Ints[i].ModRef) {
555     default:
556       assert(false && "Unknown Mod/Ref type!");
557     case CodeGenIntrinsic::NoMem:
558       OS << "  return DoesNotAccessMemory;\n";
559       break;
560     case CodeGenIntrinsic::ReadArgMem:
561     case CodeGenIntrinsic::ReadMem:
562       OS << "  return OnlyReadsMemory;\n";
563       break;
564     case CodeGenIntrinsic::ReadWriteArgMem:
565       OS << "  return AccessesArguments;\n";
566       break;
567     }
568   }
569   OS << "}\n";
570   OS << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
571 }
572
573 void IntrinsicEmitter::
574 EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
575   OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
576   OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
577   OS << "  switch (F->getIntrinsicID()) {\n";
578   OS << "  default: BuiltinName = \"\"; break;\n";
579   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
580     if (!Ints[i].GCCBuiltinName.empty()) {
581       OS << "  case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
582          << Ints[i].GCCBuiltinName << "\"; break;\n";
583     }
584   }
585   OS << "  }\n";
586   OS << "#endif\n\n";
587 }
588
589 /// EmitBuiltinComparisons - Emit comparisons to determine whether the specified
590 /// sorted range of builtin names is equal to the current builtin.  This breaks
591 /// it down into a simple tree.
592 ///
593 /// At this point, we know that all the builtins in the range have the same name
594 /// for the first 'CharStart' characters.  Only the end of the name needs to be
595 /// discriminated.
596 typedef std::map<std::string, std::string>::const_iterator StrMapIterator;
597 static void EmitBuiltinComparisons(StrMapIterator Start, StrMapIterator End,
598                                    unsigned CharStart, unsigned Indent,
599                                    std::string TargetPrefix, raw_ostream &OS) {
600   if (Start == End) return; // empty range.
601   
602   // Determine what, if anything, is the same about all these strings.
603   std::string CommonString = Start->first;
604   unsigned NumInRange = 0;
605   for (StrMapIterator I = Start; I != End; ++I, ++NumInRange) {
606     // Find the first character that doesn't match.
607     const std::string &ThisStr = I->first;
608     unsigned NonMatchChar = CharStart;
609     while (NonMatchChar < CommonString.size() && 
610            NonMatchChar < ThisStr.size() &&
611            CommonString[NonMatchChar] == ThisStr[NonMatchChar])
612       ++NonMatchChar;
613     // Truncate off pieces that don't match.
614     CommonString.resize(NonMatchChar);
615   }
616   
617   // Just compare the rest of the string.
618   if (NumInRange == 1) {
619     if (CharStart != CommonString.size()) {
620       OS << std::string(Indent*2, ' ') << "if (!memcmp(BuiltinName";
621       if (CharStart) OS << "+" << CharStart;
622       OS << ", \"" << (CommonString.c_str()+CharStart) << "\", ";
623       OS << CommonString.size() - CharStart << "))\n";
624       ++Indent;
625     }
626     OS << std::string(Indent*2, ' ') << "IntrinsicID = " << TargetPrefix
627        << "Intrinsic::";
628     OS << Start->second << ";\n";
629     return;
630   }
631
632   // At this point, we potentially have a common prefix for these builtins, emit
633   // a check for this common prefix.
634   if (CommonString.size() != CharStart) {
635     OS << std::string(Indent*2, ' ') << "if (!memcmp(BuiltinName";
636     if (CharStart) OS << "+" << CharStart;
637     OS << ", \"" << (CommonString.c_str()+CharStart) << "\", ";
638     OS << CommonString.size()-CharStart << ")) {\n";
639     
640     EmitBuiltinComparisons(Start, End, CommonString.size(), Indent+1, 
641                            TargetPrefix, OS);
642     OS << std::string(Indent*2, ' ') << "}\n";
643     return;
644   }
645   
646   // Output a switch on the character that differs across the set.
647   OS << std::string(Indent*2, ' ') << "switch (BuiltinName[" << CharStart
648       << "]) {";
649   if (CharStart)
650     OS << "  // \"" << std::string(Start->first.begin(), 
651                                    Start->first.begin()+CharStart) << "\"";
652   OS << "\n";
653   
654   for (StrMapIterator I = Start; I != End; ) {
655     char ThisChar = I->first[CharStart];
656     OS << std::string(Indent*2, ' ') << "case '" << ThisChar << "':\n";
657     // Figure out the range that has this common character.
658     StrMapIterator NextChar = I;
659     for (++NextChar; NextChar != End && NextChar->first[CharStart] == ThisChar;
660          ++NextChar)
661       /*empty*/;
662     EmitBuiltinComparisons(I, NextChar, CharStart+1, Indent+1, TargetPrefix,OS);
663     OS << std::string(Indent*2, ' ') << "  break;\n";
664     I = NextChar;
665   }
666   OS << std::string(Indent*2, ' ') << "}\n";
667 }
668
669 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
670 /// same target, and we already checked it.
671 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
672                                const std::string &TargetPrefix,
673                                raw_ostream &OS) {
674   // Rearrange the builtins by length.
675   std::vector<std::map<std::string, std::string> > BuiltinsByLen;
676   BuiltinsByLen.reserve(100);
677   
678   for (StrMapIterator I = BIM.begin(), E = BIM.end(); I != E; ++I) {
679     if (I->first.size() >= BuiltinsByLen.size())
680       BuiltinsByLen.resize(I->first.size()+1);
681     BuiltinsByLen[I->first.size()].insert(*I);
682   }
683   
684   // Now that we have all the builtins by their length, emit a switch stmt.
685   OS << "    switch (strlen(BuiltinName)) {\n";
686   OS << "    default: break;\n";
687   for (unsigned i = 0, e = BuiltinsByLen.size(); i != e; ++i) {
688     if (BuiltinsByLen[i].empty()) continue;
689     OS << "    case " << i << ":\n";
690     EmitBuiltinComparisons(BuiltinsByLen[i].begin(), BuiltinsByLen[i].end(),
691                            0, 3, TargetPrefix, OS);
692     OS << "      break;\n";
693   }
694   OS << "    }\n";
695 }
696
697         
698 void IntrinsicEmitter::
699 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, 
700                              raw_ostream &OS) {
701   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
702   BIMTy BuiltinMap;
703   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
704     if (!Ints[i].GCCBuiltinName.empty()) {
705       // Get the map for this target prefix.
706       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
707       
708       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
709                                      Ints[i].EnumName)).second)
710         throw "Intrinsic '" + Ints[i].TheDef->getName() +
711               "': duplicate GCC builtin name!";
712     }
713   }
714   
715   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
716   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
717   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
718   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
719   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
720   
721   if (TargetOnly) {
722     OS << "static " << TargetPrefix << "Intrinsic::ID "
723        << "getIntrinsicForGCCBuiltin(const char "
724        << "*TargetPrefix, const char *BuiltinName) {\n";
725     OS << "  " << TargetPrefix << "Intrinsic::ID IntrinsicID = ";
726   } else {
727     OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char "
728        << "*TargetPrefix, const char *BuiltinName) {\n";
729     OS << "  Intrinsic::ID IntrinsicID = ";
730   }
731   
732   if (TargetOnly)
733     OS << "(" << TargetPrefix<< "Intrinsic::ID)";
734
735   OS << "Intrinsic::not_intrinsic;\n";
736   
737   // Note: this could emit significantly better code if we cared.
738   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
739     OS << "  ";
740     if (!I->first.empty())
741       OS << "if (!strcmp(TargetPrefix, \"" << I->first << "\")) ";
742     else
743       OS << "/* Target Independent Builtins */ ";
744     OS << "{\n";
745
746     // Emit the comparisons for this target prefix.
747     EmitTargetBuiltins(I->second, TargetPrefix, OS);
748     OS << "  }\n";
749   }
750   OS << "  return IntrinsicID;\n";
751   OS << "}\n";
752   OS << "#endif\n\n";
753 }