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