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