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>
25using namespace llvm;
26
27cl::OptionCategory GenIntrinsicCat("Options for -gen-intrinsic-enums");
28cl::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
33namespace {
34class IntrinsicEmitter {
35  RecordKeeper &Records;
36
37public:
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
59void 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
91void 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
149void 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
166void 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
176void 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!
197enum 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};
249
250static void EncodeFixedValueType(MVT::SimpleValueType VT,
251                                 std::vector<unsigned char> &Sig) {
252  if (MVT(VT).isInteger()) {
253    unsigned BitWidth = MVT(VT).getSizeInBits();
254    switch (BitWidth) {
255    default: PrintFatalError("unhandled integer type width in intrinsic!");
256    case 1: return Sig.push_back(IIT_I1);
257    case 8: return Sig.push_back(IIT_I8);
258    case 16: return Sig.push_back(IIT_I16);
259    case 32: return Sig.push_back(IIT_I32);
260    case 64: return Sig.push_back(IIT_I64);
261    case 128: return Sig.push_back(IIT_I128);
262    }
263  }
264
265  switch (VT) {
266  default: PrintFatalError("unhandled MVT in intrinsic!");
267  case MVT::f16: return Sig.push_back(IIT_F16);
268  case MVT::f32: return Sig.push_back(IIT_F32);
269  case MVT::f64: return Sig.push_back(IIT_F64);
270  case MVT::f128: return Sig.push_back(IIT_F128);
271  case MVT::token: return Sig.push_back(IIT_TOKEN);
272  case MVT::Metadata: return Sig.push_back(IIT_METADATA);
273  case MVT::x86mmx: return Sig.push_back(IIT_MMX);
274  // MVT::OtherVT is used to mean the empty struct type here.
275  case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
276  // MVT::isVoid is used to represent varargs here.
277  case MVT::isVoid: return Sig.push_back(IIT_VARARG);
278  }
279}
280
281#if defined(_MSC_VER) && !defined(__clang__)
282#pragma optimize("",off) // MSVC 2015 optimizer can't deal with this function.
283#endif
284
285static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes,
286                            unsigned &NextArgCode,
287                            std::vector<unsigned char> &Sig,
288                            ArrayRef<unsigned char> Mapping) {
289
290  if (R->isSubClassOf("LLVMMatchType")) {
291    unsigned Number = Mapping[R->getValueAsInt("Number")];
292    assert(Number < ArgCodes.size() && "Invalid matching number!");
293    if (R->isSubClassOf("LLVMExtendedType"))
294      Sig.push_back(IIT_EXTEND_ARG);
295    else if (R->isSubClassOf("LLVMTruncatedType"))
296      Sig.push_back(IIT_TRUNC_ARG);
297    else if (R->isSubClassOf("LLVMHalfElementsVectorType"))
298      Sig.push_back(IIT_HALF_VEC_ARG);
299    else if (R->isSubClassOf("LLVMScalarOrSameVectorWidth")) {
300      Sig.push_back(IIT_SAME_VEC_WIDTH_ARG);
301      Sig.push_back((Number << 3) | ArgCodes[Number]);
302      MVT::SimpleValueType VT = getValueType(R->getValueAsDef("ElTy"));
303      EncodeFixedValueType(VT, Sig);
304      return;
305    }
306    else if (R->isSubClassOf("LLVMPointerTo"))
307      Sig.push_back(IIT_PTR_TO_ARG);
308    else if (R->isSubClassOf("LLVMVectorOfAnyPointersToElt")) {
309      Sig.push_back(IIT_VEC_OF_ANYPTRS_TO_ELT);
310      // Encode overloaded ArgNo
311      Sig.push_back(NextArgCode++);
312      // Encode LLVMMatchType<Number> ArgNo
313      Sig.push_back(Number);
314      return;
315    } else if (R->isSubClassOf("LLVMPointerToElt"))
316      Sig.push_back(IIT_PTR_TO_ELT);
317    else if (R->isSubClassOf("LLVMVectorElementType"))
318      Sig.push_back(IIT_VEC_ELEMENT);
319    else if (R->isSubClassOf("LLVMSubdivide2VectorType"))
320      Sig.push_back(IIT_SUBDIVIDE2_ARG);
321    else if (R->isSubClassOf("LLVMSubdivide4VectorType"))
322      Sig.push_back(IIT_SUBDIVIDE4_ARG);
323    else if (R->isSubClassOf("LLVMVectorOfBitcastsToInt"))
324      Sig.push_back(IIT_VEC_OF_BITCASTS_TO_INT);
325    else
326      Sig.push_back(IIT_ARG);
327    return Sig.push_back((Number << 3) | 7 /*IITDescriptor::AK_MatchType*/);
328  }
329
330  MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
331
332  unsigned Tmp = 0;
333  switch (VT) {
334  default: break;
335  case MVT::iPTRAny: ++Tmp; LLVM_FALLTHROUGH;
336  case MVT::vAny: ++Tmp;    LLVM_FALLTHROUGH;
337  case MVT::fAny: ++Tmp;    LLVM_FALLTHROUGH;
338  case MVT::iAny: ++Tmp;    LLVM_FALLTHROUGH;
339  case MVT::Any: {
340    // If this is an "any" valuetype, then the type is the type of the next
341    // type in the list specified to getIntrinsic().
342    Sig.push_back(IIT_ARG);
343
344    // Figure out what arg # this is consuming, and remember what kind it was.
345    assert(NextArgCode < ArgCodes.size() && ArgCodes[NextArgCode] == Tmp &&
346           "Invalid or no ArgCode associated with overloaded VT!");
347    unsigned ArgNo = NextArgCode++;
348
349    // Encode what sort of argument it must be in the low 3 bits of the ArgNo.
350    return Sig.push_back((ArgNo << 3) | Tmp);
351  }
352
353  case MVT::iPTR: {
354    unsigned AddrSpace = 0;
355    if (R->isSubClassOf("LLVMQualPointerType")) {
356      AddrSpace = R->getValueAsInt("AddrSpace");
357      assert(AddrSpace < 256 && "Address space exceeds 255");
358    }
359    if (AddrSpace) {
360      Sig.push_back(IIT_ANYPTR);
361      Sig.push_back(AddrSpace);
362    } else {
363      Sig.push_back(IIT_PTR);
364    }
365    return EncodeFixedType(R->getValueAsDef("ElTy"), ArgCodes, NextArgCode, Sig,
366                           Mapping);
367  }
368  }
369
370  if (MVT(VT).isVector()) {
371    MVT VVT = VT;
372    if (VVT.isScalableVector())
373      Sig.push_back(IIT_SCALABLE_VEC);
374    switch (VVT.getVectorNumElements()) {
375    default: PrintFatalError("unhandled vector type width in intrinsic!");
376    case 1: Sig.push_back(IIT_V1); break;
377    case 2: Sig.push_back(IIT_V2); break;
378    case 4: Sig.push_back(IIT_V4); break;
379    case 8: Sig.push_back(IIT_V8); break;
380    case 16: Sig.push_back(IIT_V16); break;
381    case 32: Sig.push_back(IIT_V32); break;
382    case 64: Sig.push_back(IIT_V64); break;
383    case 512: Sig.push_back(IIT_V512); break;
384    case 1024: Sig.push_back(IIT_V1024); break;
385    }
386
387    return EncodeFixedValueType(VVT.getVectorElementType().SimpleTy, Sig);
388  }
389
390  EncodeFixedValueType(VT, Sig);
391}
392
393static void UpdateArgCodes(Record *R, std::vector<unsigned char> &ArgCodes,
394                           unsigned int &NumInserted,
395                           SmallVectorImpl<unsigned char> &Mapping) {
396  if (R->isSubClassOf("LLVMMatchType")) {
397    if (R->isSubClassOf("LLVMVectorOfAnyPointersToElt")) {
398      ArgCodes.push_back(3 /*vAny*/);
399      ++NumInserted;
400    }
401    return;
402  }
403
404  unsigned Tmp = 0;
405  switch (getValueType(R->getValueAsDef("VT"))) {
406  default: break;
407  case MVT::iPTR:
408    UpdateArgCodes(R->getValueAsDef("ElTy"), ArgCodes, NumInserted, Mapping);
409    break;
410  case MVT::iPTRAny:
411    ++Tmp;
412    LLVM_FALLTHROUGH;
413  case MVT::vAny:
414    ++Tmp;
415    LLVM_FALLTHROUGH;
416  case MVT::fAny:
417    ++Tmp;
418    LLVM_FALLTHROUGH;
419  case MVT::iAny:
420    ++Tmp;
421    LLVM_FALLTHROUGH;
422  case MVT::Any:
423    unsigned OriginalIdx = ArgCodes.size() - NumInserted;
424    assert(OriginalIdx >= Mapping.size());
425    Mapping.resize(OriginalIdx+1);
426    Mapping[OriginalIdx] = ArgCodes.size();
427    ArgCodes.push_back(Tmp);
428    break;
429  }
430}
431
432#if defined(_MSC_VER) && !defined(__clang__)
433#pragma optimize("",on)
434#endif
435
436/// ComputeFixedEncoding - If we can encode the type signature for this
437/// intrinsic into 32 bits, return it.  If not, return ~0U.
438static void ComputeFixedEncoding(const CodeGenIntrinsic &Int,
439                                 std::vector<unsigned char> &TypeSig) {
440  std::vector<unsigned char> ArgCodes;
441
442  // Add codes for any overloaded result VTs.
443  unsigned int NumInserted = 0;
444  SmallVector<unsigned char, 8> ArgMapping;
445  for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
446    UpdateArgCodes(Int.IS.RetTypeDefs[i], ArgCodes, NumInserted, ArgMapping);
447
448  // Add codes for any overloaded operand VTs.
449  for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
450    UpdateArgCodes(Int.IS.ParamTypeDefs[i], ArgCodes, NumInserted, ArgMapping);
451
452  unsigned NextArgCode = 0;
453  if (Int.IS.RetVTs.empty())
454    TypeSig.push_back(IIT_Done);
455  else if (Int.IS.RetVTs.size() == 1 &&
456           Int.IS.RetVTs[0] == MVT::isVoid)
457    TypeSig.push_back(IIT_Done);
458  else {
459    switch (Int.IS.RetVTs.size()) {
460      case 1: break;
461      case 2: TypeSig.push_back(IIT_STRUCT2); break;
462      case 3: TypeSig.push_back(IIT_STRUCT3); break;
463      case 4: TypeSig.push_back(IIT_STRUCT4); break;
464      case 5: TypeSig.push_back(IIT_STRUCT5); break;
465      case 6: TypeSig.push_back(IIT_STRUCT6); break;
466      case 7: TypeSig.push_back(IIT_STRUCT7); break;
467      case 8: TypeSig.push_back(IIT_STRUCT8); break;
468      default: llvm_unreachable("Unhandled case in struct");
469    }
470
471    for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
472      EncodeFixedType(Int.IS.RetTypeDefs[i], ArgCodes, NextArgCode, TypeSig,
473                      ArgMapping);
474  }
475
476  for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
477    EncodeFixedType(Int.IS.ParamTypeDefs[i], ArgCodes, NextArgCode, TypeSig,
478                    ArgMapping);
479}
480
481static void printIITEntry(raw_ostream &OS, unsigned char X) {
482  OS << (unsigned)X;
483}
484
485void IntrinsicEmitter::EmitGenerator(const CodeGenIntrinsicTable &Ints,
486                                     raw_ostream &OS) {
487  // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
488  // capture it in this vector, otherwise store a ~0U.
489  std::vector<unsigned> FixedEncodings;
490
491  SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable;
492
493  std::vector<unsigned char> TypeSig;
494
495  // Compute the unique argument type info.
496  for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
497    // Get the signature for the intrinsic.
498    TypeSig.clear();
499    ComputeFixedEncoding(Ints[i], TypeSig);
500
501    // Check to see if we can encode it into a 32-bit word.  We can only encode
502    // 8 nibbles into a 32-bit word.
503    if (TypeSig.size() <= 8) {
504      bool Failed = false;
505      unsigned Result = 0;
506      for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
507        // If we had an unencodable argument, bail out.
508        if (TypeSig[i] > 15) {
509          Failed = true;
510          break;
511        }
512        Result = (Result << 4) | TypeSig[e-i-1];
513      }
514
515      // If this could be encoded into a 31-bit word, return it.
516      if (!Failed && (Result >> 31) == 0) {
517        FixedEncodings.push_back(Result);
518        continue;
519      }
520    }
521
522    // Otherwise, we're going to unique the sequence into the
523    // LongEncodingTable, and use its offset in the 32-bit table instead.
524    LongEncodingTable.add(TypeSig);
525
526    // This is a placehold that we'll replace after the table is laid out.
527    FixedEncodings.push_back(~0U);
528  }
529
530  LongEncodingTable.layout();
531
532  OS << "// Global intrinsic function declaration type table.\n";
533  OS << "#ifdef GET_INTRINSIC_GENERATOR_GLOBAL\n";
534
535  OS << "static const unsigned IIT_Table[] = {\n  ";
536
537  for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
538    if ((i & 7) == 7)
539      OS << "\n  ";
540
541    // If the entry fit in the table, just emit it.
542    if (FixedEncodings[i] != ~0U) {
543      OS << "0x" << Twine::utohexstr(FixedEncodings[i]) << ", ";
544      continue;
545    }
546
547    TypeSig.clear();
548    ComputeFixedEncoding(Ints[i], TypeSig);
549
550
551    // Otherwise, emit the offset into the long encoding table.  We emit it this
552    // way so that it is easier to read the offset in the .def file.
553    OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", ";
554  }
555
556  OS << "0\n};\n\n";
557
558  // Emit the shared table of register lists.
559  OS << "static const unsigned char IIT_LongEncodingTable[] = {\n";
560  if (!LongEncodingTable.empty())
561    LongEncodingTable.emit(OS, printIITEntry);
562  OS << "  255\n};\n\n";
563
564  OS << "#endif\n\n";  // End of GET_INTRINSIC_GENERATOR_GLOBAL
565}
566
567namespace {
568struct AttributeComparator {
569  bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
570    // Sort throwing intrinsics after non-throwing intrinsics.
571    if (L->canThrow != R->canThrow)
572      return R->canThrow;
573
574    if (L->isNoDuplicate != R->isNoDuplicate)
575      return R->isNoDuplicate;
576
577    if (L->isNoReturn != R->isNoReturn)
578      return R->isNoReturn;
579
580    if (L->isWillReturn != R->isWillReturn)
581      return R->isWillReturn;
582
583    if (L->isCold != R->isCold)
584      return R->isCold;
585
586    if (L->isConvergent != R->isConvergent)
587      return R->isConvergent;
588
589    if (L->isSpeculatable != R->isSpeculatable)
590      return R->isSpeculatable;
591
592    if (L->hasSideEffects != R->hasSideEffects)
593      return R->hasSideEffects;
594
595    // Try to order by readonly/readnone attribute.
596    CodeGenIntrinsic::ModRefBehavior LK = L->ModRef;
597    CodeGenIntrinsic::ModRefBehavior RK = R->ModRef;
598    if (LK != RK) return (LK > RK);
599    // Order by argument attributes.
600    // This is reliable because each side is already sorted internally.
601    return (L->ArgumentAttributes < R->ArgumentAttributes);
602  }
603};
604} // End anonymous namespace
605
606/// EmitAttributes - This emits the Intrinsic::getAttributes method.
607void IntrinsicEmitter::EmitAttributes(const CodeGenIntrinsicTable &Ints,
608                                      raw_ostream &OS) {
609  OS << "// Add parameter attributes that are not common to all intrinsics.\n";
610  OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
611  OS << "AttributeList Intrinsic::getAttributes(LLVMContext &C, ID id) {\n";
612
613  // Compute the maximum number of attribute arguments and the map
614  typedef std::map<const CodeGenIntrinsic*, unsigned,
615                   AttributeComparator> UniqAttrMapTy;
616  UniqAttrMapTy UniqAttributes;
617  unsigned maxArgAttrs = 0;
618  unsigned AttrNum = 0;
619  for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
620    const CodeGenIntrinsic &intrinsic = Ints[i];
621    maxArgAttrs =
622      std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
623    unsigned &N = UniqAttributes[&intrinsic];
624    if (N) continue;
625    assert(AttrNum < 256 && "Too many unique attributes for table!");
626    N = ++AttrNum;
627  }
628
629  // Emit an array of AttributeList.  Most intrinsics will have at least one
630  // entry, for the function itself (index ~1), which is usually nounwind.
631  OS << "  static const uint8_t IntrinsicsToAttributesMap[] = {\n";
632
633  for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
634    const CodeGenIntrinsic &intrinsic = Ints[i];
635
636    OS << "    " << UniqAttributes[&intrinsic] << ", // "
637       << intrinsic.Name << "\n";
638  }
639  OS << "  };\n\n";
640
641  OS << "  AttributeList AS[" << maxArgAttrs + 1 << "];\n";
642  OS << "  unsigned NumAttrs = 0;\n";
643  OS << "  if (id != 0) {\n";
644  OS << "    switch(IntrinsicsToAttributesMap[id - 1]) {\n";
645  OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
646  for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(),
647       E = UniqAttributes.end(); I != E; ++I) {
648    OS << "    case " << I->second << ": {\n";
649
650    const CodeGenIntrinsic &intrinsic = *(I->first);
651
652    // Keep track of the number of attributes we're writing out.
653    unsigned numAttrs = 0;
654
655    // The argument attributes are alreadys sorted by argument index.
656    unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size();
657    if (ae) {
658      while (ai != ae) {
659        unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
660        unsigned attrIdx = argNo + 1; // Must match AttributeList::FirstArgIndex
661
662        OS << "      const Attribute::AttrKind AttrParam" << attrIdx << "[]= {";
663        bool addComma = false;
664
665        do {
666          switch (intrinsic.ArgumentAttributes[ai].second) {
667          case CodeGenIntrinsic::NoCapture:
668            if (addComma)
669              OS << ",";
670            OS << "Attribute::NoCapture";
671            addComma = true;
672            break;
673          case CodeGenIntrinsic::NoAlias:
674            if (addComma)
675              OS << ",";
676            OS << "Attribute::NoAlias";
677            addComma = true;
678            break;
679          case CodeGenIntrinsic::Returned:
680            if (addComma)
681              OS << ",";
682            OS << "Attribute::Returned";
683            addComma = true;
684            break;
685          case CodeGenIntrinsic::ReadOnly:
686            if (addComma)
687              OS << ",";
688            OS << "Attribute::ReadOnly";
689            addComma = true;
690            break;
691          case CodeGenIntrinsic::WriteOnly:
692            if (addComma)
693              OS << ",";
694            OS << "Attribute::WriteOnly";
695            addComma = true;
696            break;
697          case CodeGenIntrinsic::ReadNone:
698            if (addComma)
699              OS << ",";
700            OS << "Attribute::ReadNone";
701            addComma = true;
702            break;
703          case CodeGenIntrinsic::ImmArg:
704            if (addComma)
705              OS << ',';
706            OS << "Attribute::ImmArg";
707            addComma = true;
708            break;
709          }
710
711          ++ai;
712        } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
713        OS << "};\n";
714        OS << "      AS[" << numAttrs++ << "] = AttributeList::get(C, "
715           << attrIdx << ", AttrParam" << attrIdx << ");\n";
716      }
717    }
718
719    if (!intrinsic.canThrow ||
720        (intrinsic.ModRef != CodeGenIntrinsic::ReadWriteMem && !intrinsic.hasSideEffects) ||
721        intrinsic.isNoReturn || intrinsic.isWillReturn || intrinsic.isCold ||
722        intrinsic.isNoDuplicate || intrinsic.isConvergent ||
723        intrinsic.isSpeculatable) {
724      OS << "      const Attribute::AttrKind Atts[] = {";
725      bool addComma = false;
726      if (!intrinsic.canThrow) {
727        OS << "Attribute::NoUnwind";
728        addComma = true;
729      }
730      if (intrinsic.isNoReturn) {
731        if (addComma)
732          OS << ",";
733        OS << "Attribute::NoReturn";
734        addComma = true;
735      }
736      if (intrinsic.isWillReturn) {
737        if (addComma)
738          OS << ",";
739        OS << "Attribute::WillReturn";
740        addComma = true;
741      }
742      if (intrinsic.isCold) {
743        if (addComma)
744          OS << ",";
745        OS << "Attribute::Cold";
746        addComma = true;
747      }
748      if (intrinsic.isNoDuplicate) {
749        if (addComma)
750          OS << ",";
751        OS << "Attribute::NoDuplicate";
752        addComma = true;
753      }
754      if (intrinsic.isConvergent) {
755        if (addComma)
756          OS << ",";
757        OS << "Attribute::Convergent";
758        addComma = true;
759      }
760      if (intrinsic.isSpeculatable) {
761        if (addComma)
762          OS << ",";
763        OS << "Attribute::Speculatable";
764        addComma = true;
765      }
766
767      switch (intrinsic.ModRef) {
768      case CodeGenIntrinsic::NoMem:
769        if (intrinsic.hasSideEffects)
770          break;
771        if (addComma)
772          OS << ",";
773        OS << "Attribute::ReadNone";
774        break;
775      case CodeGenIntrinsic::ReadArgMem:
776        if (addComma)
777          OS << ",";
778        OS << "Attribute::ReadOnly,";
779        OS << "Attribute::ArgMemOnly";
780        break;
781      case CodeGenIntrinsic::ReadMem:
782        if (addComma)
783          OS << ",";
784        OS << "Attribute::ReadOnly";
785        break;
786      case CodeGenIntrinsic::ReadInaccessibleMem:
787        if (addComma)
788          OS << ",";
789        OS << "Attribute::ReadOnly,";
790        OS << "Attribute::InaccessibleMemOnly";
791        break;
792      case CodeGenIntrinsic::ReadInaccessibleMemOrArgMem:
793        if (addComma)
794          OS << ",";
795        OS << "Attribute::ReadOnly,";
796        OS << "Attribute::InaccessibleMemOrArgMemOnly";
797        break;
798      case CodeGenIntrinsic::WriteArgMem:
799        if (addComma)
800          OS << ",";
801        OS << "Attribute::WriteOnly,";
802        OS << "Attribute::ArgMemOnly";
803        break;
804      case CodeGenIntrinsic::WriteMem:
805        if (addComma)
806          OS << ",";
807        OS << "Attribute::WriteOnly";
808        break;
809      case CodeGenIntrinsic::WriteInaccessibleMem:
810        if (addComma)
811          OS << ",";
812        OS << "Attribute::WriteOnly,";
813        OS << "Attribute::InaccessibleMemOnly";
814        break;
815      case CodeGenIntrinsic::WriteInaccessibleMemOrArgMem:
816        if (addComma)
817          OS << ",";
818        OS << "Attribute::WriteOnly,";
819        OS << "Attribute::InaccessibleMemOrArgMemOnly";
820        break;
821      case CodeGenIntrinsic::ReadWriteArgMem:
822        if (addComma)
823          OS << ",";
824        OS << "Attribute::ArgMemOnly";
825        break;
826      case CodeGenIntrinsic::ReadWriteInaccessibleMem:
827        if (addComma)
828          OS << ",";
829        OS << "Attribute::InaccessibleMemOnly";
830        break;
831      case CodeGenIntrinsic::ReadWriteInaccessibleMemOrArgMem:
832        if (addComma)
833          OS << ",";
834        OS << "Attribute::InaccessibleMemOrArgMemOnly";
835        break;
836      case CodeGenIntrinsic::ReadWriteMem:
837        break;
838      }
839      OS << "};\n";
840      OS << "      AS[" << numAttrs++ << "] = AttributeList::get(C, "
841         << "AttributeList::FunctionIndex, Atts);\n";
842    }
843
844    if (numAttrs) {
845      OS << "      NumAttrs = " << numAttrs << ";\n";
846      OS << "      break;\n";
847      OS << "      }\n";
848    } else {
849      OS << "      return AttributeList();\n";
850      OS << "      }\n";
851    }
852  }
853
854  OS << "    }\n";
855  OS << "  }\n";
856  OS << "  return AttributeList::get(C, makeArrayRef(AS, NumAttrs));\n";
857  OS << "}\n";
858  OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
859}
860
861void IntrinsicEmitter::EmitIntrinsicToBuiltinMap(
862    const CodeGenIntrinsicTable &Ints, bool IsGCC, raw_ostream &OS) {
863  StringRef CompilerName = (IsGCC ? "GCC" : "MS");
864  typedef std::map<std::string, std::map<std::string, std::string>> BIMTy;
865  BIMTy BuiltinMap;
866  StringToOffsetTable Table;
867  for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
868    const std::string &BuiltinName =
869        IsGCC ? Ints[i].GCCBuiltinName : Ints[i].MSBuiltinName;
870    if (!BuiltinName.empty()) {
871      // Get the map for this target prefix.
872      std::map<std::string, std::string> &BIM =
873          BuiltinMap[Ints[i].TargetPrefix];
874
875      if (!BIM.insert(std::make_pair(BuiltinName, Ints[i].EnumName)).second)
876        PrintFatalError(Ints[i].TheDef->getLoc(),
877                        "Intrinsic '" + Ints[i].TheDef->getName() +
878                            "': duplicate " + CompilerName + " builtin name!");
879      Table.GetOrAddStringOffset(BuiltinName);
880    }
881  }
882
883  OS << "// Get the LLVM intrinsic that corresponds to a builtin.\n";
884  OS << "// This is used by the C front-end.  The builtin name is passed\n";
885  OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
886  OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
887  OS << "#ifdef GET_LLVM_INTRINSIC_FOR_" << CompilerName << "_BUILTIN\n";
888
889  OS << "Intrinsic::ID Intrinsic::getIntrinsicFor" << CompilerName
890     << "Builtin(const char "
891     << "*TargetPrefixStr, StringRef BuiltinNameStr) {\n";
892
893  if (Table.Empty()) {
894    OS << "  return Intrinsic::not_intrinsic;\n";
895    OS << "}\n";
896    OS << "#endif\n\n";
897    return;
898  }
899
900  OS << "  static const char BuiltinNames[] = {\n";
901  Table.EmitCharArray(OS);
902  OS << "  };\n\n";
903
904  OS << "  struct BuiltinEntry {\n";
905  OS << "    Intrinsic::ID IntrinID;\n";
906  OS << "    unsigned StrTabOffset;\n";
907  OS << "    const char *getName() const {\n";
908  OS << "      return &BuiltinNames[StrTabOffset];\n";
909  OS << "    }\n";
910  OS << "    bool operator<(StringRef RHS) const {\n";
911  OS << "      return strncmp(getName(), RHS.data(), RHS.size()) < 0;\n";
912  OS << "    }\n";
913  OS << "  };\n";
914
915  OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
916
917  // Note: this could emit significantly better code if we cared.
918  for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
919    OS << "  ";
920    if (!I->first.empty())
921      OS << "if (TargetPrefix == \"" << I->first << "\") ";
922    else
923      OS << "/* Target Independent Builtins */ ";
924    OS << "{\n";
925
926    // Emit the comparisons for this target prefix.
927    OS << "    static const BuiltinEntry " << I->first << "Names[] = {\n";
928    for (const auto &P : I->second) {
929      OS << "      {Intrinsic::" << P.second << ", "
930         << Table.GetOrAddStringOffset(P.first) << "}, // " << P.first << "\n";
931    }
932    OS << "    };\n";
933    OS << "    auto I = std::lower_bound(std::begin(" << I->first << "Names),\n";
934    OS << "                              std::end(" << I->first << "Names),\n";
935    OS << "                              BuiltinNameStr);\n";
936    OS << "    if (I != std::end(" << I->first << "Names) &&\n";
937    OS << "        I->getName() == BuiltinNameStr)\n";
938    OS << "      return I->IntrinID;\n";
939    OS << "  }\n";
940  }
941  OS << "  return ";
942  OS << "Intrinsic::not_intrinsic;\n";
943  OS << "}\n";
944  OS << "#endif\n\n";
945}
946
947void llvm::EmitIntrinsicEnums(RecordKeeper &RK, raw_ostream &OS) {
948  IntrinsicEmitter(RK).run(OS, /*Enums=*/true);
949}
950
951void llvm::EmitIntrinsicImpl(RecordKeeper &RK, raw_ostream &OS) {
952  IntrinsicEmitter(RK).run(OS, /*Enums=*/false);
953}
954