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