1 //===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This tablegen backend emits information about intrinsic functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenIntrinsics.h"
14 #include "CodeGenTarget.h"
15 #include "SequenceToOffsetTable.h"
16 #include "TableGenBackends.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/TableGen/StringMatcher.h"
22 #include "llvm/TableGen/StringToOffsetTable.h"
23 #include "llvm/TableGen/TableGenBackend.h"
24 #include <algorithm>
25 using namespace llvm;
26 
27 cl::OptionCategory GenIntrinsicCat("Options for -gen-intrinsic-enums");
28 cl::opt<std::string>
29     IntrinsicPrefix("intrinsic-prefix",
30                     cl::desc("Generate intrinsics with this target prefix"),
31                     cl::value_desc("target prefix"), cl::cat(GenIntrinsicCat));
32 
33 namespace {
34 class IntrinsicEmitter {
35   RecordKeeper &Records;
36 
37 public:
38   IntrinsicEmitter(RecordKeeper &R) : Records(R) {}
39 
40   void run(raw_ostream &OS, bool Enums);
41 
42   void EmitPrefix(raw_ostream &OS);
43 
44   void EmitEnumInfo(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
45   void EmitTargetInfo(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
46   void EmitIntrinsicToNameTable(const CodeGenIntrinsicTable &Ints,
47                                 raw_ostream &OS);
48   void EmitIntrinsicToOverloadTable(const CodeGenIntrinsicTable &Ints,
49                                     raw_ostream &OS);
50   void EmitGenerator(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
51   void EmitAttributes(const CodeGenIntrinsicTable &Ints, raw_ostream &OS);
52   void EmitIntrinsicToBuiltinMap(const CodeGenIntrinsicTable &Ints, bool IsGCC,
53                                  raw_ostream &OS);
54   void EmitSuffix(raw_ostream &OS);
55 };
56 } // End anonymous namespace
57 
58 //===----------------------------------------------------------------------===//
59 // IntrinsicEmitter Implementation
60 //===----------------------------------------------------------------------===//
61 
62 void IntrinsicEmitter::run(raw_ostream &OS, bool Enums) {
63   emitSourceFileHeader("Intrinsic Function Source Fragment", OS);
64 
65   CodeGenIntrinsicTable Ints(Records);
66 
67   if (Enums) {
68     // Emit the enum information.
69     EmitEnumInfo(Ints, OS);
70   } else {
71     EmitPrefix(OS);
72 
73     // Emit the target metadata.
74     EmitTargetInfo(Ints, OS);
75 
76     // Emit the intrinsic ID -> name table.
77     EmitIntrinsicToNameTable(Ints, OS);
78 
79     // Emit the intrinsic ID -> overload table.
80     EmitIntrinsicToOverloadTable(Ints, OS);
81 
82     // Emit the intrinsic declaration generator.
83     EmitGenerator(Ints, OS);
84 
85     // Emit the intrinsic parameter attributes.
86     EmitAttributes(Ints, OS);
87 
88     // Emit code to translate GCC builtins into LLVM intrinsics.
89     EmitIntrinsicToBuiltinMap(Ints, true, OS);
90 
91     // Emit code to translate MS builtins into LLVM intrinsics.
92     EmitIntrinsicToBuiltinMap(Ints, false, OS);
93 
94     EmitSuffix(OS);
95   }
96 }
97 
98 void IntrinsicEmitter::EmitPrefix(raw_ostream &OS) {
99   OS << "// VisualStudio defines setjmp as _setjmp\n"
100         "#if defined(_MSC_VER) && defined(setjmp) && \\\n"
101         "                         !defined(setjmp_undefined_for_msvc)\n"
102         "#  pragma push_macro(\"setjmp\")\n"
103         "#  undef setjmp\n"
104         "#  define setjmp_undefined_for_msvc\n"
105         "#endif\n\n";
106 }
107 
108 void IntrinsicEmitter::EmitSuffix(raw_ostream &OS) {
109   OS << "#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)\n"
110         "// let's return it to _setjmp state\n"
111         "#  pragma pop_macro(\"setjmp\")\n"
112         "#  undef setjmp_undefined_for_msvc\n"
113         "#endif\n\n";
114 }
115 
116 void IntrinsicEmitter::EmitEnumInfo(const CodeGenIntrinsicTable &Ints,
117                                     raw_ostream &OS) {
118   // Find the TargetSet for which to generate enums. There will be an initial
119   // set with an empty target prefix which will include target independent
120   // intrinsics like dbg.value.
121   const CodeGenIntrinsicTable::TargetSet *Set = nullptr;
122   for (const auto &Target : Ints.Targets) {
123     if (Target.Name == IntrinsicPrefix) {
124       Set = &Target;
125       break;
126     }
127   }
128   if (!Set) {
129     std::vector<std::string> KnownTargets;
130     for (const auto &Target : Ints.Targets)
131       if (!Target.Name.empty())
132         KnownTargets.push_back(Target.Name);
133     PrintFatalError("tried to generate intrinsics for unknown target " +
134                     IntrinsicPrefix +
135                     "\nKnown targets are: " + join(KnownTargets, ", ") + "\n");
136   }
137 
138   // Generate a complete header for target specific intrinsics.
139   if (!IntrinsicPrefix.empty()) {
140     std::string UpperPrefix = StringRef(IntrinsicPrefix).upper();
141     OS << "#ifndef LLVM_IR_INTRINSIC_" << UpperPrefix << "_ENUMS_H\n";
142     OS << "#define LLVM_IR_INTRINSIC_" << UpperPrefix << "_ENUMS_H\n\n";
143     OS << "namespace llvm {\n";
144     OS << "namespace Intrinsic {\n";
145     OS << "enum " << UpperPrefix << "Intrinsics : unsigned {\n";
146   } else {
147     EmitPrefix(OS);
148   }
149 
150   OS << "// Enum values for intrinsics\n";
151   for (unsigned i = Set->Offset, e = Set->Offset + Set->Count; i != e; ++i) {
152     OS << "    " << Ints[i].EnumName;
153 
154     // Assign a value to the first intrinsic in this target set so that all
155     // intrinsic ids are distinct.
156     if (i == Set->Offset)
157       OS << " = " << (Set->Offset + 1);
158 
159     OS << ", ";
160     if (Ints[i].EnumName.size() < 40)
161       OS.indent(40 - Ints[i].EnumName.size());
162     OS << " // " << Ints[i].Name << "\n";
163   }
164 
165   // Emit num_intrinsics into the target neutral enum.
166   if (IntrinsicPrefix.empty()) {
167     OS << "    num_intrinsics = " << (Ints.size() + 1) << "\n";
168     EmitSuffix(OS);
169   } else {
170     OS << "}; // enum\n";
171     OS << "} // namespace Intrinsic\n";
172     OS << "} // namespace llvm\n\n";
173     OS << "#endif\n";
174   }
175 }
176 
177 void IntrinsicEmitter::EmitTargetInfo(const CodeGenIntrinsicTable &Ints,
178                                     raw_ostream &OS) {
179   OS << "// Target mapping\n";
180   OS << "#ifdef GET_INTRINSIC_TARGET_DATA\n";
181   OS << "struct IntrinsicTargetInfo {\n"
182      << "  llvm::StringLiteral Name;\n"
183      << "  size_t Offset;\n"
184      << "  size_t Count;\n"
185      << "};\n";
186   OS << "static constexpr IntrinsicTargetInfo TargetInfos[] = {\n";
187   for (auto Target : Ints.Targets)
188     OS << "  {llvm::StringLiteral(\"" << Target.Name << "\"), " << Target.Offset
189        << ", " << Target.Count << "},\n";
190   OS << "};\n";
191   OS << "#endif\n\n";
192 }
193 
194 void IntrinsicEmitter::EmitIntrinsicToNameTable(
195     const CodeGenIntrinsicTable &Ints, 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::EmitIntrinsicToOverloadTable(
205     const CodeGenIntrinsicTable &Ints, raw_ostream &OS) {
206   OS << "// Intrinsic ID to overload bitset\n";
207   OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
208   OS << "static const uint8_t OTable[] = {\n";
209   OS << "  0";
210   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
211     // Add one to the index so we emit a null bit for the invalid #0 intrinsic.
212     if ((i+1)%8 == 0)
213       OS << ",\n  0";
214     if (Ints[i].isOverloaded)
215       OS << " | (1<<" << (i+1)%8 << ')';
216   }
217   OS << "\n};\n\n";
218   // OTable contains a true bit at the position if the intrinsic is overloaded.
219   OS << "return (OTable[id/8] & (1 << (id%8))) != 0;\n";
220   OS << "#endif\n\n";
221 }
222 
223 
224 // NOTE: This must be kept in synch with the copy in lib/IR/Function.cpp!
225 enum IIT_Info {
226   // Common values should be encoded with 0-15.
227   IIT_Done = 0,
228   IIT_I1   = 1,
229   IIT_I8   = 2,
230   IIT_I16  = 3,
231   IIT_I32  = 4,
232   IIT_I64  = 5,
233   IIT_F16  = 6,
234   IIT_F32  = 7,
235   IIT_F64  = 8,
236   IIT_V2   = 9,
237   IIT_V4   = 10,
238   IIT_V8   = 11,
239   IIT_V16  = 12,
240   IIT_V32  = 13,
241   IIT_PTR  = 14,
242   IIT_ARG  = 15,
243 
244   // Values from 16+ are only encodable with the inefficient encoding.
245   IIT_V64  = 16,
246   IIT_MMX  = 17,
247   IIT_TOKEN = 18,
248   IIT_METADATA = 19,
249   IIT_EMPTYSTRUCT = 20,
250   IIT_STRUCT2 = 21,
251   IIT_STRUCT3 = 22,
252   IIT_STRUCT4 = 23,
253   IIT_STRUCT5 = 24,
254   IIT_EXTEND_ARG = 25,
255   IIT_TRUNC_ARG = 26,
256   IIT_ANYPTR = 27,
257   IIT_V1   = 28,
258   IIT_VARARG = 29,
259   IIT_HALF_VEC_ARG = 30,
260   IIT_SAME_VEC_WIDTH_ARG = 31,
261   IIT_PTR_TO_ARG = 32,
262   IIT_PTR_TO_ELT = 33,
263   IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
264   IIT_I128 = 35,
265   IIT_V512 = 36,
266   IIT_V1024 = 37,
267   IIT_STRUCT6 = 38,
268   IIT_STRUCT7 = 39,
269   IIT_STRUCT8 = 40,
270   IIT_F128 = 41,
271   IIT_VEC_ELEMENT = 42,
272   IIT_SCALABLE_VEC = 43,
273   IIT_SUBDIVIDE2_ARG = 44,
274   IIT_SUBDIVIDE4_ARG = 45,
275   IIT_VEC_OF_BITCASTS_TO_INT = 46
276 };
277 
278 static void EncodeFixedValueType(MVT::SimpleValueType VT,
279                                  std::vector<unsigned char> &Sig) {
280   if (MVT(VT).isInteger()) {
281     unsigned BitWidth = MVT(VT).getSizeInBits();
282     switch (BitWidth) {
283     default: PrintFatalError("unhandled integer type width in intrinsic!");
284     case 1: return Sig.push_back(IIT_I1);
285     case 8: return Sig.push_back(IIT_I8);
286     case 16: return Sig.push_back(IIT_I16);
287     case 32: return Sig.push_back(IIT_I32);
288     case 64: return Sig.push_back(IIT_I64);
289     case 128: return Sig.push_back(IIT_I128);
290     }
291   }
292 
293   switch (VT) {
294   default: PrintFatalError("unhandled MVT in intrinsic!");
295   case MVT::f16: return Sig.push_back(IIT_F16);
296   case MVT::f32: return Sig.push_back(IIT_F32);
297   case MVT::f64: return Sig.push_back(IIT_F64);
298   case MVT::f128: return Sig.push_back(IIT_F128);
299   case MVT::token: return Sig.push_back(IIT_TOKEN);
300   case MVT::Metadata: return Sig.push_back(IIT_METADATA);
301   case MVT::x86mmx: return Sig.push_back(IIT_MMX);
302   // MVT::OtherVT is used to mean the empty struct type here.
303   case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
304   // MVT::isVoid is used to represent varargs here.
305   case MVT::isVoid: return Sig.push_back(IIT_VARARG);
306   }
307 }
308 
309 #if defined(_MSC_VER) && !defined(__clang__)
310 #pragma optimize("",off) // MSVC 2015 optimizer can't deal with this function.
311 #endif
312 
313 static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes,
314                             unsigned &NextArgCode,
315                             std::vector<unsigned char> &Sig,
316                             ArrayRef<unsigned char> Mapping) {
317 
318   if (R->isSubClassOf("LLVMMatchType")) {
319     unsigned Number = Mapping[R->getValueAsInt("Number")];
320     assert(Number < ArgCodes.size() && "Invalid matching number!");
321     if (R->isSubClassOf("LLVMExtendedType"))
322       Sig.push_back(IIT_EXTEND_ARG);
323     else if (R->isSubClassOf("LLVMTruncatedType"))
324       Sig.push_back(IIT_TRUNC_ARG);
325     else if (R->isSubClassOf("LLVMHalfElementsVectorType"))
326       Sig.push_back(IIT_HALF_VEC_ARG);
327     else if (R->isSubClassOf("LLVMScalarOrSameVectorWidth")) {
328       Sig.push_back(IIT_SAME_VEC_WIDTH_ARG);
329       Sig.push_back((Number << 3) | ArgCodes[Number]);
330       MVT::SimpleValueType VT = getValueType(R->getValueAsDef("ElTy"));
331       EncodeFixedValueType(VT, Sig);
332       return;
333     }
334     else if (R->isSubClassOf("LLVMPointerTo"))
335       Sig.push_back(IIT_PTR_TO_ARG);
336     else if (R->isSubClassOf("LLVMVectorOfAnyPointersToElt")) {
337       Sig.push_back(IIT_VEC_OF_ANYPTRS_TO_ELT);
338       // Encode overloaded ArgNo
339       Sig.push_back(NextArgCode++);
340       // Encode LLVMMatchType<Number> ArgNo
341       Sig.push_back(Number);
342       return;
343     } else if (R->isSubClassOf("LLVMPointerToElt"))
344       Sig.push_back(IIT_PTR_TO_ELT);
345     else if (R->isSubClassOf("LLVMVectorElementType"))
346       Sig.push_back(IIT_VEC_ELEMENT);
347     else if (R->isSubClassOf("LLVMSubdivide2VectorType"))
348       Sig.push_back(IIT_SUBDIVIDE2_ARG);
349     else if (R->isSubClassOf("LLVMSubdivide4VectorType"))
350       Sig.push_back(IIT_SUBDIVIDE4_ARG);
351     else if (R->isSubClassOf("LLVMVectorOfBitcastsToInt"))
352       Sig.push_back(IIT_VEC_OF_BITCASTS_TO_INT);
353     else
354       Sig.push_back(IIT_ARG);
355     return Sig.push_back((Number << 3) | 7 /*IITDescriptor::AK_MatchType*/);
356   }
357 
358   MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
359 
360   unsigned Tmp = 0;
361   switch (VT) {
362   default: break;
363   case MVT::iPTRAny: ++Tmp; LLVM_FALLTHROUGH;
364   case MVT::vAny: ++Tmp;    LLVM_FALLTHROUGH;
365   case MVT::fAny: ++Tmp;    LLVM_FALLTHROUGH;
366   case MVT::iAny: ++Tmp;    LLVM_FALLTHROUGH;
367   case MVT::Any: {
368     // If this is an "any" valuetype, then the type is the type of the next
369     // type in the list specified to getIntrinsic().
370     Sig.push_back(IIT_ARG);
371 
372     // Figure out what arg # this is consuming, and remember what kind it was.
373     assert(NextArgCode < ArgCodes.size() && ArgCodes[NextArgCode] == Tmp &&
374            "Invalid or no ArgCode associated with overloaded VT!");
375     unsigned ArgNo = NextArgCode++;
376 
377     // Encode what sort of argument it must be in the low 3 bits of the ArgNo.
378     return Sig.push_back((ArgNo << 3) | Tmp);
379   }
380 
381   case MVT::iPTR: {
382     unsigned AddrSpace = 0;
383     if (R->isSubClassOf("LLVMQualPointerType")) {
384       AddrSpace = R->getValueAsInt("AddrSpace");
385       assert(AddrSpace < 256 && "Address space exceeds 255");
386     }
387     if (AddrSpace) {
388       Sig.push_back(IIT_ANYPTR);
389       Sig.push_back(AddrSpace);
390     } else {
391       Sig.push_back(IIT_PTR);
392     }
393     return EncodeFixedType(R->getValueAsDef("ElTy"), ArgCodes, NextArgCode, Sig,
394                            Mapping);
395   }
396   }
397 
398   if (MVT(VT).isVector()) {
399     MVT VVT = VT;
400     if (VVT.isScalableVector())
401       Sig.push_back(IIT_SCALABLE_VEC);
402     switch (VVT.getVectorNumElements()) {
403     default: PrintFatalError("unhandled vector type width in intrinsic!");
404     case 1: Sig.push_back(IIT_V1); break;
405     case 2: Sig.push_back(IIT_V2); break;
406     case 4: Sig.push_back(IIT_V4); break;
407     case 8: Sig.push_back(IIT_V8); break;
408     case 16: Sig.push_back(IIT_V16); break;
409     case 32: Sig.push_back(IIT_V32); break;
410     case 64: Sig.push_back(IIT_V64); break;
411     case 512: Sig.push_back(IIT_V512); break;
412     case 1024: Sig.push_back(IIT_V1024); break;
413     }
414 
415     return EncodeFixedValueType(VVT.getVectorElementType().SimpleTy, Sig);
416   }
417 
418   EncodeFixedValueType(VT, Sig);
419 }
420 
421 static void UpdateArgCodes(Record *R, std::vector<unsigned char> &ArgCodes,
422                            unsigned int &NumInserted,
423                            SmallVectorImpl<unsigned char> &Mapping) {
424   if (R->isSubClassOf("LLVMMatchType")) {
425     if (R->isSubClassOf("LLVMVectorOfAnyPointersToElt")) {
426       ArgCodes.push_back(3 /*vAny*/);
427       ++NumInserted;
428     }
429     return;
430   }
431 
432   unsigned Tmp = 0;
433   switch (getValueType(R->getValueAsDef("VT"))) {
434   default: break;
435   case MVT::iPTR:
436     UpdateArgCodes(R->getValueAsDef("ElTy"), ArgCodes, NumInserted, Mapping);
437     break;
438   case MVT::iPTRAny:
439     ++Tmp;
440     LLVM_FALLTHROUGH;
441   case MVT::vAny:
442     ++Tmp;
443     LLVM_FALLTHROUGH;
444   case MVT::fAny:
445     ++Tmp;
446     LLVM_FALLTHROUGH;
447   case MVT::iAny:
448     ++Tmp;
449     LLVM_FALLTHROUGH;
450   case MVT::Any:
451     unsigned OriginalIdx = ArgCodes.size() - NumInserted;
452     assert(OriginalIdx >= Mapping.size());
453     Mapping.resize(OriginalIdx+1);
454     Mapping[OriginalIdx] = ArgCodes.size();
455     ArgCodes.push_back(Tmp);
456     break;
457   }
458 }
459 
460 #if defined(_MSC_VER) && !defined(__clang__)
461 #pragma optimize("",on)
462 #endif
463 
464 /// ComputeFixedEncoding - If we can encode the type signature for this
465 /// intrinsic into 32 bits, return it.  If not, return ~0U.
466 static void ComputeFixedEncoding(const CodeGenIntrinsic &Int,
467                                  std::vector<unsigned char> &TypeSig) {
468   std::vector<unsigned char> ArgCodes;
469 
470   // Add codes for any overloaded result VTs.
471   unsigned int NumInserted = 0;
472   SmallVector<unsigned char, 8> ArgMapping;
473   for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
474     UpdateArgCodes(Int.IS.RetTypeDefs[i], ArgCodes, NumInserted, ArgMapping);
475 
476   // Add codes for any overloaded operand VTs.
477   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
478     UpdateArgCodes(Int.IS.ParamTypeDefs[i], ArgCodes, NumInserted, ArgMapping);
479 
480   unsigned NextArgCode = 0;
481   if (Int.IS.RetVTs.empty())
482     TypeSig.push_back(IIT_Done);
483   else if (Int.IS.RetVTs.size() == 1 &&
484            Int.IS.RetVTs[0] == MVT::isVoid)
485     TypeSig.push_back(IIT_Done);
486   else {
487     switch (Int.IS.RetVTs.size()) {
488       case 1: break;
489       case 2: TypeSig.push_back(IIT_STRUCT2); break;
490       case 3: TypeSig.push_back(IIT_STRUCT3); break;
491       case 4: TypeSig.push_back(IIT_STRUCT4); break;
492       case 5: TypeSig.push_back(IIT_STRUCT5); break;
493       case 6: TypeSig.push_back(IIT_STRUCT6); break;
494       case 7: TypeSig.push_back(IIT_STRUCT7); break;
495       case 8: TypeSig.push_back(IIT_STRUCT8); break;
496       default: llvm_unreachable("Unhandled case in struct");
497     }
498 
499     for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
500       EncodeFixedType(Int.IS.RetTypeDefs[i], ArgCodes, NextArgCode, TypeSig,
501                       ArgMapping);
502   }
503 
504   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
505     EncodeFixedType(Int.IS.ParamTypeDefs[i], ArgCodes, NextArgCode, TypeSig,
506                     ArgMapping);
507 }
508 
509 static void printIITEntry(raw_ostream &OS, unsigned char X) {
510   OS << (unsigned)X;
511 }
512 
513 void IntrinsicEmitter::EmitGenerator(const CodeGenIntrinsicTable &Ints,
514                                      raw_ostream &OS) {
515   // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
516   // capture it in this vector, otherwise store a ~0U.
517   std::vector<unsigned> FixedEncodings;
518 
519   SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable;
520 
521   std::vector<unsigned char> TypeSig;
522 
523   // Compute the unique argument type info.
524   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
525     // Get the signature for the intrinsic.
526     TypeSig.clear();
527     ComputeFixedEncoding(Ints[i], TypeSig);
528 
529     // Check to see if we can encode it into a 32-bit word.  We can only encode
530     // 8 nibbles into a 32-bit word.
531     if (TypeSig.size() <= 8) {
532       bool Failed = false;
533       unsigned Result = 0;
534       for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
535         // If we had an unencodable argument, bail out.
536         if (TypeSig[i] > 15) {
537           Failed = true;
538           break;
539         }
540         Result = (Result << 4) | TypeSig[e-i-1];
541       }
542 
543       // If this could be encoded into a 31-bit word, return it.
544       if (!Failed && (Result >> 31) == 0) {
545         FixedEncodings.push_back(Result);
546         continue;
547       }
548     }
549 
550     // Otherwise, we're going to unique the sequence into the
551     // LongEncodingTable, and use its offset in the 32-bit table instead.
552     LongEncodingTable.add(TypeSig);
553 
554     // This is a placehold that we'll replace after the table is laid out.
555     FixedEncodings.push_back(~0U);
556   }
557 
558   LongEncodingTable.layout();
559 
560   OS << "// Global intrinsic function declaration type table.\n";
561   OS << "#ifdef GET_INTRINSIC_GENERATOR_GLOBAL\n";
562 
563   OS << "static const unsigned IIT_Table[] = {\n  ";
564 
565   for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
566     if ((i & 7) == 7)
567       OS << "\n  ";
568 
569     // If the entry fit in the table, just emit it.
570     if (FixedEncodings[i] != ~0U) {
571       OS << "0x" << Twine::utohexstr(FixedEncodings[i]) << ", ";
572       continue;
573     }
574 
575     TypeSig.clear();
576     ComputeFixedEncoding(Ints[i], TypeSig);
577 
578 
579     // Otherwise, emit the offset into the long encoding table.  We emit it this
580     // way so that it is easier to read the offset in the .def file.
581     OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", ";
582   }
583 
584   OS << "0\n};\n\n";
585 
586   // Emit the shared table of register lists.
587   OS << "static const unsigned char IIT_LongEncodingTable[] = {\n";
588   if (!LongEncodingTable.empty())
589     LongEncodingTable.emit(OS, printIITEntry);
590   OS << "  255\n};\n\n";
591 
592   OS << "#endif\n\n";  // End of GET_INTRINSIC_GENERATOR_GLOBAL
593 }
594 
595 namespace {
596 struct AttributeComparator {
597   bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
598     // Sort throwing intrinsics after non-throwing intrinsics.
599     if (L->canThrow != R->canThrow)
600       return R->canThrow;
601 
602     if (L->isNoDuplicate != R->isNoDuplicate)
603       return R->isNoDuplicate;
604 
605     if (L->isNoReturn != R->isNoReturn)
606       return R->isNoReturn;
607 
608     if (L->isWillReturn != R->isWillReturn)
609       return R->isWillReturn;
610 
611     if (L->isCold != R->isCold)
612       return R->isCold;
613 
614     if (L->isConvergent != R->isConvergent)
615       return R->isConvergent;
616 
617     if (L->isSpeculatable != R->isSpeculatable)
618       return R->isSpeculatable;
619 
620     if (L->hasSideEffects != R->hasSideEffects)
621       return R->hasSideEffects;
622 
623     // Try to order by readonly/readnone attribute.
624     CodeGenIntrinsic::ModRefBehavior LK = L->ModRef;
625     CodeGenIntrinsic::ModRefBehavior RK = R->ModRef;
626     if (LK != RK) return (LK > RK);
627     // Order by argument attributes.
628     // This is reliable because each side is already sorted internally.
629     return (L->ArgumentAttributes < R->ArgumentAttributes);
630   }
631 };
632 } // End anonymous namespace
633 
634 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
635 void IntrinsicEmitter::EmitAttributes(const CodeGenIntrinsicTable &Ints,
636                                       raw_ostream &OS) {
637   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
638   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
639   OS << "AttributeList Intrinsic::getAttributes(LLVMContext &C, ID id) {\n";
640 
641   // Compute the maximum number of attribute arguments and the map
642   typedef std::map<const CodeGenIntrinsic*, unsigned,
643                    AttributeComparator> UniqAttrMapTy;
644   UniqAttrMapTy UniqAttributes;
645   unsigned maxArgAttrs = 0;
646   unsigned AttrNum = 0;
647   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
648     const CodeGenIntrinsic &intrinsic = Ints[i];
649     maxArgAttrs =
650       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
651     unsigned &N = UniqAttributes[&intrinsic];
652     if (N) continue;
653     assert(AttrNum < 256 && "Too many unique attributes for table!");
654     N = ++AttrNum;
655   }
656 
657   // Emit an array of AttributeList.  Most intrinsics will have at least one
658   // entry, for the function itself (index ~1), which is usually nounwind.
659   OS << "  static const uint8_t IntrinsicsToAttributesMap[] = {\n";
660 
661   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
662     const CodeGenIntrinsic &intrinsic = Ints[i];
663 
664     OS << "    " << UniqAttributes[&intrinsic] << ", // "
665        << intrinsic.Name << "\n";
666   }
667   OS << "  };\n\n";
668 
669   OS << "  AttributeList AS[" << maxArgAttrs + 1 << "];\n";
670   OS << "  unsigned NumAttrs = 0;\n";
671   OS << "  if (id != 0) {\n";
672   OS << "    switch(IntrinsicsToAttributesMap[id - 1]) {\n";
673   OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
674   for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(),
675        E = UniqAttributes.end(); I != E; ++I) {
676     OS << "    case " << I->second << ": {\n";
677 
678     const CodeGenIntrinsic &intrinsic = *(I->first);
679 
680     // Keep track of the number of attributes we're writing out.
681     unsigned numAttrs = 0;
682 
683     // The argument attributes are alreadys sorted by argument index.
684     unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size();
685     if (ae) {
686       while (ai != ae) {
687         unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
688         unsigned attrIdx = argNo + 1; // Must match AttributeList::FirstArgIndex
689 
690         OS << "      const Attribute::AttrKind AttrParam" << attrIdx << "[]= {";
691         bool addComma = false;
692 
693         do {
694           switch (intrinsic.ArgumentAttributes[ai].second) {
695           case CodeGenIntrinsic::NoCapture:
696             if (addComma)
697               OS << ",";
698             OS << "Attribute::NoCapture";
699             addComma = true;
700             break;
701           case CodeGenIntrinsic::NoAlias:
702             if (addComma)
703               OS << ",";
704             OS << "Attribute::NoAlias";
705             addComma = true;
706             break;
707           case CodeGenIntrinsic::Returned:
708             if (addComma)
709               OS << ",";
710             OS << "Attribute::Returned";
711             addComma = true;
712             break;
713           case CodeGenIntrinsic::ReadOnly:
714             if (addComma)
715               OS << ",";
716             OS << "Attribute::ReadOnly";
717             addComma = true;
718             break;
719           case CodeGenIntrinsic::WriteOnly:
720             if (addComma)
721               OS << ",";
722             OS << "Attribute::WriteOnly";
723             addComma = true;
724             break;
725           case CodeGenIntrinsic::ReadNone:
726             if (addComma)
727               OS << ",";
728             OS << "Attribute::ReadNone";
729             addComma = true;
730             break;
731           case CodeGenIntrinsic::ImmArg:
732             if (addComma)
733               OS << ',';
734             OS << "Attribute::ImmArg";
735             addComma = true;
736             break;
737           }
738 
739           ++ai;
740         } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
741         OS << "};\n";
742         OS << "      AS[" << numAttrs++ << "] = AttributeList::get(C, "
743            << attrIdx << ", AttrParam" << attrIdx << ");\n";
744       }
745     }
746 
747     if (!intrinsic.canThrow ||
748         (intrinsic.ModRef != CodeGenIntrinsic::ReadWriteMem && !intrinsic.hasSideEffects) ||
749         intrinsic.isNoReturn || intrinsic.isWillReturn || intrinsic.isCold ||
750         intrinsic.isNoDuplicate || intrinsic.isConvergent ||
751         intrinsic.isSpeculatable) {
752       OS << "      const Attribute::AttrKind Atts[] = {";
753       bool addComma = false;
754       if (!intrinsic.canThrow) {
755         OS << "Attribute::NoUnwind";
756         addComma = true;
757       }
758       if (intrinsic.isNoReturn) {
759         if (addComma)
760           OS << ",";
761         OS << "Attribute::NoReturn";
762         addComma = true;
763       }
764       if (intrinsic.isWillReturn) {
765         if (addComma)
766           OS << ",";
767         OS << "Attribute::WillReturn";
768         addComma = true;
769       }
770       if (intrinsic.isCold) {
771         if (addComma)
772           OS << ",";
773         OS << "Attribute::Cold";
774         addComma = true;
775       }
776       if (intrinsic.isNoDuplicate) {
777         if (addComma)
778           OS << ",";
779         OS << "Attribute::NoDuplicate";
780         addComma = true;
781       }
782       if (intrinsic.isConvergent) {
783         if (addComma)
784           OS << ",";
785         OS << "Attribute::Convergent";
786         addComma = true;
787       }
788       if (intrinsic.isSpeculatable) {
789         if (addComma)
790           OS << ",";
791         OS << "Attribute::Speculatable";
792         addComma = true;
793       }
794 
795       switch (intrinsic.ModRef) {
796       case CodeGenIntrinsic::NoMem:
797         if (intrinsic.hasSideEffects)
798           break;
799         if (addComma)
800           OS << ",";
801         OS << "Attribute::ReadNone";
802         break;
803       case CodeGenIntrinsic::ReadArgMem:
804         if (addComma)
805           OS << ",";
806         OS << "Attribute::ReadOnly,";
807         OS << "Attribute::ArgMemOnly";
808         break;
809       case CodeGenIntrinsic::ReadMem:
810         if (addComma)
811           OS << ",";
812         OS << "Attribute::ReadOnly";
813         break;
814       case CodeGenIntrinsic::ReadInaccessibleMem:
815         if (addComma)
816           OS << ",";
817         OS << "Attribute::ReadOnly,";
818         OS << "Attribute::InaccessibleMemOnly";
819         break;
820       case CodeGenIntrinsic::ReadInaccessibleMemOrArgMem:
821         if (addComma)
822           OS << ",";
823         OS << "Attribute::ReadOnly,";
824         OS << "Attribute::InaccessibleMemOrArgMemOnly";
825         break;
826       case CodeGenIntrinsic::WriteArgMem:
827         if (addComma)
828           OS << ",";
829         OS << "Attribute::WriteOnly,";
830         OS << "Attribute::ArgMemOnly";
831         break;
832       case CodeGenIntrinsic::WriteMem:
833         if (addComma)
834           OS << ",";
835         OS << "Attribute::WriteOnly";
836         break;
837       case CodeGenIntrinsic::WriteInaccessibleMem:
838         if (addComma)
839           OS << ",";
840         OS << "Attribute::WriteOnly,";
841         OS << "Attribute::InaccessibleMemOnly";
842         break;
843       case CodeGenIntrinsic::WriteInaccessibleMemOrArgMem:
844         if (addComma)
845           OS << ",";
846         OS << "Attribute::WriteOnly,";
847         OS << "Attribute::InaccessibleMemOrArgMemOnly";
848         break;
849       case CodeGenIntrinsic::ReadWriteArgMem:
850         if (addComma)
851           OS << ",";
852         OS << "Attribute::ArgMemOnly";
853         break;
854       case CodeGenIntrinsic::ReadWriteInaccessibleMem:
855         if (addComma)
856           OS << ",";
857         OS << "Attribute::InaccessibleMemOnly";
858         break;
859       case CodeGenIntrinsic::ReadWriteInaccessibleMemOrArgMem:
860         if (addComma)
861           OS << ",";
862         OS << "Attribute::InaccessibleMemOrArgMemOnly";
863         break;
864       case CodeGenIntrinsic::ReadWriteMem:
865         break;
866       }
867       OS << "};\n";
868       OS << "      AS[" << numAttrs++ << "] = AttributeList::get(C, "
869          << "AttributeList::FunctionIndex, Atts);\n";
870     }
871 
872     if (numAttrs) {
873       OS << "      NumAttrs = " << numAttrs << ";\n";
874       OS << "      break;\n";
875       OS << "      }\n";
876     } else {
877       OS << "      return AttributeList();\n";
878       OS << "      }\n";
879     }
880   }
881 
882   OS << "    }\n";
883   OS << "  }\n";
884   OS << "  return AttributeList::get(C, makeArrayRef(AS, NumAttrs));\n";
885   OS << "}\n";
886   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
887 }
888 
889 void IntrinsicEmitter::EmitIntrinsicToBuiltinMap(
890     const CodeGenIntrinsicTable &Ints, bool IsGCC, raw_ostream &OS) {
891   StringRef CompilerName = (IsGCC ? "GCC" : "MS");
892   typedef std::map<std::string, std::map<std::string, std::string>> BIMTy;
893   BIMTy BuiltinMap;
894   StringToOffsetTable Table;
895   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
896     const std::string &BuiltinName =
897         IsGCC ? Ints[i].GCCBuiltinName : Ints[i].MSBuiltinName;
898     if (!BuiltinName.empty()) {
899       // Get the map for this target prefix.
900       std::map<std::string, std::string> &BIM =
901           BuiltinMap[Ints[i].TargetPrefix];
902 
903       if (!BIM.insert(std::make_pair(BuiltinName, Ints[i].EnumName)).second)
904         PrintFatalError(Ints[i].TheDef->getLoc(),
905                         "Intrinsic '" + Ints[i].TheDef->getName() +
906                             "': duplicate " + CompilerName + " builtin name!");
907       Table.GetOrAddStringOffset(BuiltinName);
908     }
909   }
910 
911   OS << "// Get the LLVM intrinsic that corresponds to a builtin.\n";
912   OS << "// This is used by the C front-end.  The builtin name is passed\n";
913   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
914   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
915   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_" << CompilerName << "_BUILTIN\n";
916 
917   OS << "Intrinsic::ID Intrinsic::getIntrinsicFor" << CompilerName
918      << "Builtin(const char "
919      << "*TargetPrefixStr, StringRef BuiltinNameStr) {\n";
920 
921   if (Table.Empty()) {
922     OS << "  return Intrinsic::not_intrinsic;\n";
923     OS << "}\n";
924     OS << "#endif\n\n";
925     return;
926   }
927 
928   OS << "  static const char BuiltinNames[] = {\n";
929   Table.EmitCharArray(OS);
930   OS << "  };\n\n";
931 
932   OS << "  struct BuiltinEntry {\n";
933   OS << "    Intrinsic::ID IntrinID;\n";
934   OS << "    unsigned StrTabOffset;\n";
935   OS << "    const char *getName() const {\n";
936   OS << "      return &BuiltinNames[StrTabOffset];\n";
937   OS << "    }\n";
938   OS << "    bool operator<(StringRef RHS) const {\n";
939   OS << "      return strncmp(getName(), RHS.data(), RHS.size()) < 0;\n";
940   OS << "    }\n";
941   OS << "  };\n";
942 
943   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
944 
945   // Note: this could emit significantly better code if we cared.
946   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
947     OS << "  ";
948     if (!I->first.empty())
949       OS << "if (TargetPrefix == \"" << I->first << "\") ";
950     else
951       OS << "/* Target Independent Builtins */ ";
952     OS << "{\n";
953 
954     // Emit the comparisons for this target prefix.
955     OS << "    static const BuiltinEntry " << I->first << "Names[] = {\n";
956     for (const auto &P : I->second) {
957       OS << "      {Intrinsic::" << P.second << ", "
958          << Table.GetOrAddStringOffset(P.first) << "}, // " << P.first << "\n";
959     }
960     OS << "    };\n";
961     OS << "    auto I = std::lower_bound(std::begin(" << I->first << "Names),\n";
962     OS << "                              std::end(" << I->first << "Names),\n";
963     OS << "                              BuiltinNameStr);\n";
964     OS << "    if (I != std::end(" << I->first << "Names) &&\n";
965     OS << "        I->getName() == BuiltinNameStr)\n";
966     OS << "      return I->IntrinID;\n";
967     OS << "  }\n";
968   }
969   OS << "  return ";
970   OS << "Intrinsic::not_intrinsic;\n";
971   OS << "}\n";
972   OS << "#endif\n\n";
973 }
974 
975 void llvm::EmitIntrinsicEnums(RecordKeeper &RK, raw_ostream &OS) {
976   IntrinsicEmitter(RK).run(OS, /*Enums=*/true);
977 }
978 
979 void llvm::EmitIntrinsicImpl(RecordKeeper &RK, raw_ostream &OS) {
980   IntrinsicEmitter(RK).run(OS, /*Enums=*/false);
981 }
982