This patch adds support for the vector quadword add/sub instructions introduced
[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 "CodeGenIntrinsics.h"
15 #include "CodeGenTarget.h"
16 #include "SequenceToOffsetTable.h"
17 #include "TableGenBackends.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/TableGen/StringMatcher.h"
22 #include "llvm/TableGen/TableGenBackend.h"
23 #include <algorithm>
24 using namespace llvm;
25
26 namespace {
27 class IntrinsicEmitter {
28   RecordKeeper &Records;
29   bool TargetOnly;
30   std::string TargetPrefix;
31
32 public:
33   IntrinsicEmitter(RecordKeeper &R, bool T)
34     : Records(R), TargetOnly(T) {}
35
36   void run(raw_ostream &OS);
37
38   void EmitPrefix(raw_ostream &OS);
39
40   void EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
41                     raw_ostream &OS);
42
43   void EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints,
44                             raw_ostream &OS);
45   void EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints,
46                                 raw_ostream &OS);
47   void EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints,
48                                     raw_ostream &OS);
49   void EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints,
50                      raw_ostream &OS);
51   void EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints,
52                       raw_ostream &OS);
53   void EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints,
54                           raw_ostream &OS);
55   void EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
56                                     raw_ostream &OS);
57   void EmitIntrinsicToMSBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
58                                    raw_ostream &OS);
59   void EmitSuffix(raw_ostream &OS);
60 };
61 } // End anonymous namespace
62
63 //===----------------------------------------------------------------------===//
64 // IntrinsicEmitter Implementation
65 //===----------------------------------------------------------------------===//
66
67 void IntrinsicEmitter::run(raw_ostream &OS) {
68   emitSourceFileHeader("Intrinsic Function Source Fragment", OS);
69
70   std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records, TargetOnly);
71
72   if (TargetOnly && !Ints.empty())
73     TargetPrefix = Ints[0].TargetPrefix;
74
75   EmitPrefix(OS);
76
77   // Emit the enum information.
78   EmitEnumInfo(Ints, OS);
79
80   // Emit the intrinsic ID -> name table.
81   EmitIntrinsicToNameTable(Ints, OS);
82
83   // Emit the intrinsic ID -> overload table.
84   EmitIntrinsicToOverloadTable(Ints, OS);
85
86   // Emit the function name recognizer.
87   EmitFnNameRecognizer(Ints, OS);
88
89   // Emit the intrinsic declaration generator.
90   EmitGenerator(Ints, OS);
91
92   // Emit the intrinsic parameter attributes.
93   EmitAttributes(Ints, OS);
94
95   // Emit intrinsic alias analysis mod/ref behavior.
96   EmitModRefBehavior(Ints, OS);
97
98   // Emit code to translate GCC builtins into LLVM intrinsics.
99   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
100
101   // Emit code to translate MS builtins into LLVM intrinsics.
102   EmitIntrinsicToMSBuiltinMap(Ints, OS);
103
104   EmitSuffix(OS);
105 }
106
107 void IntrinsicEmitter::EmitPrefix(raw_ostream &OS) {
108   OS << "// VisualStudio defines setjmp as _setjmp\n"
109         "#if defined(_MSC_VER) && defined(setjmp) && \\\n"
110         "                         !defined(setjmp_undefined_for_msvc)\n"
111         "#  pragma push_macro(\"setjmp\")\n"
112         "#  undef setjmp\n"
113         "#  define setjmp_undefined_for_msvc\n"
114         "#endif\n\n";
115 }
116
117 void IntrinsicEmitter::EmitSuffix(raw_ostream &OS) {
118   OS << "#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)\n"
119         "// let's return it to _setjmp state\n"
120         "#  pragma pop_macro(\"setjmp\")\n"
121         "#  undef setjmp_undefined_for_msvc\n"
122         "#endif\n\n";
123 }
124
125 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
126                                     raw_ostream &OS) {
127   OS << "// Enum values for Intrinsics.h\n";
128   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
129   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
130     OS << "    " << Ints[i].EnumName;
131     OS << ((i != e-1) ? ", " : "  ");
132     if (Ints[i].EnumName.size() < 40)
133       OS << std::string(40-Ints[i].EnumName.size(), ' ');
134     OS << " // " << Ints[i].Name << "\n";
135   }
136   OS << "#endif\n\n";
137 }
138
139 void IntrinsicEmitter::
140 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints,
141                      raw_ostream &OS) {
142   // Build a 'first character of function name' -> intrinsic # mapping.
143   std::map<char, std::vector<unsigned> > IntMapping;
144   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
145     IntMapping[Ints[i].Name[5]].push_back(i);
146
147   OS << "// Function name -> enum value recognizer code.\n";
148   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
149   OS << "  StringRef NameR(Name+6, Len-6);   // Skip over 'llvm.'\n";
150   OS << "  switch (Name[5]) {                  // Dispatch on first letter.\n";
151   OS << "  default: break;\n";
152   // Emit the intrinsic matching stuff by first letter.
153   for (std::map<char, std::vector<unsigned> >::iterator I = IntMapping.begin(),
154        E = IntMapping.end(); I != E; ++I) {
155     OS << "  case '" << I->first << "':\n";
156     std::vector<unsigned> &IntList = I->second;
157
158     // Sort in reverse order of intrinsic name so "abc.def" appears after
159     // "abd.def.ghi" in the overridden name matcher
160     std::sort(IntList.begin(), IntList.end(), [&](unsigned i, unsigned j) {
161       return Ints[i].Name > Ints[j].Name;
162     });
163
164     // Emit all the overloaded intrinsics first, build a table of the
165     // non-overloaded ones.
166     std::vector<StringMatcher::StringPair> MatchTable;
167
168     for (unsigned i = 0, e = IntList.size(); i != e; ++i) {
169       unsigned IntNo = IntList[i];
170       std::string Result = "return " + TargetPrefix + "Intrinsic::" +
171         Ints[IntNo].EnumName + ";";
172
173       if (!Ints[IntNo].isOverloaded) {
174         MatchTable.push_back(std::make_pair(Ints[IntNo].Name.substr(6),Result));
175         continue;
176       }
177
178       // For overloaded intrinsics, only the prefix needs to match
179       std::string TheStr = Ints[IntNo].Name.substr(6);
180       TheStr += '.';  // Require "bswap." instead of bswap.
181       OS << "    if (NameR.startswith(\"" << TheStr << "\")) "
182          << Result << '\n';
183     }
184
185     // Emit the matcher logic for the fixed length strings.
186     StringMatcher("NameR", MatchTable, OS).Emit(1);
187     OS << "    break;  // end of '" << I->first << "' case.\n";
188   }
189
190   OS << "  }\n";
191   OS << "#endif\n\n";
192 }
193
194 void IntrinsicEmitter::
195 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints,
196                          raw_ostream &OS) {
197   OS << "// Intrinsic ID to name table\n";
198   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
199   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
200   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
201     OS << "  \"" << Ints[i].Name << "\",\n";
202   OS << "#endif\n\n";
203 }
204
205 void IntrinsicEmitter::
206 EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints,
207                          raw_ostream &OS) {
208   OS << "// Intrinsic ID to overload bitset\n";
209   OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
210   OS << "static const uint8_t OTable[] = {\n";
211   OS << "  0";
212   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
213     // Add one to the index so we emit a null bit for the invalid #0 intrinsic.
214     if ((i+1)%8 == 0)
215       OS << ",\n  0";
216     if (Ints[i].isOverloaded)
217       OS << " | (1<<" << (i+1)%8 << ')';
218   }
219   OS << "\n};\n\n";
220   // OTable contains a true bit at the position if the intrinsic is overloaded.
221   OS << "return (OTable[id/8] & (1 << (id%8))) != 0;\n";
222   OS << "#endif\n\n";
223 }
224
225
226 // NOTE: This must be kept in synch with the copy in lib/VMCore/Function.cpp!
227 enum IIT_Info {
228   // Common values should be encoded with 0-15.
229   IIT_Done = 0,
230   IIT_I1   = 1,
231   IIT_I8   = 2,
232   IIT_I16  = 3,
233   IIT_I32  = 4,
234   IIT_I64  = 5,
235   IIT_F16  = 6,
236   IIT_F32  = 7,
237   IIT_F64  = 8,
238   IIT_V2   = 9,
239   IIT_V4   = 10,
240   IIT_V8   = 11,
241   IIT_V16  = 12,
242   IIT_V32  = 13,
243   IIT_PTR  = 14,
244   IIT_ARG  = 15,
245
246   // Values from 16+ are only encodable with the inefficient encoding.
247   IIT_V64  = 16,
248   IIT_MMX  = 17,
249   IIT_METADATA = 18,
250   IIT_EMPTYSTRUCT = 19,
251   IIT_STRUCT2 = 20,
252   IIT_STRUCT3 = 21,
253   IIT_STRUCT4 = 22,
254   IIT_STRUCT5 = 23,
255   IIT_EXTEND_ARG = 24,
256   IIT_TRUNC_ARG = 25,
257   IIT_ANYPTR = 26,
258   IIT_V1   = 27,
259   IIT_VARARG = 28,
260   IIT_HALF_VEC_ARG = 29,
261   IIT_SAME_VEC_WIDTH_ARG = 30,
262   IIT_PTR_TO_ARG = 31,
263   IIT_VEC_OF_PTRS_TO_ELT = 32,
264   IIT_I128 = 33
265 };
266
267
268 static void EncodeFixedValueType(MVT::SimpleValueType VT,
269                                  std::vector<unsigned char> &Sig) {
270   if (MVT(VT).isInteger()) {
271     unsigned BitWidth = MVT(VT).getSizeInBits();
272     switch (BitWidth) {
273     default: PrintFatalError("unhandled integer type width in intrinsic!");
274     case 1: return Sig.push_back(IIT_I1);
275     case 8: return Sig.push_back(IIT_I8);
276     case 16: return Sig.push_back(IIT_I16);
277     case 32: return Sig.push_back(IIT_I32);
278     case 64: return Sig.push_back(IIT_I64);
279     case 128: return Sig.push_back(IIT_I128);
280     }
281   }
282
283   switch (VT) {
284   default: PrintFatalError("unhandled MVT in intrinsic!");
285   case MVT::f16: return Sig.push_back(IIT_F16);
286   case MVT::f32: return Sig.push_back(IIT_F32);
287   case MVT::f64: return Sig.push_back(IIT_F64);
288   case MVT::Metadata: return Sig.push_back(IIT_METADATA);
289   case MVT::x86mmx: return Sig.push_back(IIT_MMX);
290   // MVT::OtherVT is used to mean the empty struct type here.
291   case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
292   // MVT::isVoid is used to represent varargs here.
293   case MVT::isVoid: return Sig.push_back(IIT_VARARG);
294   }
295 }
296
297 #if defined(_MSC_VER) && !defined(__clang__)
298 #pragma optimize("",off) // MSVC 2010 optimizer can't deal with this function.
299 #endif
300
301 static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes,
302                             std::vector<unsigned char> &Sig) {
303
304   if (R->isSubClassOf("LLVMMatchType")) {
305     unsigned Number = R->getValueAsInt("Number");
306     assert(Number < ArgCodes.size() && "Invalid matching number!");
307     if (R->isSubClassOf("LLVMExtendedType"))
308       Sig.push_back(IIT_EXTEND_ARG);
309     else if (R->isSubClassOf("LLVMTruncatedType"))
310       Sig.push_back(IIT_TRUNC_ARG);
311     else if (R->isSubClassOf("LLVMHalfElementsVectorType"))
312       Sig.push_back(IIT_HALF_VEC_ARG);
313     else if (R->isSubClassOf("LLVMVectorSameWidth")) {
314       Sig.push_back(IIT_SAME_VEC_WIDTH_ARG);
315       Sig.push_back((Number << 3) | ArgCodes[Number]);
316       MVT::SimpleValueType VT = getValueType(R->getValueAsDef("ElTy"));
317       EncodeFixedValueType(VT, Sig);
318       return;
319     }
320     else if (R->isSubClassOf("LLVMPointerTo"))
321       Sig.push_back(IIT_PTR_TO_ARG);
322     else if (R->isSubClassOf("LLVMVectorOfPointersToElt"))
323       Sig.push_back(IIT_VEC_OF_PTRS_TO_ELT);
324     else
325       Sig.push_back(IIT_ARG);
326     return Sig.push_back((Number << 3) | ArgCodes[Number]);
327   }
328
329   MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
330
331   unsigned Tmp = 0;
332   switch (VT) {
333   default: break;
334   case MVT::iPTRAny: ++Tmp; // FALL THROUGH.
335   case MVT::vAny: ++Tmp; // FALL THROUGH.
336   case MVT::fAny: ++Tmp; // FALL THROUGH.
337   case MVT::iAny: ++Tmp; // FALL THROUGH.
338   case MVT::Any: {
339     // If this is an "any" valuetype, then the type is the type of the next
340     // type in the list specified to getIntrinsic().
341     Sig.push_back(IIT_ARG);
342
343     // Figure out what arg # this is consuming, and remember what kind it was.
344     unsigned ArgNo = ArgCodes.size();
345     ArgCodes.push_back(Tmp);
346
347     // Encode what sort of argument it must be in the low 3 bits of the ArgNo.
348     return Sig.push_back((ArgNo << 3) | Tmp);
349   }
350
351   case MVT::iPTR: {
352     unsigned AddrSpace = 0;
353     if (R->isSubClassOf("LLVMQualPointerType")) {
354       AddrSpace = R->getValueAsInt("AddrSpace");
355       assert(AddrSpace < 256 && "Address space exceeds 255");
356     }
357     if (AddrSpace) {
358       Sig.push_back(IIT_ANYPTR);
359       Sig.push_back(AddrSpace);
360     } else {
361       Sig.push_back(IIT_PTR);
362     }
363     return EncodeFixedType(R->getValueAsDef("ElTy"), ArgCodes, Sig);
364   }
365   }
366
367   if (MVT(VT).isVector()) {
368     MVT VVT = VT;
369     switch (VVT.getVectorNumElements()) {
370     default: PrintFatalError("unhandled vector type width in intrinsic!");
371     case 1: Sig.push_back(IIT_V1); break;
372     case 2: Sig.push_back(IIT_V2); break;
373     case 4: Sig.push_back(IIT_V4); break;
374     case 8: Sig.push_back(IIT_V8); break;
375     case 16: Sig.push_back(IIT_V16); break;
376     case 32: Sig.push_back(IIT_V32); break;
377     case 64: Sig.push_back(IIT_V64); break;
378     }
379
380     return EncodeFixedValueType(VVT.getVectorElementType().SimpleTy, Sig);
381   }
382
383   EncodeFixedValueType(VT, Sig);
384 }
385
386 #if defined(_MSC_VER) && !defined(__clang__)
387 #pragma optimize("",on)
388 #endif
389
390 /// ComputeFixedEncoding - If we can encode the type signature for this
391 /// intrinsic into 32 bits, return it.  If not, return ~0U.
392 static void ComputeFixedEncoding(const CodeGenIntrinsic &Int,
393                                  std::vector<unsigned char> &TypeSig) {
394   std::vector<unsigned char> ArgCodes;
395
396   if (Int.IS.RetVTs.empty())
397     TypeSig.push_back(IIT_Done);
398   else if (Int.IS.RetVTs.size() == 1 &&
399            Int.IS.RetVTs[0] == MVT::isVoid)
400     TypeSig.push_back(IIT_Done);
401   else {
402     switch (Int.IS.RetVTs.size()) {
403       case 1: break;
404       case 2: TypeSig.push_back(IIT_STRUCT2); break;
405       case 3: TypeSig.push_back(IIT_STRUCT3); break;
406       case 4: TypeSig.push_back(IIT_STRUCT4); break;
407       case 5: TypeSig.push_back(IIT_STRUCT5); break;
408       default: llvm_unreachable("Unhandled case in struct");
409     }
410
411     for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
412       EncodeFixedType(Int.IS.RetTypeDefs[i], ArgCodes, TypeSig);
413   }
414
415   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
416     EncodeFixedType(Int.IS.ParamTypeDefs[i], ArgCodes, TypeSig);
417 }
418
419 static void printIITEntry(raw_ostream &OS, unsigned char X) {
420   OS << (unsigned)X;
421 }
422
423 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints,
424                                      raw_ostream &OS) {
425   // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
426   // capture it in this vector, otherwise store a ~0U.
427   std::vector<unsigned> FixedEncodings;
428
429   SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable;
430
431   std::vector<unsigned char> TypeSig;
432
433   // Compute the unique argument type info.
434   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
435     // Get the signature for the intrinsic.
436     TypeSig.clear();
437     ComputeFixedEncoding(Ints[i], TypeSig);
438
439     // Check to see if we can encode it into a 32-bit word.  We can only encode
440     // 8 nibbles into a 32-bit word.
441     if (TypeSig.size() <= 8) {
442       bool Failed = false;
443       unsigned Result = 0;
444       for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
445         // If we had an unencodable argument, bail out.
446         if (TypeSig[i] > 15) {
447           Failed = true;
448           break;
449         }
450         Result = (Result << 4) | TypeSig[e-i-1];
451       }
452
453       // If this could be encoded into a 31-bit word, return it.
454       if (!Failed && (Result >> 31) == 0) {
455         FixedEncodings.push_back(Result);
456         continue;
457       }
458     }
459
460     // Otherwise, we're going to unique the sequence into the
461     // LongEncodingTable, and use its offset in the 32-bit table instead.
462     LongEncodingTable.add(TypeSig);
463
464     // This is a placehold that we'll replace after the table is laid out.
465     FixedEncodings.push_back(~0U);
466   }
467
468   LongEncodingTable.layout();
469
470   OS << "// Global intrinsic function declaration type table.\n";
471   OS << "#ifdef GET_INTRINSIC_GENERATOR_GLOBAL\n";
472
473   OS << "static const unsigned IIT_Table[] = {\n  ";
474
475   for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
476     if ((i & 7) == 7)
477       OS << "\n  ";
478
479     // If the entry fit in the table, just emit it.
480     if (FixedEncodings[i] != ~0U) {
481       OS << "0x" << utohexstr(FixedEncodings[i]) << ", ";
482       continue;
483     }
484
485     TypeSig.clear();
486     ComputeFixedEncoding(Ints[i], TypeSig);
487
488
489     // Otherwise, emit the offset into the long encoding table.  We emit it this
490     // way so that it is easier to read the offset in the .def file.
491     OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", ";
492   }
493
494   OS << "0\n};\n\n";
495
496   // Emit the shared table of register lists.
497   OS << "static const unsigned char IIT_LongEncodingTable[] = {\n";
498   if (!LongEncodingTable.empty())
499     LongEncodingTable.emit(OS, printIITEntry);
500   OS << "  255\n};\n\n";
501
502   OS << "#endif\n\n";  // End of GET_INTRINSIC_GENERATOR_GLOBAL
503 }
504
505 namespace {
506 enum ModRefKind {
507   MRK_none,
508   MRK_readonly,
509   MRK_readnone
510 };
511 }
512
513 static ModRefKind getModRefKind(const CodeGenIntrinsic &intrinsic) {
514   switch (intrinsic.ModRef) {
515   case CodeGenIntrinsic::NoMem:
516     return MRK_readnone;
517   case CodeGenIntrinsic::ReadArgMem:
518   case CodeGenIntrinsic::ReadMem:
519     return MRK_readonly;
520   case CodeGenIntrinsic::ReadWriteArgMem:
521   case CodeGenIntrinsic::ReadWriteMem:
522     return MRK_none;
523   }
524   llvm_unreachable("bad mod-ref kind");
525 }
526
527 namespace {
528 struct AttributeComparator {
529   bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
530     // Sort throwing intrinsics after non-throwing intrinsics.
531     if (L->canThrow != R->canThrow)
532       return R->canThrow;
533
534     if (L->isNoDuplicate != R->isNoDuplicate)
535       return R->isNoDuplicate;
536
537     if (L->isNoReturn != R->isNoReturn)
538       return R->isNoReturn;
539
540     // Try to order by readonly/readnone attribute.
541     ModRefKind LK = getModRefKind(*L);
542     ModRefKind RK = getModRefKind(*R);
543     if (LK != RK) return (LK > RK);
544
545     // Order by argument attributes.
546     // This is reliable because each side is already sorted internally.
547     return (L->ArgumentAttributes < R->ArgumentAttributes);
548   }
549 };
550 } // End anonymous namespace
551
552 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
553 void IntrinsicEmitter::
554 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) {
555   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
556   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
557   if (TargetOnly)
558     OS << "static AttributeSet getAttributes(LLVMContext &C, " << TargetPrefix
559        << "Intrinsic::ID id) {\n";
560   else
561     OS << "AttributeSet Intrinsic::getAttributes(LLVMContext &C, ID id) {\n";
562
563   // Compute the maximum number of attribute arguments and the map
564   typedef std::map<const CodeGenIntrinsic*, unsigned,
565                    AttributeComparator> UniqAttrMapTy;
566   UniqAttrMapTy UniqAttributes;
567   unsigned maxArgAttrs = 0;
568   unsigned AttrNum = 0;
569   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
570     const CodeGenIntrinsic &intrinsic = Ints[i];
571     maxArgAttrs =
572       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
573     unsigned &N = UniqAttributes[&intrinsic];
574     if (N) continue;
575     assert(AttrNum < 256 && "Too many unique attributes for table!");
576     N = ++AttrNum;
577   }
578
579   // Emit an array of AttributeSet.  Most intrinsics will have at least one
580   // entry, for the function itself (index ~1), which is usually nounwind.
581   OS << "  static const uint8_t IntrinsicsToAttributesMap[] = {\n";
582
583   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
584     const CodeGenIntrinsic &intrinsic = Ints[i];
585
586     OS << "    " << UniqAttributes[&intrinsic] << ", // "
587        << intrinsic.Name << "\n";
588   }
589   OS << "  };\n\n";
590
591   OS << "  AttributeSet AS[" << maxArgAttrs+1 << "];\n";
592   OS << "  unsigned NumAttrs = 0;\n";
593   OS << "  if (id != 0) {\n";
594   OS << "    switch(IntrinsicsToAttributesMap[id - ";
595   if (TargetOnly)
596     OS << "Intrinsic::num_intrinsics";
597   else
598     OS << "1";
599   OS << "]) {\n";
600   OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
601   for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(),
602        E = UniqAttributes.end(); I != E; ++I) {
603     OS << "    case " << I->second << ": {\n";
604
605     const CodeGenIntrinsic &intrinsic = *(I->first);
606
607     // Keep track of the number of attributes we're writing out.
608     unsigned numAttrs = 0;
609
610     // The argument attributes are alreadys sorted by argument index.
611     unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size();
612     if (ae) {
613       while (ai != ae) {
614         unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
615
616         OS <<  "      const Attribute::AttrKind AttrParam" << argNo + 1 <<"[]= {";
617         bool addComma = false;
618
619         do {
620           switch (intrinsic.ArgumentAttributes[ai].second) {
621           case CodeGenIntrinsic::NoCapture:
622             if (addComma)
623               OS << ",";
624             OS << "Attribute::NoCapture";
625             addComma = true;
626             break;
627           case CodeGenIntrinsic::ReadOnly:
628             if (addComma)
629               OS << ",";
630             OS << "Attribute::ReadOnly";
631             addComma = true;
632             break;
633           case CodeGenIntrinsic::ReadNone:
634             if (addComma)
635               OS << ",";
636             OS << "Attributes::ReadNone";
637             addComma = true;
638             break;
639           }
640
641           ++ai;
642         } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
643         OS << "};\n";
644         OS << "      AS[" << numAttrs++ << "] = AttributeSet::get(C, "
645            << argNo+1 << ", AttrParam" << argNo +1 << ");\n";
646       }
647     }
648
649     ModRefKind modRef = getModRefKind(intrinsic);
650
651     if (!intrinsic.canThrow || modRef || intrinsic.isNoReturn ||
652         intrinsic.isNoDuplicate) {
653       OS << "      const Attribute::AttrKind Atts[] = {";
654       bool addComma = false;
655       if (!intrinsic.canThrow) {
656         OS << "Attribute::NoUnwind";
657         addComma = true;
658       }
659       if (intrinsic.isNoReturn) {
660         if (addComma)
661           OS << ",";
662         OS << "Attribute::NoReturn";
663         addComma = true;
664       }
665       if (intrinsic.isNoDuplicate) {
666         if (addComma)
667           OS << ",";
668         OS << "Attribute::NoDuplicate";
669         addComma = true;
670       }
671
672       switch (modRef) {
673       case MRK_none: break;
674       case MRK_readonly:
675         if (addComma)
676           OS << ",";
677         OS << "Attribute::ReadOnly";
678         break;
679       case MRK_readnone:
680         if (addComma)
681           OS << ",";
682         OS << "Attribute::ReadNone";
683         break;
684       }
685       OS << "};\n";
686       OS << "      AS[" << numAttrs++ << "] = AttributeSet::get(C, "
687          << "AttributeSet::FunctionIndex, Atts);\n";
688     }
689
690     if (numAttrs) {
691       OS << "      NumAttrs = " << numAttrs << ";\n";
692       OS << "      break;\n";
693       OS << "      }\n";
694     } else {
695       OS << "      return AttributeSet();\n";
696       OS << "      }\n";
697     }
698   }
699
700   OS << "    }\n";
701   OS << "  }\n";
702   OS << "  return AttributeSet::get(C, makeArrayRef(AS, NumAttrs));\n";
703   OS << "}\n";
704   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
705 }
706
707 /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavior.
708 void IntrinsicEmitter::
709 EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
710   OS << "// Determine intrinsic alias analysis mod/ref behavior.\n"
711      << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n"
712      << "assert(iid <= Intrinsic::" << Ints.back().EnumName << " && "
713      << "\"Unknown intrinsic.\");\n\n";
714
715   OS << "static const uint8_t IntrinsicModRefBehavior[] = {\n"
716      << "  /* invalid */ UnknownModRefBehavior,\n";
717   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
718     OS << "  /* " << TargetPrefix << Ints[i].EnumName << " */ ";
719     switch (Ints[i].ModRef) {
720     case CodeGenIntrinsic::NoMem:
721       OS << "DoesNotAccessMemory,\n";
722       break;
723     case CodeGenIntrinsic::ReadArgMem:
724       OS << "OnlyReadsArgumentPointees,\n";
725       break;
726     case CodeGenIntrinsic::ReadMem:
727       OS << "OnlyReadsMemory,\n";
728       break;
729     case CodeGenIntrinsic::ReadWriteArgMem:
730       OS << "OnlyAccessesArgumentPointees,\n";
731       break;
732     case CodeGenIntrinsic::ReadWriteMem:
733       OS << "UnknownModRefBehavior,\n";
734       break;
735     }
736   }
737   OS << "};\n\n"
738      << "return static_cast<ModRefBehavior>(IntrinsicModRefBehavior[iid]);\n"
739      << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
740 }
741
742 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
743 /// same target, and we already checked it.
744 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
745                                const std::string &TargetPrefix,
746                                raw_ostream &OS) {
747
748   std::vector<StringMatcher::StringPair> Results;
749
750   for (std::map<std::string, std::string>::const_iterator I = BIM.begin(),
751        E = BIM.end(); I != E; ++I) {
752     std::string ResultCode =
753     "return " + TargetPrefix + "Intrinsic::" + I->second + ";";
754     Results.push_back(StringMatcher::StringPair(I->first, ResultCode));
755   }
756
757   StringMatcher("BuiltinName", Results, OS).Emit();
758 }
759
760
761 void IntrinsicEmitter::
762 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
763                              raw_ostream &OS) {
764   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
765   BIMTy BuiltinMap;
766   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
767     if (!Ints[i].GCCBuiltinName.empty()) {
768       // Get the map for this target prefix.
769       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
770
771       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
772                                      Ints[i].EnumName)).second)
773         PrintFatalError("Intrinsic '" + Ints[i].TheDef->getName() +
774               "': duplicate GCC builtin name!");
775     }
776   }
777
778   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
779   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
780   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
781   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
782   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
783
784   if (TargetOnly) {
785     OS << "static " << TargetPrefix << "Intrinsic::ID "
786        << "getIntrinsicForGCCBuiltin(const char "
787        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
788   } else {
789     OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char "
790        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
791   }
792
793   OS << "  StringRef BuiltinName(BuiltinNameStr);\n";
794   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
795
796   // Note: this could emit significantly better code if we cared.
797   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
798     OS << "  ";
799     if (!I->first.empty())
800       OS << "if (TargetPrefix == \"" << I->first << "\") ";
801     else
802       OS << "/* Target Independent Builtins */ ";
803     OS << "{\n";
804
805     // Emit the comparisons for this target prefix.
806     EmitTargetBuiltins(I->second, TargetPrefix, OS);
807     OS << "  }\n";
808   }
809   OS << "  return ";
810   if (!TargetPrefix.empty())
811     OS << "(" << TargetPrefix << "Intrinsic::ID)";
812   OS << "Intrinsic::not_intrinsic;\n";
813   OS << "}\n";
814   OS << "#endif\n\n";
815 }
816
817 void IntrinsicEmitter::
818 EmitIntrinsicToMSBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
819                             raw_ostream &OS) {
820   std::map<std::string, std::map<std::string, std::string>> TargetBuiltins;
821
822   for (const auto &Intrinsic : Ints) {
823     if (Intrinsic.MSBuiltinName.empty())
824       continue;
825
826     auto &Builtins = TargetBuiltins[Intrinsic.TargetPrefix];
827     if (!Builtins.insert(std::make_pair(Intrinsic.MSBuiltinName,
828                                         Intrinsic.EnumName)).second)
829       PrintFatalError("Intrinsic '" + Intrinsic.TheDef->getName() + "': "
830                       "duplicate MS builtin name!");
831   }
832
833   OS << "// Get the LLVM intrinsic that corresponds to a MS builtin.\n"
834         "// This is used by the C front-end.  The MS builtin name is passed\n"
835         "// in as a BuiltinName, and a target prefix (e.g. 'arm') is passed\n"
836         "// in as a TargetPrefix.  The result is assigned to 'IntrinsicID'.\n"
837         "#ifdef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN\n";
838
839   OS << (TargetOnly ? "static " + TargetPrefix : "") << "Intrinsic::ID "
840      << (TargetOnly ? "" : "Intrinsic::")
841      << "getIntrinsicForMSBuiltin(const char *TP, const char *BN) {\n";
842   OS << "  StringRef BuiltinName(BN);\n"
843         "  StringRef TargetPrefix(TP);\n"
844         "\n";
845
846   for (const auto &Builtins : TargetBuiltins) {
847     OS << "  ";
848     if (Builtins.first.empty())
849       OS << "/* Target Independent Builtins */ ";
850     else
851       OS << "if (TargetPrefix == \"" << Builtins.first << "\") ";
852     OS << "{\n";
853     EmitTargetBuiltins(Builtins.second, TargetPrefix, OS);
854     OS << "}";
855   }
856
857   OS << "  return ";
858   if (!TargetPrefix.empty())
859     OS << "(" << TargetPrefix << "Intrinsic::ID)";
860   OS << "Intrinsic::not_intrinsic;\n";
861   OS << "}\n";
862
863   OS << "#endif\n\n";
864 }
865
866 void llvm::EmitIntrinsics(RecordKeeper &RK, raw_ostream &OS, bool TargetOnly) {
867   IntrinsicEmitter(RK, TargetOnly).run(OS);
868 }