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