Fixes a bug in vector load legalization that confused bits and bytes.
[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 };
264
265
266 static void EncodeFixedValueType(MVT::SimpleValueType VT,
267                                  std::vector<unsigned char> &Sig) {
268   if (MVT(VT).isInteger()) {
269     unsigned BitWidth = MVT(VT).getSizeInBits();
270     switch (BitWidth) {
271     default: PrintFatalError("unhandled integer type width in intrinsic!");
272     case 1: return Sig.push_back(IIT_I1);
273     case 8: return Sig.push_back(IIT_I8);
274     case 16: return Sig.push_back(IIT_I16);
275     case 32: return Sig.push_back(IIT_I32);
276     case 64: return Sig.push_back(IIT_I64);
277     }
278   }
279
280   switch (VT) {
281   default: PrintFatalError("unhandled MVT in intrinsic!");
282   case MVT::f16: return Sig.push_back(IIT_F16);
283   case MVT::f32: return Sig.push_back(IIT_F32);
284   case MVT::f64: return Sig.push_back(IIT_F64);
285   case MVT::Metadata: return Sig.push_back(IIT_METADATA);
286   case MVT::x86mmx: return Sig.push_back(IIT_MMX);
287   // MVT::OtherVT is used to mean the empty struct type here.
288   case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
289   // MVT::isVoid is used to represent varargs here.
290   case MVT::isVoid: return Sig.push_back(IIT_VARARG);
291   }
292 }
293
294 #ifdef _MSC_VER
295 #pragma optimize("",off) // MSVC 2010 optimizer can't deal with this function.
296 #endif
297
298 static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes,
299                             std::vector<unsigned char> &Sig) {
300
301   if (R->isSubClassOf("LLVMMatchType")) {
302     unsigned Number = R->getValueAsInt("Number");
303     assert(Number < ArgCodes.size() && "Invalid matching number!");
304     if (R->isSubClassOf("LLVMExtendedType"))
305       Sig.push_back(IIT_EXTEND_ARG);
306     else if (R->isSubClassOf("LLVMTruncatedType"))
307       Sig.push_back(IIT_TRUNC_ARG);
308     else if (R->isSubClassOf("LLVMHalfElementsVectorType"))
309       Sig.push_back(IIT_HALF_VEC_ARG);
310     else if (R->isSubClassOf("LLVMVectorSameWidth")) {
311       Sig.push_back(IIT_SAME_VEC_WIDTH_ARG);
312       Sig.push_back((Number << 3) | ArgCodes[Number]);
313       MVT::SimpleValueType VT = getValueType(R->getValueAsDef("ElTy"));
314       EncodeFixedValueType(VT, Sig);
315       return;
316     }
317     else if (R->isSubClassOf("LLVMPointerTo")) {
318       Sig.push_back(IIT_PTR_TO_ARG);
319     }
320     else
321       Sig.push_back(IIT_ARG);
322     return Sig.push_back((Number << 3) | ArgCodes[Number]);
323   }
324
325   MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
326
327   unsigned Tmp = 0;
328   switch (VT) {
329   default: break;
330   case MVT::iPTRAny: ++Tmp; // FALL THROUGH.
331   case MVT::vAny: ++Tmp; // FALL THROUGH.
332   case MVT::fAny: ++Tmp; // FALL THROUGH.
333   case MVT::iAny: ++Tmp; // FALL THROUGH.
334   case MVT::Any: {
335     // If this is an "any" valuetype, then the type is the type of the next
336     // type in the list specified to getIntrinsic().
337     Sig.push_back(IIT_ARG);
338
339     // Figure out what arg # this is consuming, and remember what kind it was.
340     unsigned ArgNo = ArgCodes.size();
341     ArgCodes.push_back(Tmp);
342
343     // Encode what sort of argument it must be in the low 3 bits of the ArgNo.
344     return Sig.push_back((ArgNo << 3) | Tmp);
345   }
346
347   case MVT::iPTR: {
348     unsigned AddrSpace = 0;
349     if (R->isSubClassOf("LLVMQualPointerType")) {
350       AddrSpace = R->getValueAsInt("AddrSpace");
351       assert(AddrSpace < 256 && "Address space exceeds 255");
352     }
353     if (AddrSpace) {
354       Sig.push_back(IIT_ANYPTR);
355       Sig.push_back(AddrSpace);
356     } else {
357       Sig.push_back(IIT_PTR);
358     }
359     return EncodeFixedType(R->getValueAsDef("ElTy"), ArgCodes, Sig);
360   }
361   }
362
363   if (MVT(VT).isVector()) {
364     MVT VVT = VT;
365     switch (VVT.getVectorNumElements()) {
366     default: PrintFatalError("unhandled vector type width in intrinsic!");
367     case 1: Sig.push_back(IIT_V1); break;
368     case 2: Sig.push_back(IIT_V2); break;
369     case 4: Sig.push_back(IIT_V4); break;
370     case 8: Sig.push_back(IIT_V8); break;
371     case 16: Sig.push_back(IIT_V16); break;
372     case 32: Sig.push_back(IIT_V32); break;
373     case 64: Sig.push_back(IIT_V64); break;
374     }
375
376     return EncodeFixedValueType(VVT.getVectorElementType().SimpleTy, Sig);
377   }
378
379   EncodeFixedValueType(VT, Sig);
380 }
381
382 #ifdef _MSC_VER
383 #pragma optimize("",on)
384 #endif
385
386 /// ComputeFixedEncoding - If we can encode the type signature for this
387 /// intrinsic into 32 bits, return it.  If not, return ~0U.
388 static void ComputeFixedEncoding(const CodeGenIntrinsic &Int,
389                                  std::vector<unsigned char> &TypeSig) {
390   std::vector<unsigned char> ArgCodes;
391
392   if (Int.IS.RetVTs.empty())
393     TypeSig.push_back(IIT_Done);
394   else if (Int.IS.RetVTs.size() == 1 &&
395            Int.IS.RetVTs[0] == MVT::isVoid)
396     TypeSig.push_back(IIT_Done);
397   else {
398     switch (Int.IS.RetVTs.size()) {
399       case 1: break;
400       case 2: TypeSig.push_back(IIT_STRUCT2); break;
401       case 3: TypeSig.push_back(IIT_STRUCT3); break;
402       case 4: TypeSig.push_back(IIT_STRUCT4); break;
403       case 5: TypeSig.push_back(IIT_STRUCT5); break;
404       default: llvm_unreachable("Unhandled case in struct");
405     }
406
407     for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
408       EncodeFixedType(Int.IS.RetTypeDefs[i], ArgCodes, TypeSig);
409   }
410
411   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
412     EncodeFixedType(Int.IS.ParamTypeDefs[i], ArgCodes, TypeSig);
413 }
414
415 static void printIITEntry(raw_ostream &OS, unsigned char X) {
416   OS << (unsigned)X;
417 }
418
419 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints,
420                                      raw_ostream &OS) {
421   // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
422   // capture it in this vector, otherwise store a ~0U.
423   std::vector<unsigned> FixedEncodings;
424
425   SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable;
426
427   std::vector<unsigned char> TypeSig;
428
429   // Compute the unique argument type info.
430   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
431     // Get the signature for the intrinsic.
432     TypeSig.clear();
433     ComputeFixedEncoding(Ints[i], TypeSig);
434
435     // Check to see if we can encode it into a 32-bit word.  We can only encode
436     // 8 nibbles into a 32-bit word.
437     if (TypeSig.size() <= 8) {
438       bool Failed = false;
439       unsigned Result = 0;
440       for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
441         // If we had an unencodable argument, bail out.
442         if (TypeSig[i] > 15) {
443           Failed = true;
444           break;
445         }
446         Result = (Result << 4) | TypeSig[e-i-1];
447       }
448
449       // If this could be encoded into a 31-bit word, return it.
450       if (!Failed && (Result >> 31) == 0) {
451         FixedEncodings.push_back(Result);
452         continue;
453       }
454     }
455
456     // Otherwise, we're going to unique the sequence into the
457     // LongEncodingTable, and use its offset in the 32-bit table instead.
458     LongEncodingTable.add(TypeSig);
459
460     // This is a placehold that we'll replace after the table is laid out.
461     FixedEncodings.push_back(~0U);
462   }
463
464   LongEncodingTable.layout();
465
466   OS << "// Global intrinsic function declaration type table.\n";
467   OS << "#ifdef GET_INTRINSIC_GENERATOR_GLOBAL\n";
468
469   OS << "static const unsigned IIT_Table[] = {\n  ";
470
471   for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
472     if ((i & 7) == 7)
473       OS << "\n  ";
474
475     // If the entry fit in the table, just emit it.
476     if (FixedEncodings[i] != ~0U) {
477       OS << "0x" << utohexstr(FixedEncodings[i]) << ", ";
478       continue;
479     }
480
481     TypeSig.clear();
482     ComputeFixedEncoding(Ints[i], TypeSig);
483
484
485     // Otherwise, emit the offset into the long encoding table.  We emit it this
486     // way so that it is easier to read the offset in the .def file.
487     OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", ";
488   }
489
490   OS << "0\n};\n\n";
491
492   // Emit the shared table of register lists.
493   OS << "static const unsigned char IIT_LongEncodingTable[] = {\n";
494   if (!LongEncodingTable.empty())
495     LongEncodingTable.emit(OS, printIITEntry);
496   OS << "  255\n};\n\n";
497
498   OS << "#endif\n\n";  // End of GET_INTRINSIC_GENERATOR_GLOBAL
499 }
500
501 namespace {
502 enum ModRefKind {
503   MRK_none,
504   MRK_readonly,
505   MRK_readnone
506 };
507 }
508
509 static ModRefKind getModRefKind(const CodeGenIntrinsic &intrinsic) {
510   switch (intrinsic.ModRef) {
511   case CodeGenIntrinsic::NoMem:
512     return MRK_readnone;
513   case CodeGenIntrinsic::ReadArgMem:
514   case CodeGenIntrinsic::ReadMem:
515     return MRK_readonly;
516   case CodeGenIntrinsic::ReadWriteArgMem:
517   case CodeGenIntrinsic::ReadWriteMem:
518     return MRK_none;
519   }
520   llvm_unreachable("bad mod-ref kind");
521 }
522
523 namespace {
524 struct AttributeComparator {
525   bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
526     // Sort throwing intrinsics after non-throwing intrinsics.
527     if (L->canThrow != R->canThrow)
528       return R->canThrow;
529
530     if (L->isNoDuplicate != R->isNoDuplicate)
531       return R->isNoDuplicate;
532
533     if (L->isNoReturn != R->isNoReturn)
534       return R->isNoReturn;
535
536     // Try to order by readonly/readnone attribute.
537     ModRefKind LK = getModRefKind(*L);
538     ModRefKind RK = getModRefKind(*R);
539     if (LK != RK) return (LK > RK);
540
541     // Order by argument attributes.
542     // This is reliable because each side is already sorted internally.
543     return (L->ArgumentAttributes < R->ArgumentAttributes);
544   }
545 };
546 } // End anonymous namespace
547
548 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
549 void IntrinsicEmitter::
550 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) {
551   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
552   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
553   if (TargetOnly)
554     OS << "static AttributeSet getAttributes(LLVMContext &C, " << TargetPrefix
555        << "Intrinsic::ID id) {\n";
556   else
557     OS << "AttributeSet Intrinsic::getAttributes(LLVMContext &C, ID id) {\n";
558
559   // Compute the maximum number of attribute arguments and the map
560   typedef std::map<const CodeGenIntrinsic*, unsigned,
561                    AttributeComparator> UniqAttrMapTy;
562   UniqAttrMapTy UniqAttributes;
563   unsigned maxArgAttrs = 0;
564   unsigned AttrNum = 0;
565   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
566     const CodeGenIntrinsic &intrinsic = Ints[i];
567     maxArgAttrs =
568       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
569     unsigned &N = UniqAttributes[&intrinsic];
570     if (N) continue;
571     assert(AttrNum < 256 && "Too many unique attributes for table!");
572     N = ++AttrNum;
573   }
574
575   // Emit an array of AttributeSet.  Most intrinsics will have at least one
576   // entry, for the function itself (index ~1), which is usually nounwind.
577   OS << "  static const uint8_t IntrinsicsToAttributesMap[] = {\n";
578
579   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
580     const CodeGenIntrinsic &intrinsic = Ints[i];
581
582     OS << "    " << UniqAttributes[&intrinsic] << ", // "
583        << intrinsic.Name << "\n";
584   }
585   OS << "  };\n\n";
586
587   OS << "  AttributeSet AS[" << maxArgAttrs+1 << "];\n";
588   OS << "  unsigned NumAttrs = 0;\n";
589   OS << "  if (id != 0) {\n";
590   OS << "    switch(IntrinsicsToAttributesMap[id - ";
591   if (TargetOnly)
592     OS << "Intrinsic::num_intrinsics";
593   else
594     OS << "1";
595   OS << "]) {\n";
596   OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
597   for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(),
598        E = UniqAttributes.end(); I != E; ++I) {
599     OS << "    case " << I->second << ": {\n";
600
601     const CodeGenIntrinsic &intrinsic = *(I->first);
602
603     // Keep track of the number of attributes we're writing out.
604     unsigned numAttrs = 0;
605
606     // The argument attributes are alreadys sorted by argument index.
607     unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size();
608     if (ae) {
609       while (ai != ae) {
610         unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
611
612         OS <<  "      const Attribute::AttrKind AttrParam" << argNo + 1 <<"[]= {";
613         bool addComma = false;
614
615         do {
616           switch (intrinsic.ArgumentAttributes[ai].second) {
617           case CodeGenIntrinsic::NoCapture:
618             if (addComma)
619               OS << ",";
620             OS << "Attribute::NoCapture";
621             addComma = true;
622             break;
623           case CodeGenIntrinsic::ReadOnly:
624             if (addComma)
625               OS << ",";
626             OS << "Attribute::ReadOnly";
627             addComma = true;
628             break;
629           case CodeGenIntrinsic::ReadNone:
630             if (addComma)
631               OS << ",";
632             OS << "Attributes::ReadNone";
633             addComma = true;
634             break;
635           }
636
637           ++ai;
638         } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
639         OS << "};\n";
640         OS << "      AS[" << numAttrs++ << "] = AttributeSet::get(C, "
641            << argNo+1 << ", AttrParam" << argNo +1 << ");\n";
642       }
643     }
644
645     ModRefKind modRef = getModRefKind(intrinsic);
646
647     if (!intrinsic.canThrow || modRef || intrinsic.isNoReturn ||
648         intrinsic.isNoDuplicate) {
649       OS << "      const Attribute::AttrKind Atts[] = {";
650       bool addComma = false;
651       if (!intrinsic.canThrow) {
652         OS << "Attribute::NoUnwind";
653         addComma = true;
654       }
655       if (intrinsic.isNoReturn) {
656         if (addComma)
657           OS << ",";
658         OS << "Attribute::NoReturn";
659         addComma = true;
660       }
661       if (intrinsic.isNoDuplicate) {
662         if (addComma)
663           OS << ",";
664         OS << "Attribute::NoDuplicate";
665         addComma = true;
666       }
667
668       switch (modRef) {
669       case MRK_none: break;
670       case MRK_readonly:
671         if (addComma)
672           OS << ",";
673         OS << "Attribute::ReadOnly";
674         break;
675       case MRK_readnone:
676         if (addComma)
677           OS << ",";
678         OS << "Attribute::ReadNone";
679         break;
680       }
681       OS << "};\n";
682       OS << "      AS[" << numAttrs++ << "] = AttributeSet::get(C, "
683          << "AttributeSet::FunctionIndex, Atts);\n";
684     }
685
686     if (numAttrs) {
687       OS << "      NumAttrs = " << numAttrs << ";\n";
688       OS << "      break;\n";
689       OS << "      }\n";
690     } else {
691       OS << "      return AttributeSet();\n";
692       OS << "      }\n";
693     }
694   }
695
696   OS << "    }\n";
697   OS << "  }\n";
698   OS << "  return AttributeSet::get(C, makeArrayRef(AS, NumAttrs));\n";
699   OS << "}\n";
700   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
701 }
702
703 /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavior.
704 void IntrinsicEmitter::
705 EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
706   OS << "// Determine intrinsic alias analysis mod/ref behavior.\n"
707      << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n"
708      << "assert(iid <= Intrinsic::" << Ints.back().EnumName << " && "
709      << "\"Unknown intrinsic.\");\n\n";
710
711   OS << "static const uint8_t IntrinsicModRefBehavior[] = {\n"
712      << "  /* invalid */ UnknownModRefBehavior,\n";
713   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
714     OS << "  /* " << TargetPrefix << Ints[i].EnumName << " */ ";
715     switch (Ints[i].ModRef) {
716     case CodeGenIntrinsic::NoMem:
717       OS << "DoesNotAccessMemory,\n";
718       break;
719     case CodeGenIntrinsic::ReadArgMem:
720       OS << "OnlyReadsArgumentPointees,\n";
721       break;
722     case CodeGenIntrinsic::ReadMem:
723       OS << "OnlyReadsMemory,\n";
724       break;
725     case CodeGenIntrinsic::ReadWriteArgMem:
726       OS << "OnlyAccessesArgumentPointees,\n";
727       break;
728     case CodeGenIntrinsic::ReadWriteMem:
729       OS << "UnknownModRefBehavior,\n";
730       break;
731     }
732   }
733   OS << "};\n\n"
734      << "return static_cast<ModRefBehavior>(IntrinsicModRefBehavior[iid]);\n"
735      << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
736 }
737
738 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
739 /// same target, and we already checked it.
740 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
741                                const std::string &TargetPrefix,
742                                raw_ostream &OS) {
743
744   std::vector<StringMatcher::StringPair> Results;
745
746   for (std::map<std::string, std::string>::const_iterator I = BIM.begin(),
747        E = BIM.end(); I != E; ++I) {
748     std::string ResultCode =
749     "return " + TargetPrefix + "Intrinsic::" + I->second + ";";
750     Results.push_back(StringMatcher::StringPair(I->first, ResultCode));
751   }
752
753   StringMatcher("BuiltinName", Results, OS).Emit();
754 }
755
756
757 void IntrinsicEmitter::
758 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
759                              raw_ostream &OS) {
760   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
761   BIMTy BuiltinMap;
762   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
763     if (!Ints[i].GCCBuiltinName.empty()) {
764       // Get the map for this target prefix.
765       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
766
767       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
768                                      Ints[i].EnumName)).second)
769         PrintFatalError("Intrinsic '" + Ints[i].TheDef->getName() +
770               "': duplicate GCC builtin name!");
771     }
772   }
773
774   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
775   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
776   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
777   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
778   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
779
780   if (TargetOnly) {
781     OS << "static " << TargetPrefix << "Intrinsic::ID "
782        << "getIntrinsicForGCCBuiltin(const char "
783        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
784   } else {
785     OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char "
786        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
787   }
788
789   OS << "  StringRef BuiltinName(BuiltinNameStr);\n";
790   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
791
792   // Note: this could emit significantly better code if we cared.
793   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
794     OS << "  ";
795     if (!I->first.empty())
796       OS << "if (TargetPrefix == \"" << I->first << "\") ";
797     else
798       OS << "/* Target Independent Builtins */ ";
799     OS << "{\n";
800
801     // Emit the comparisons for this target prefix.
802     EmitTargetBuiltins(I->second, TargetPrefix, OS);
803     OS << "  }\n";
804   }
805   OS << "  return ";
806   if (!TargetPrefix.empty())
807     OS << "(" << TargetPrefix << "Intrinsic::ID)";
808   OS << "Intrinsic::not_intrinsic;\n";
809   OS << "}\n";
810   OS << "#endif\n\n";
811 }
812
813 void IntrinsicEmitter::
814 EmitIntrinsicToMSBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
815                             raw_ostream &OS) {
816   std::map<std::string, std::map<std::string, std::string>> TargetBuiltins;
817
818   for (const auto &Intrinsic : Ints) {
819     if (Intrinsic.MSBuiltinName.empty())
820       continue;
821
822     auto &Builtins = TargetBuiltins[Intrinsic.TargetPrefix];
823     if (!Builtins.insert(std::make_pair(Intrinsic.MSBuiltinName,
824                                         Intrinsic.EnumName)).second)
825       PrintFatalError("Intrinsic '" + Intrinsic.TheDef->getName() + "': "
826                       "duplicate MS builtin name!");
827   }
828
829   OS << "// Get the LLVM intrinsic that corresponds to a MS builtin.\n"
830         "// This is used by the C front-end.  The MS builtin name is passed\n"
831         "// in as a BuiltinName, and a target prefix (e.g. 'arm') is passed\n"
832         "// in as a TargetPrefix.  The result is assigned to 'IntrinsicID'.\n"
833         "#ifdef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN\n";
834
835   OS << (TargetOnly ? "static " + TargetPrefix : "") << "Intrinsic::ID "
836      << (TargetOnly ? "" : "Intrinsic::")
837      << "getIntrinsicForMSBuiltin(const char *TP, const char *BN) {\n";
838   OS << "  StringRef BuiltinName(BN);\n"
839         "  StringRef TargetPrefix(TP);\n"
840         "\n";
841
842   for (const auto &Builtins : TargetBuiltins) {
843     OS << "  ";
844     if (Builtins.first.empty())
845       OS << "/* Target Independent Builtins */ ";
846     else
847       OS << "if (TargetPrefix == \"" << Builtins.first << "\") ";
848     OS << "{\n";
849     EmitTargetBuiltins(Builtins.second, TargetPrefix, OS);
850     OS << "}";
851   }
852
853   OS << "  return ";
854   if (!TargetPrefix.empty())
855     OS << "(" << TargetPrefix << "Intrinsic::ID)";
856   OS << "Intrinsic::not_intrinsic;\n";
857   OS << "}\n";
858
859   OS << "#endif\n\n";
860 }
861
862 void llvm::EmitIntrinsics(RecordKeeper &RK, raw_ostream &OS, bool TargetOnly) {
863   IntrinsicEmitter(RK, TargetOnly).run(OS);
864 }