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