LLVM 23.0.0git
Intrinsics.cpp
Go to the documentation of this file.
1//===-- Intrinsics.cpp - Intrinsic Function Handling ------------*- C++ -*-===//
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 file implements functions required for supporting intrinsic functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Intrinsics.h"
17#include "llvm/IR/Function.h"
18#include "llvm/IR/IntrinsicsAArch64.h"
19#include "llvm/IR/IntrinsicsAMDGPU.h"
20#include "llvm/IR/IntrinsicsARM.h"
21#include "llvm/IR/IntrinsicsBPF.h"
22#include "llvm/IR/IntrinsicsHexagon.h"
23#include "llvm/IR/IntrinsicsLoongArch.h"
24#include "llvm/IR/IntrinsicsMips.h"
25#include "llvm/IR/IntrinsicsNVPTX.h"
26#include "llvm/IR/IntrinsicsPowerPC.h"
27#include "llvm/IR/IntrinsicsR600.h"
28#include "llvm/IR/IntrinsicsRISCV.h"
29#include "llvm/IR/IntrinsicsS390.h"
30#include "llvm/IR/IntrinsicsSPIRV.h"
31#include "llvm/IR/IntrinsicsVE.h"
32#include "llvm/IR/IntrinsicsX86.h"
33#include "llvm/IR/IntrinsicsXCore.h"
34#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
38
39using namespace llvm;
40
41// Forward declaration of static functions.
42static bool isSignatureValid(FunctionType *FTy,
44 unsigned NumArgs, bool IsVarArg,
45 SmallVectorImpl<Type *> &OverloadTys,
46 raw_ostream &OS);
47
48/// Table of string intrinsic names indexed by enum value.
49#define GET_INTRINSIC_NAME_TABLE
50#include "llvm/IR/IntrinsicImpl.inc"
51
53 assert(id < num_intrinsics && "Invalid intrinsic ID!");
54 return IntrinsicNameTable[IntrinsicNameOffsetTable[id]];
55}
56
58 assert(id < num_intrinsics && "Invalid intrinsic ID!");
60 "This version of getName does not support overloading");
61 return getBaseName(id);
62}
63
64/// Returns a stable mangling for the type specified for use in the name
65/// mangling scheme used by 'any' types in intrinsic signatures. The mangling
66/// of named types is simply their name. Manglings for unnamed types consist
67/// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
68/// combined with the mangling of their component types. A vararg function
69/// type will have a suffix of 'vararg'. Since function types can contain
70/// other function types, we close a function type mangling with suffix 'f'
71/// which can't be confused with it's prefix. This ensures we don't have
72/// collisions between two unrelated function types. Otherwise, you might
73/// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
74/// The HasUnnamedType boolean is set if an unnamed type was encountered,
75/// indicating that extra care must be taken to ensure a unique name.
76static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) {
77 std::string Result;
78 if (PointerType *PTyp = dyn_cast<PointerType>(Ty)) {
79 Result += "p" + utostr(PTyp->getAddressSpace());
80 } else if (ArrayType *ATyp = dyn_cast<ArrayType>(Ty)) {
81 Result += "a" + utostr(ATyp->getNumElements()) +
82 getMangledTypeStr(ATyp->getElementType(), HasUnnamedType);
83 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
84 if (!STyp->isLiteral()) {
85 Result += "s_";
86 if (STyp->hasName())
87 Result += STyp->getName();
88 else
89 HasUnnamedType = true;
90 } else {
91 Result += "sl_";
92 for (auto *Elem : STyp->elements())
93 Result += getMangledTypeStr(Elem, HasUnnamedType);
94 }
95 // Ensure nested structs are distinguishable.
96 Result += "s";
97 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
98 Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType);
99 for (size_t i = 0; i < FT->getNumParams(); i++)
100 Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType);
101 if (FT->isVarArg())
102 Result += "vararg";
103 // Ensure nested function types are distinguishable.
104 Result += "f";
105 } else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
106 ElementCount EC = VTy->getElementCount();
107 if (EC.isScalable())
108 Result += "nx";
109 Result += "v" + utostr(EC.getKnownMinValue()) +
110 getMangledTypeStr(VTy->getElementType(), HasUnnamedType);
111 } else if (TargetExtType *TETy = dyn_cast<TargetExtType>(Ty)) {
112 Result += "t";
113 Result += TETy->getName();
114 for (Type *ParamTy : TETy->type_params())
115 Result += "_" + getMangledTypeStr(ParamTy, HasUnnamedType);
116 for (unsigned IntParam : TETy->int_params())
117 Result += "_" + utostr(IntParam);
118 // Ensure nested target extension types are distinguishable.
119 Result += "t";
120 } else if (Ty) {
121 switch (Ty->getTypeID()) {
122 default:
123 llvm_unreachable("Unhandled type");
124 case Type::VoidTyID:
125 Result += "isVoid";
126 break;
128 Result += "Metadata";
129 break;
130 case Type::HalfTyID:
131 Result += "f16";
132 break;
133 case Type::BFloatTyID:
134 Result += "bf16";
135 break;
136 case Type::FloatTyID:
137 Result += "f32";
138 break;
139 case Type::DoubleTyID:
140 Result += "f64";
141 break;
143 Result += "f80";
144 break;
145 case Type::FP128TyID:
146 Result += "f128";
147 break;
149 Result += "ppcf128";
150 break;
152 Result += "x86amx";
153 break;
155 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
156 break;
157 case Type::ByteTyID:
158 Result += "b" + utostr(cast<ByteType>(Ty)->getBitWidth());
159 break;
160 }
161 }
162 return Result;
163}
164
166 ArrayRef<Type *> OverloadTys, Module *M,
167 FunctionType *FT,
168 bool EarlyModuleCheck) {
169
170 assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!");
171 assert((OverloadTys.empty() || Intrinsic::isOverloaded(Id)) &&
172 "This version of getName is for overloaded intrinsics only");
173 (void)EarlyModuleCheck;
174 assert((!EarlyModuleCheck || M ||
175 !any_of(OverloadTys, llvm::IsaPred<PointerType>)) &&
176 "Intrinsic overloading on pointer types need to provide a Module");
177 bool HasUnnamedType = false;
178 std::string Result(Intrinsic::getBaseName(Id));
179 for (Type *Ty : OverloadTys)
180 Result += "." + getMangledTypeStr(Ty, HasUnnamedType);
181 if (HasUnnamedType) {
182 assert(M && "unnamed types need a module");
183 if (!FT)
184 FT = Intrinsic::getType(M->getContext(), Id, OverloadTys);
185 else
186 assert(FT == Intrinsic::getType(M->getContext(), Id, OverloadTys) &&
187 "Provided FunctionType must match arguments");
188 return M->getUniqueIntrinsicName(Result, Id, FT);
189 }
190 return Result;
191}
192
193std::string Intrinsic::getName(ID Id, ArrayRef<Type *> OverloadTys, Module *M,
194 FunctionType *FT) {
195 assert(M && "We need to have a Module");
196 return getIntrinsicNameImpl(Id, OverloadTys, M, FT, true);
197}
198
200 ArrayRef<Type *> OverloadTys) {
201 return getIntrinsicNameImpl(Id, OverloadTys, nullptr, nullptr, false);
202}
203
204/// IIT_Info - These are enumerators that describe the entries returned by the
205/// getIntrinsicInfoTableEntries function.
206///
207/// Defined in Intrinsics.td.
209#define GET_INTRINSIC_IITINFO
210#include "llvm/IR/IntrinsicImpl.inc"
211};
212
213static_assert(IIT_Done == 0, "IIT_Done expected to be 0");
214
215static void
216DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
218 using namespace Intrinsic;
219
220 auto IsScalableVector = [&]() {
221 IIT_Info NextInfo = IIT_Info(Infos[NextElt]);
222 if (NextInfo != IIT_SCALABLE_VEC)
223 return false;
224 // Eat the IIT_SCALABLE_VEC token.
225 ++NextElt;
226 return true;
227 };
228
229 IIT_Info Info = IIT_Info(Infos[NextElt++]);
230
231 switch (Info) {
232 case IIT_Done:
233 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
234 return;
235 case IIT_VARARG:
236 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
237 return;
238 case IIT_MMX:
239 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
240 return;
241 case IIT_AMX:
242 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0));
243 return;
244 case IIT_TOKEN:
245 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
246 return;
247 case IIT_METADATA:
248 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
249 return;
250 case IIT_F16:
251 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
252 return;
253 case IIT_BF16:
254 OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
255 return;
256 case IIT_F32:
257 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
258 return;
259 case IIT_F64:
260 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
261 return;
262 case IIT_F128:
263 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
264 return;
265 case IIT_PPCF128:
266 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PPCQuad, 0));
267 return;
268 case IIT_I1:
269 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
270 return;
271 case IIT_I2:
272 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 2));
273 return;
274 case IIT_I4:
275 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 4));
276 return;
277 case IIT_AARCH64_SVCOUNT:
278 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AArch64Svcount, 0));
279 return;
280 case IIT_I8:
281 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
282 return;
283 case IIT_I16:
284 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 16));
285 return;
286 case IIT_I32:
287 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
288 return;
289 case IIT_I64:
290 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
291 return;
292 case IIT_I128:
293 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
294 return;
295 case IIT_V1:
296 OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector()));
297 DecodeIITType(NextElt, Infos, OutputTable);
298 return;
299 case IIT_V2:
300 OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector()));
301 DecodeIITType(NextElt, Infos, OutputTable);
302 return;
303 case IIT_V3:
304 OutputTable.push_back(IITDescriptor::getVector(3, IsScalableVector()));
305 DecodeIITType(NextElt, Infos, OutputTable);
306 return;
307 case IIT_V4:
308 OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector()));
309 DecodeIITType(NextElt, Infos, OutputTable);
310 return;
311 case IIT_V6:
312 OutputTable.push_back(IITDescriptor::getVector(6, IsScalableVector()));
313 DecodeIITType(NextElt, Infos, OutputTable);
314 return;
315 case IIT_V8:
316 OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector()));
317 DecodeIITType(NextElt, Infos, OutputTable);
318 return;
319 case IIT_V10:
320 OutputTable.push_back(IITDescriptor::getVector(10, IsScalableVector()));
321 DecodeIITType(NextElt, Infos, OutputTable);
322 return;
323 case IIT_V16:
324 OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector()));
325 DecodeIITType(NextElt, Infos, OutputTable);
326 return;
327 case IIT_V32:
328 OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector()));
329 DecodeIITType(NextElt, Infos, OutputTable);
330 return;
331 case IIT_V64:
332 OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector()));
333 DecodeIITType(NextElt, Infos, OutputTable);
334 return;
335 case IIT_V128:
336 OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector()));
337 DecodeIITType(NextElt, Infos, OutputTable);
338 return;
339 case IIT_V256:
340 OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector()));
341 DecodeIITType(NextElt, Infos, OutputTable);
342 return;
343 case IIT_V512:
344 OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector()));
345 DecodeIITType(NextElt, Infos, OutputTable);
346 return;
347 case IIT_V1024:
348 OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector()));
349 DecodeIITType(NextElt, Infos, OutputTable);
350 return;
351 case IIT_V2048:
352 OutputTable.push_back(IITDescriptor::getVector(2048, IsScalableVector()));
353 DecodeIITType(NextElt, Infos, OutputTable);
354 return;
355 case IIT_V4096:
356 OutputTable.push_back(IITDescriptor::getVector(4096, IsScalableVector()));
357 DecodeIITType(NextElt, Infos, OutputTable);
358 return;
359 case IIT_EXTERNREF:
360 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 10));
361 return;
362 case IIT_FUNCREF:
363 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 20));
364 return;
365 case IIT_PTR:
366 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
367 return;
368 case IIT_PTR_AS: // pointer with address space.
369 OutputTable.push_back(
370 IITDescriptor::get(IITDescriptor::Pointer, Infos[NextElt++]));
371 return;
372 case IIT_ANY: {
373 unsigned OverloadInfo = Infos[NextElt++];
374 OutputTable.push_back(
375 IITDescriptor::get(IITDescriptor::Overloaded, OverloadInfo));
376 return;
377 }
378 case IIT_EXTEND_ARG: {
379 unsigned OverloadIndex = Infos[NextElt++];
380 OutputTable.push_back(
381 IITDescriptor::get(IITDescriptor::Extend, OverloadIndex));
382 return;
383 }
384 case IIT_TRUNC_ARG: {
385 unsigned OverloadIndex = Infos[NextElt++];
386 OutputTable.push_back(
387 IITDescriptor::get(IITDescriptor::Trunc, OverloadIndex));
388 return;
389 }
390 case IIT_ONE_NTH_ELTS_VEC_ARG: {
391 unsigned short OverloadIndex = Infos[NextElt++];
392 unsigned short N = Infos[NextElt++];
393 OutputTable.push_back(IITDescriptor::get(IITDescriptor::OneNthEltsVec,
394 /*Hi=*/N, /*Lo=*/OverloadIndex));
395 return;
396 }
397 case IIT_SAME_VEC_WIDTH_ARG: {
398 unsigned OverloadIndex = Infos[NextElt++];
399 OutputTable.push_back(
400 IITDescriptor::get(IITDescriptor::SameVecWidth, OverloadIndex));
401 // IIT_SAME_VEC_WIDTH_ARG entry is followed by the element type.
402 DecodeIITType(NextElt, Infos, OutputTable);
403 return;
404 }
405 case IIT_VEC_OF_ANYPTRS_TO_ELT: {
406 unsigned short OverloadIndex = Infos[NextElt++];
407 unsigned short RefOverloadIndex = Infos[NextElt++];
408 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt,
409 /*Hi=*/RefOverloadIndex,
410 /*Lo=*/OverloadIndex));
411 return;
412 }
413 case IIT_STRUCT: {
414 unsigned StructElts = Infos[NextElt++] + 2;
415
416 OutputTable.push_back(
417 IITDescriptor::get(IITDescriptor::Struct, StructElts));
418
419 for (unsigned i = 0; i != StructElts; ++i)
420 DecodeIITType(NextElt, Infos, OutputTable);
421 return;
422 }
423 case IIT_SUBDIVIDE2_ARG: {
424 unsigned OverloadIndex = Infos[NextElt++];
425 OutputTable.push_back(
426 IITDescriptor::get(IITDescriptor::Subdivide2, OverloadIndex));
427 return;
428 }
429 case IIT_SUBDIVIDE4_ARG: {
430 unsigned OverloadIndex = Infos[NextElt++];
431 OutputTable.push_back(
432 IITDescriptor::get(IITDescriptor::Subdivide4, OverloadIndex));
433 return;
434 }
435 case IIT_VEC_ELEMENT: {
436 unsigned OverloadIndex = Infos[NextElt++];
437 OutputTable.push_back(
438 IITDescriptor::get(IITDescriptor::VecElement, OverloadIndex));
439 return;
440 }
441 case IIT_VEC_OF_BITCASTS_TO_INT: {
442 unsigned OverloadIndex = Infos[NextElt++];
443 OutputTable.push_back(
444 IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt, OverloadIndex));
445 return;
446 }
447 case IIT_SCALABLE_VEC:
448 break;
449 }
450 llvm_unreachable("unhandled");
451}
452
453#define GET_INTRINSIC_GENERATOR_GLOBAL
454#include "llvm/IR/IntrinsicImpl.inc"
455
456std::tuple<ArrayRef<Intrinsic::IITDescriptor>, unsigned, bool>
459 // Note that `FixedEncodingTy` is defined in IntrinsicImpl.inc and can be
460 // uint16_t or uint32_t based on the the value of `Use16BitFixedEncoding` in
461 // IntrinsicEmitter.cpp.
462 constexpr unsigned FixedEncodingBits = sizeof(FixedEncodingTy) * CHAR_BIT;
463 constexpr unsigned MSBPosition = FixedEncodingBits - 1;
464 // Mask with all bits 1 except the most significant bit.
465 constexpr unsigned Mask = (1U << MSBPosition) - 1;
466
467 FixedEncodingTy TableVal = IIT_Table[id - 1];
468
469 // Array to hold the inlined fixed encoding values expanded from nibbles to
470 // bytes. Its size can be be atmost FixedEncodingBits / 4 i.e., number
471 // of nibbles that can fit in `FixedEncodingTy` + 1 (the IIT_Done terminator
472 // that is not explicitly encoded). Note that if there are trailing 0 bytes
473 // in the encoding (for example, payload following one of the IIT tokens),
474 // the inlined encoding does not encode the actual size of the encoding, so
475 // we always assume its size of this maximum length possible, followed by the
476 // IIT_Done terminator token (whose value is 0).
477 unsigned char IITValues[FixedEncodingBits / 4 + 1] = {0};
478
479 ArrayRef<unsigned char> IITEntries;
480 unsigned NextElt = 0;
481 // Check to see if the intrinsic's type was inlined in the fixed encoding
482 // table.
483 if (TableVal >> MSBPosition) {
484 // This is an offset into the IIT_LongEncodingTable.
485 IITEntries = IIT_LongEncodingTable;
486
487 // Strip sentinel bit.
488 NextElt = TableVal & Mask;
489 } else {
490 // If the entry was encoded into a single word in the table itself, decode
491 // it from an array of nibbles to an array of bytes.
492 do {
493 IITValues[NextElt++] = TableVal & 0xF;
494 TableVal >>= 4;
495 } while (TableVal);
496
497 IITEntries = IITValues;
498 NextElt = 0;
499 }
500
501 // Okay, decode the table into the output vector of IITDescriptors.
502 DecodeIITType(NextElt, IITEntries, T);
503 unsigned NumArgs = 0;
504 while (IITEntries[NextElt] != IIT_Done) {
505 DecodeIITType(NextElt, IITEntries, T);
506 ++NumArgs;
507 }
508
510
511 bool IsVarArg = false;
512 if (TableRef.back().Kind == Intrinsic::IITDescriptor::VarArg) {
513 IsVarArg = true;
514 TableRef.consume_back();
515 --NumArgs;
516 }
517 return {TableRef, NumArgs, IsVarArg};
518}
519
521 ArrayRef<Type *> OverloadTys,
522 LLVMContext &Context) {
523 using namespace Intrinsic;
524
525 IITDescriptor D = Infos.consume_front();
526
527 switch (D.Kind) {
528 case IITDescriptor::Void:
529 return Type::getVoidTy(Context);
530 case IITDescriptor::MMX:
532 case IITDescriptor::AMX:
533 return Type::getX86_AMXTy(Context);
534 case IITDescriptor::Token:
535 return Type::getTokenTy(Context);
536 case IITDescriptor::Metadata:
537 return Type::getMetadataTy(Context);
538 case IITDescriptor::Half:
539 return Type::getHalfTy(Context);
540 case IITDescriptor::BFloat:
541 return Type::getBFloatTy(Context);
542 case IITDescriptor::Float:
543 return Type::getFloatTy(Context);
544 case IITDescriptor::Double:
545 return Type::getDoubleTy(Context);
546 case IITDescriptor::Quad:
547 return Type::getFP128Ty(Context);
548 case IITDescriptor::PPCQuad:
549 return Type::getPPC_FP128Ty(Context);
550 case IITDescriptor::AArch64Svcount:
551 return TargetExtType::get(Context, "aarch64.svcount");
552
553 case IITDescriptor::Integer:
554 return IntegerType::get(Context, D.IntegerWidth);
555 case IITDescriptor::Vector:
556 return VectorType::get(DecodeFixedType(Infos, OverloadTys, Context),
557 D.VectorWidth);
558 case IITDescriptor::Pointer:
559 return PointerType::get(Context, D.PointerAddressSpace);
560 case IITDescriptor::Struct: {
562 for (unsigned i = 0, e = D.StructNumElements; i != e; ++i)
563 Elts.push_back(DecodeFixedType(Infos, OverloadTys, Context));
564 return StructType::get(Context, Elts);
565 }
566 // For any overload kind or partially dependent type, substitute it with the
567 // corresponding concrete type from OverloadTys.
568 case IITDescriptor::Overloaded:
569 case IITDescriptor::VecOfAnyPtrsToElt:
570 return OverloadTys[D.getOverloadIndex()];
571 case IITDescriptor::Extend:
572 return OverloadTys[D.getOverloadIndex()]->getExtendedType();
573 case IITDescriptor::Trunc:
574 return OverloadTys[D.getOverloadIndex()]->getTruncatedType();
575 case IITDescriptor::Subdivide2:
576 case IITDescriptor::Subdivide4: {
577 Type *Ty = OverloadTys[D.getOverloadIndex()];
579 assert(VTy && "Expected overload type to be a Vector Type");
580 int SubDivs = D.Kind == IITDescriptor::Subdivide2 ? 1 : 2;
581 return VectorType::getSubdividedVectorType(VTy, SubDivs);
582 }
583 case IITDescriptor::OneNthEltsVec:
585 cast<VectorType>(OverloadTys[D.getOverloadIndex()]),
586 D.getVectorDivisor());
587 case IITDescriptor::SameVecWidth: {
588 Type *EltTy = DecodeFixedType(Infos, OverloadTys, Context);
589 Type *Ty = OverloadTys[D.getOverloadIndex()];
590 if (auto *VTy = dyn_cast<VectorType>(Ty))
591 return VectorType::get(EltTy, VTy->getElementCount());
592 return EltTy;
593 }
594 case IITDescriptor::VecElement: {
595 Type *Ty = OverloadTys[D.getOverloadIndex()];
596 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
597 return VTy->getElementType();
598 llvm_unreachable("Expected overload type to be a Vector Type");
599 }
600 case IITDescriptor::VecOfBitcastsToInt: {
601 Type *Ty = OverloadTys[D.getOverloadIndex()];
603 assert(VTy && "Expected overload type to be a Vector Type");
604 return VectorType::getInteger(VTy);
605 }
606 case IITDescriptor::VarArg:
607 // VarArg token should be consumed by `getIntrinsicInfoTableEntries`, so we
608 // should never see it here.
609 llvm_unreachable("IITDescriptor::VarArg not expected");
610 }
611 llvm_unreachable("unhandled");
612}
613
615 ArrayRef<Type *> OverloadTys) {
617 auto [TableRef, _, IsVarArg] = getIntrinsicInfoTableEntries(id, Table);
618
619 Type *ResultTy = DecodeFixedType(TableRef, OverloadTys, Context);
620
622 while (!TableRef.empty())
623 ArgTys.push_back(DecodeFixedType(TableRef, OverloadTys, Context));
624 return FunctionType::get(ResultTy, ArgTys, IsVarArg);
625}
626
628#define GET_INTRINSIC_OVERLOAD_TABLE
629#include "llvm/IR/IntrinsicImpl.inc"
630}
631
633#define GET_INTRINSIC_SCALARIZABLE_TABLE
634#include "llvm/IR/IntrinsicImpl.inc"
635}
636
638#define GET_INTRINSIC_PRETTY_PRINT_TABLE
639#include "llvm/IR/IntrinsicImpl.inc"
640}
641
642/// Table of per-target intrinsic name tables.
643#define GET_INTRINSIC_TARGET_DATA
644#include "llvm/IR/IntrinsicImpl.inc"
645
647 return IID > TargetInfos[0].Count;
648}
649
650/// Looks up Name in NameTable via binary search. NameTable must be sorted
651/// and all entries must start with "llvm.". If NameTable contains an exact
652/// match for Name or a prefix of Name followed by a dot, its index in
653/// NameTable is returned. Otherwise, -1 is returned.
655 StringRef Name, StringRef Target = "") {
656 assert(Name.starts_with("llvm.") && "Unexpected intrinsic prefix");
657 assert(Name.drop_front(5).starts_with(Target) && "Unexpected target");
658
659 // Do successive binary searches of the dotted name components. For
660 // "llvm.gc.experimental.statepoint.p1i8.p1i32", we will find the range of
661 // intrinsics starting with "llvm.gc", then "llvm.gc.experimental", then
662 // "llvm.gc.experimental.statepoint", and then we will stop as the range is
663 // size 1. During the search, we can skip the prefix that we already know is
664 // identical. By using strncmp we consider names with differing suffixes to
665 // be part of the equal range.
666 size_t CmpEnd = 4; // Skip the "llvm" component.
667 if (!Target.empty())
668 CmpEnd += 1 + Target.size(); // skip the .target component.
669
670 const unsigned *Low = NameOffsetTable.begin();
671 const unsigned *High = NameOffsetTable.end();
672 const unsigned *LastLow = Low;
673 while (CmpEnd < Name.size() && High - Low > 0) {
674 size_t CmpStart = CmpEnd;
675 CmpEnd = Name.find('.', CmpStart + 1);
676 CmpEnd = CmpEnd == StringRef::npos ? Name.size() : CmpEnd;
677 auto Cmp = [CmpStart, CmpEnd](auto LHS, auto RHS) {
678 // `equal_range` requires the comparison to work with either side being an
679 // offset or the value. Detect which kind each side is to set up the
680 // compared strings.
681 const char *LHSStr;
682 if constexpr (std::is_integral_v<decltype(LHS)>)
683 LHSStr = IntrinsicNameTable.getCString(LHS);
684 else
685 LHSStr = LHS;
686
687 const char *RHSStr;
688 if constexpr (std::is_integral_v<decltype(RHS)>)
689 RHSStr = IntrinsicNameTable.getCString(RHS);
690 else
691 RHSStr = RHS;
692
693 return strncmp(LHSStr + CmpStart, RHSStr + CmpStart, CmpEnd - CmpStart) <
694 0;
695 };
696 LastLow = Low;
697 std::tie(Low, High) = std::equal_range(Low, High, Name.data(), Cmp);
698 }
699 if (High - Low > 0)
700 LastLow = Low;
701
702 if (LastLow == NameOffsetTable.end())
703 return -1;
704 StringRef NameFound = IntrinsicNameTable[*LastLow];
705 if (Name == NameFound ||
706 (Name.starts_with(NameFound) && Name[NameFound.size()] == '.'))
707 return LastLow - NameOffsetTable.begin();
708 return -1;
709}
710
711/// Find the segment of \c IntrinsicNameOffsetTable for intrinsics with the same
712/// target as \c Name, or the generic table if \c Name is not target specific.
713///
714/// Returns the relevant slice of \c IntrinsicNameOffsetTable and the target
715/// name.
716static std::pair<ArrayRef<unsigned>, StringRef>
718 assert(Name.starts_with("llvm."));
719
720 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
721 // Drop "llvm." and take the first dotted component. That will be the target
722 // if this is target specific.
723 StringRef Target = Name.drop_front(5).split('.').first;
724 auto It = partition_point(
725 Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
726 // We've either found the target or just fall back to the generic set, which
727 // is always first.
728 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
729 return {ArrayRef(&IntrinsicNameOffsetTable[1] + TI.Offset, TI.Count),
730 TI.Name};
731}
732
733/// This does the actual lookup of an intrinsic ID which matches the given
734/// function name.
736 auto [NameOffsetTable, Target] = findTargetSubtable(Name);
737 int Idx = lookupLLVMIntrinsicByName(NameOffsetTable, Name, Target);
738 if (Idx == -1)
740
741 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
742 // an index into a sub-table.
743 int Adjust = NameOffsetTable.data() - IntrinsicNameOffsetTable;
744 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
745
746 // If the intrinsic is not overloaded, require an exact match. If it is
747 // overloaded, require either exact or prefix match.
748 const auto MatchSize = IntrinsicNameTable[NameOffsetTable[Idx]].size();
749 assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
750 bool IsExactMatch = Name.size() == MatchSize;
751 return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
753}
754
755/// This defines the "Intrinsic::getAttributes(ID id)" method.
756#define GET_INTRINSIC_ATTRIBUTES
757#include "llvm/IR/IntrinsicImpl.inc"
758
759static Function *
761 ArrayRef<Type *> OverloadTys,
762 FunctionType *FT) {
763 std::string Name = OverloadTys.empty()
764 ? Intrinsic::getName(id).str()
765 : Intrinsic::getName(id, OverloadTys, M, FT);
766 Function *F = cast<Function>(M->getOrInsertFunction(Name, FT).getCallee());
767 if (F->getFunctionType() == FT)
768 return F;
769
770 // It's possible that a declaration for this intrinsic already exists with an
771 // incorrect signature, if the signature has changed, but this particular
772 // declaration has not been auto-upgraded yet. In that case, rename the
773 // invalid declaration and insert a new one with the correct signature. The
774 // invalid declaration will get upgraded later.
775 F->setName(F->getName() + ".invalid");
776 return cast<Function>(M->getOrInsertFunction(Name, FT).getCallee());
777}
778
780 ArrayRef<Type *> OverloadTys) {
781 // There can never be multiple globals with the same name of different types,
782 // because intrinsics must be a specific type.
783 FunctionType *FT = getType(M->getContext(), id, OverloadTys);
784 return getOrInsertIntrinsicDeclarationImpl(M, id, OverloadTys, FT);
785}
786
788 ArrayRef<Type *> ArgTys) {
789 // If the intrinsic is not overloaded, use the non-overloaded version.
791 return getOrInsertDeclaration(M, id);
792
793 // Get the intrinsic signature metadata.
795 auto [TableRef, NumArgs, IsVarArg] = getIntrinsicInfoTableEntries(id, Table);
796 FunctionType *FTy = FunctionType::get(RetTy, ArgTys, IsVarArg);
797
798 // Automatically determine the overloaded types.
799 SmallVector<Type *, 4> OverloadTys;
800 [[maybe_unused]] bool IsValid = ::isSignatureValid(
801 FTy, TableRef, NumArgs, IsVarArg, OverloadTys, nulls());
802 assert(IsValid && "intrinsic signature mismatch");
803 return getOrInsertIntrinsicDeclarationImpl(M, id, OverloadTys, FTy);
804}
805
807 return M->getFunction(getName(id));
808}
809
811 ArrayRef<Type *> OverloadTys,
812 FunctionType *FT) {
813 return M->getFunction(getName(id, OverloadTys, M, FT));
814}
815
816// This defines the "Intrinsic::getIntrinsicForClangBuiltin()" method.
817#define GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN
818#include "llvm/IR/IntrinsicImpl.inc"
819
820// This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
821#define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
822#include "llvm/IR/IntrinsicImpl.inc"
823
825 switch (QID) {
826#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
827 case Intrinsic::INTRINSIC:
828#include "llvm/IR/ConstrainedOps.def"
829#undef INSTRUCTION
830 return true;
831 default:
832 return false;
833 }
834}
835
837 switch (QID) {
838#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
839 case Intrinsic::INTRINSIC: \
840 return ROUND_MODE == 1;
841#include "llvm/IR/ConstrainedOps.def"
842#undef INSTRUCTION
843 default:
844 return false;
845 }
846}
847
848// This class represents a position in the intrinsic's type signature and is
849// used to generate error messages in `matchIntrinsicType`. The printed position
850// can be of the following forms:
851//
852// return
853// return struct element 3
854// return vector element
855// return struct element 3 vector element
856// argument 3
857// argument 3 vector element
858//
859// To support deferred checks also being able to generate these error messages
860// we need to encode the position compactly so that it can be stashed into
861// DeferredIntrinsicMatchInfo below (without materializing it into a string).
862// The class below serves that purpose.
863//
864namespace {
865struct MatchPosition {
866 uint16_t IsRet : 1;
867 uint16_t Num : 15; // Argument number (when IsRet = false).
868 struct Index {
869 uint16_t IsStruct : 1; // If true, this is a struct element with element
870 // index `Num`, else its a vector element.
871 uint16_t Num : 15; // Struct element index.
872 };
873 // We expect this to be just 2 levels deep, since nested structs are not
874 // supported.
875 static constexpr unsigned INDEX_TABLE_SIZE = 2;
876 Index Indices[INDEX_TABLE_SIZE];
877 uint16_t NumIndices = 0;
878
879 void pop_index() {
880 assert(NumIndices > 0 && "cannot pop from empty indices");
881 --NumIndices;
882 }
883
884 void push_struct_element(unsigned ElementNum) {
885 assert(NumIndices < INDEX_TABLE_SIZE && "index table overflow");
886 assert(isInt<15>(ElementNum) && "Element index overflow");
887 Indices[NumIndices].IsStruct = true;
888 Indices[NumIndices++].Num = ElementNum;
889 }
890
891 void push_vector_element() {
892 assert(NumIndices < INDEX_TABLE_SIZE && "index table overflow");
893 Indices[NumIndices].IsStruct = false;
894 Indices[NumIndices++].Num = 0;
895 }
896};
897} // namespace
898
899static raw_ostream &operator<<(raw_ostream &OS, const MatchPosition &Pos) {
900 OS << "intrinsic ";
901
902 if (Pos.IsRet)
903 OS << "return";
904 else
905 OS << "argument " << Pos.Num;
906
907 for (const MatchPosition::Index &Idx :
908 ArrayRef(Pos.Indices).take_front(Pos.NumIndices)) {
909 if (Idx.IsStruct)
910 OS << " struct element " << Idx.Num;
911 else
912 OS << " vector element";
913 }
914 return OS;
915}
916
918 std::tuple<Type *, ArrayRef<Intrinsic::IITDescriptor>, MatchPosition>;
919
920static bool
922 MatchPosition Position, SmallVectorImpl<Type *> &OverloadTys,
924 bool IsDeferredCheck, raw_ostream &OS) {
925 using namespace Intrinsic;
926
927 // If we ran out of descriptors, there are too many arguments or returns.
928 if (Infos.empty()) {
929 OS << Position << " too many "
930 << (Position.IsRet ? "returns" : "arguments");
931 return true;
932 }
933
934 // Do this before slicing off the 'front' part
935 auto InfosRef = Infos;
936 auto DeferCheck = [&DeferredChecks, &InfosRef, &Position](Type *T) {
937 DeferredChecks.emplace_back(T, InfosRef, Position);
938 return false;
939 };
940
941 IITDescriptor D = Infos.consume_front();
942
943 auto PrintMsg = [&OS, &Position, Ty](bool IsValid,
944 const Twine &Expected) -> bool {
945 if (IsValid)
946 return false;
947 OS << Position << " type expected " << Expected << ", but got " << *Ty;
948 return true;
949 };
950
951 switch (D.Kind) {
952 case IITDescriptor::Void:
953 assert(Position.IsRet && Position.NumIndices == 0 &&
954 "void descriptor expected only for return type");
955 return PrintMsg(Ty->isVoidTy(), "void");
956 case IITDescriptor::MMX: {
958 return PrintMsg(VT && VT->getNumElements() == 1 &&
959 VT->getElementType()->isIntegerTy(64),
960 "x86_mmx (<1 x i64>)");
961 }
962 case IITDescriptor::AMX:
963 return PrintMsg(Ty->isX86_AMXTy(), "x86_amx");
964 case IITDescriptor::Token:
965 return PrintMsg(Ty->isTokenTy(), "token");
966 case IITDescriptor::Metadata:
967 return PrintMsg(Ty->isMetadataTy(), "metadata");
968 case IITDescriptor::Half:
969 return PrintMsg(Ty->isHalfTy(), "half");
970 case IITDescriptor::BFloat:
971 return PrintMsg(Ty->isBFloatTy(), "bfloat");
972 case IITDescriptor::Float:
973 return PrintMsg(Ty->isFloatTy(), "float");
974 case IITDescriptor::Double:
975 return PrintMsg(Ty->isDoubleTy(), "double");
976 case IITDescriptor::Quad:
977 return PrintMsg(Ty->isFP128Ty(), "fp128");
978 case IITDescriptor::PPCQuad:
979 return PrintMsg(Ty->isPPC_FP128Ty(), "ppc_fp128");
980 case IITDescriptor::Integer:
981 return PrintMsg(Ty->isIntegerTy(D.IntegerWidth),
982 "i" + Twine(D.IntegerWidth));
983 case IITDescriptor::AArch64Svcount:
984 return PrintMsg(isa<TargetExtType>(Ty) &&
985 cast<TargetExtType>(Ty)->getName() == "aarch64.svcount",
986 "aarch64.svcount");
987 case IITDescriptor::Vector: {
989 StringRef Scalable = D.VectorWidth.isScalable() ? "vscale " : "";
990 bool HasError =
991 PrintMsg(VT && VT->getElementCount() == D.VectorWidth,
992 Twine(Scalable) + "vector with " +
993 Twine(D.VectorWidth.getKnownMinValue()) + " elements");
994 if (HasError)
995 return true;
996 Position.push_vector_element();
997 return matchIntrinsicType(VT->getElementType(), Infos, Position,
998 OverloadTys, DeferredChecks, IsDeferredCheck, OS);
999 }
1000 case IITDescriptor::Pointer: {
1002 unsigned AS = D.PointerAddressSpace;
1003 bool IsValid = PT && PT->getAddressSpace() == AS;
1004 if (AS == 0)
1005 return PrintMsg(IsValid, "ptr");
1006 return PrintMsg(IsValid, "ptr addrspace(" + Twine(AS) + ")");
1007 }
1008
1009 case IITDescriptor::Struct: {
1011 unsigned EC = D.StructNumElements;
1012 bool HasError = PrintMsg(
1013 ST && ST->isLiteral() && !ST->isPacked() && ST->getNumElements() == EC,
1014 "literal non-packed struct with " + Twine(EC) + " elements");
1015 if (HasError)
1016 return true;
1017
1018 for (const auto &[Idx, ETy] : llvm::enumerate(ST->elements())) {
1019 Position.push_struct_element(Idx);
1020 if (matchIntrinsicType(ETy, Infos, Position, OverloadTys, DeferredChecks,
1021 IsDeferredCheck, OS))
1022 return true;
1023 Position.pop_index();
1024 }
1025 return false;
1026 }
1027
1028 case IITDescriptor::Overloaded:
1029 // If this is the second occurrence of an argument,
1030 // verify that the later instance matches the previous instance.
1031 if (D.getOverloadIndex() < OverloadTys.size())
1032 return Ty != OverloadTys[D.getOverloadIndex()];
1033
1034 if (D.getOverloadIndex() > OverloadTys.size() ||
1035 D.getOverloadKind() == IITDescriptor::AK_MatchType)
1036 return IsDeferredCheck || DeferCheck(Ty);
1037
1038 assert(D.getOverloadIndex() == OverloadTys.size() && !IsDeferredCheck &&
1039 "Table consistency error");
1040 OverloadTys.push_back(Ty);
1041
1042 switch (D.getOverloadKind()) {
1043 case IITDescriptor::AK_Any:
1044 return false; // Success
1045 case IITDescriptor::AK_AnyInteger:
1046 return !Ty->isIntOrIntVectorTy();
1047 case IITDescriptor::AK_AnyFloat:
1048 return !Ty->isFPOrFPVectorTy();
1049 case IITDescriptor::AK_AnyVector:
1050 return !isa<VectorType>(Ty);
1051 case IITDescriptor::AK_AnyPointer:
1052 return !isa<PointerType>(Ty);
1053 default:
1054 break;
1055 }
1056 llvm_unreachable("all argument kinds not covered");
1057
1058 case IITDescriptor::Extend: {
1059 // If this is a forward reference, defer the check for later.
1060 if (D.getOverloadIndex() >= OverloadTys.size())
1061 return IsDeferredCheck || DeferCheck(Ty);
1062
1063 Type *NewTy = OverloadTys[D.getOverloadIndex()]->getExtendedType();
1064 return Ty != NewTy;
1065 }
1066 case IITDescriptor::Trunc: {
1067 // If this is a forward reference, defer the check for later.
1068 if (D.getOverloadIndex() >= OverloadTys.size())
1069 return IsDeferredCheck || DeferCheck(Ty);
1070
1071 Type *NewTy = OverloadTys[D.getOverloadIndex()]->getTruncatedType();
1072 return Ty != NewTy;
1073 }
1074 case IITDescriptor::OneNthEltsVec: {
1075 // If this is a forward reference, defer the check for later.
1076 if (D.getOverloadIndex() >= OverloadTys.size())
1077 return IsDeferredCheck || DeferCheck(Ty);
1078 auto *VTy = dyn_cast<VectorType>(OverloadTys[D.getOverloadIndex()]);
1079 if (!VTy)
1080 return true;
1081 if (!VTy->getElementCount().isKnownMultipleOf(D.getVectorDivisor()))
1082 return true;
1083 return VectorType::getOneNthElementsVectorType(VTy, D.getVectorDivisor()) !=
1084 Ty;
1085 }
1086 case IITDescriptor::SameVecWidth: {
1087 if (D.getOverloadIndex() >= OverloadTys.size()) {
1088 // Defer check and subsequent check for the vector element type.
1089 Infos.consume_front();
1090 return IsDeferredCheck || DeferCheck(Ty);
1091 }
1092 auto *ReferenceType =
1093 dyn_cast<VectorType>(OverloadTys[D.getOverloadIndex()]);
1094 auto *ThisArgType = dyn_cast<VectorType>(Ty);
1095 // Both must be vectors of the same number of elements or neither.
1096 if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
1097 return true;
1098 Type *EltTy = Ty;
1099 if (ThisArgType) {
1100 if (ReferenceType->getElementCount() != ThisArgType->getElementCount())
1101 return true;
1102 EltTy = ThisArgType->getElementType();
1103 Position.push_vector_element();
1104 }
1105 return matchIntrinsicType(EltTy, Infos, Position, OverloadTys,
1106 DeferredChecks, IsDeferredCheck, OS);
1107 }
1108 case IITDescriptor::VecOfAnyPtrsToElt: {
1109 unsigned RefOverloadIndex = D.getRefOverloadIndex();
1110 if (RefOverloadIndex >= OverloadTys.size()) {
1111 if (IsDeferredCheck)
1112 return true;
1113 // If forward referencing, already add the pointer-vector type and
1114 // defer the checks for later.
1115 OverloadTys.push_back(Ty);
1116 return DeferCheck(Ty);
1117 }
1118
1119 if (!IsDeferredCheck) {
1120 assert(D.getOverloadIndex() == OverloadTys.size() &&
1121 "Table consistency error");
1122 OverloadTys.push_back(Ty);
1123 }
1124
1125 // Verify the overloaded type "matches" the Ref type.
1126 // i.e. Ty is a vector with the same width as Ref.
1127 // Composed of pointers to the same element type as Ref.
1128 auto *ReferenceType = dyn_cast<VectorType>(OverloadTys[RefOverloadIndex]);
1129 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1130 if (!ThisArgVecTy || !ReferenceType ||
1131 (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))
1132 return true;
1133 return !ThisArgVecTy->getElementType()->isPointerTy();
1134 }
1135 case IITDescriptor::VecElement: {
1136 if (D.getOverloadIndex() >= OverloadTys.size())
1137 return IsDeferredCheck ? true : DeferCheck(Ty);
1138 auto *ReferenceType =
1139 dyn_cast<VectorType>(OverloadTys[D.getOverloadIndex()]);
1140 return !ReferenceType || Ty != ReferenceType->getElementType();
1141 }
1142 case IITDescriptor::Subdivide2:
1143 case IITDescriptor::Subdivide4: {
1144 // If this is a forward reference, defer the check for later.
1145 if (D.getOverloadIndex() >= OverloadTys.size())
1146 return IsDeferredCheck || DeferCheck(Ty);
1147
1148 Type *NewTy = OverloadTys[D.getOverloadIndex()];
1149 if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
1150 int SubDivs = D.Kind == IITDescriptor::Subdivide2 ? 1 : 2;
1151 NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
1152 return Ty != NewTy;
1153 }
1154 return true;
1155 }
1156 case IITDescriptor::VecOfBitcastsToInt: {
1157 if (D.getOverloadIndex() >= OverloadTys.size())
1158 return IsDeferredCheck || DeferCheck(Ty);
1159 auto *ReferenceType =
1160 dyn_cast<VectorType>(OverloadTys[D.getOverloadIndex()]);
1161 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1162 if (!ThisArgVecTy || !ReferenceType)
1163 return true;
1164 return ThisArgVecTy != VectorType::getInteger(ReferenceType);
1165 }
1166 case IITDescriptor::VarArg:
1167 // VarArg token should be consumed by `getIntrinsicInfoTableEntries`, so we
1168 // should never see it here.
1169 llvm_unreachable("IITDescriptor::VarArg not expected");
1170 }
1171 llvm_unreachable("unhandled");
1172}
1173
1174/// Return true if the function type \p FTy is a valid type signature for the
1175/// type constraints specified in the .td file, represented by \p Infos and
1176/// \p IsVarArg. The overloaded types for the intrinsic are pushed to the
1177/// \p OverloadTys vector.
1178///
1179/// If the type is not valid, returns false and prints an error message to
1180/// \p OS.
1183 unsigned NumArgs, bool IsVarArg,
1184 SmallVectorImpl<Type *> &OverloadTys,
1185 raw_ostream &OS) {
1187
1188 assert(!Infos.empty() && "Table consistency error");
1189
1190 MatchPosition Pos;
1191 Pos.IsRet = true;
1192 Pos.Num = 0;
1193
1194 // Temporary fix to print an error message if `matchIntrinsicType` fails but
1195 // does not print an error message. This will be removed once all failing
1196 // cases in `matchIntrinsicType` start generating error messages.
1197 uint64_t OSPos = OS.tell();
1198 auto PrintMsg = [OSPos, &OS](StringRef Msg) {
1199 if (OS.tell() != OSPos)
1200 return;
1201 OS << Msg;
1202 };
1203
1204 if (matchIntrinsicType(FTy->getReturnType(), Infos, Pos, OverloadTys,
1205 DeferredChecks, false, OS)) {
1206 PrintMsg("intrinsic has incorrect return type!");
1207 return false;
1208 }
1209 unsigned NumDeferredReturnChecks = DeferredChecks.size();
1210
1211 if (FTy->getNumParams() != NumArgs) {
1212 OS << "intrinsic has incorrect number of args. Expected " << NumArgs
1213 << ", but got " << FTy->getNumParams();
1214 return false;
1215 }
1216
1217 Pos.IsRet = false;
1218 for (const auto &[Idx, Ty] : llvm::enumerate(FTy->params())) {
1219 Pos.Num = Idx;
1220 if (matchIntrinsicType(Ty, Infos, Pos, OverloadTys, DeferredChecks, false,
1221 OS)) {
1222 PrintMsg("intrinsic has incorrect argument type!");
1223 return false;
1224 }
1225 }
1226
1227 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
1228 auto &[DefTy, DefInfos, DefPosition] = DeferredChecks[I];
1229 if (!matchIntrinsicType(DefTy, DefInfos, DefPosition, OverloadTys,
1230 DeferredChecks, true, OS))
1231 continue;
1232 if (I < NumDeferredReturnChecks)
1233 PrintMsg("intrinsic has incorrect return type!");
1234 else
1235 PrintMsg("intrinsic has incorrect argument type!");
1236 return false;
1237 }
1238
1239 if (!Infos.empty()) {
1240 OS << "intrinsic has too few arguments!";
1241 return false;
1242 }
1243
1244 if (FTy->isVarArg() != IsVarArg) {
1245 if (IsVarArg)
1246 OS << "intrinsic was not defined with variable arguments!";
1247 else
1248 OS << "intrinsic was defined with variable arguments!";
1249 return false;
1250 }
1251
1252 return true;
1253}
1254
1256 using namespace Intrinsic;
1259 return !Table.empty() && Table[0].Kind == IITDescriptor::Struct;
1260}
1261
1263 SmallVectorImpl<Type *> &OverloadTys,
1264 raw_ostream &OS) {
1265 if (!ID)
1266 return false;
1267
1269 auto [TableRef, NumArgs, IsVarArg] = getIntrinsicInfoTableEntries(ID, Table);
1270
1271 return ::isSignatureValid(FT, TableRef, NumArgs, IsVarArg, OverloadTys, OS);
1272}
1273
1275 SmallVectorImpl<Type *> &OverloadTys,
1276 raw_ostream &OS) {
1277 return isSignatureValid(F->getIntrinsicID(), F->getFunctionType(),
1278 OverloadTys, OS);
1279}
1280
1282 SmallVector<Type *, 4> OverloadTys;
1283 if (!isSignatureValid(F, OverloadTys))
1284 return std::nullopt;
1285
1286 Intrinsic::ID ID = F->getIntrinsicID();
1287 StringRef Name = F->getName();
1288 std::string WantedName =
1289 Intrinsic::getName(ID, OverloadTys, F->getParent(), F->getFunctionType());
1290 if (Name == WantedName)
1291 return std::nullopt;
1292
1293 Function *NewDecl = [&] {
1294 if (auto *ExistingGV = F->getParent()->getNamedValue(WantedName)) {
1295 if (auto *ExistingF = dyn_cast<Function>(ExistingGV))
1296 if (ExistingF->getFunctionType() == F->getFunctionType())
1297 return ExistingF;
1298
1299 // The name already exists, but is not a function or has the wrong
1300 // prototype. Make place for the new one by renaming the old version.
1301 // Either this old version will be removed later on or the module is
1302 // invalid and we'll get an error.
1303 ExistingGV->setName(WantedName + ".renamed");
1304 }
1305 return Intrinsic::getOrInsertDeclaration(F->getParent(), ID, OverloadTys);
1306 }();
1307
1308 NewDecl->setCallingConv(F->getCallingConv());
1309 assert(NewDecl->getFunctionType() == F->getFunctionType() &&
1310 "Shouldn't change the signature");
1311 return NewDecl;
1312}
1313
1317
1319 {Intrinsic::vector_interleave2, Intrinsic::vector_deinterleave2},
1320 {Intrinsic::vector_interleave3, Intrinsic::vector_deinterleave3},
1321 {Intrinsic::vector_interleave4, Intrinsic::vector_deinterleave4},
1322 {Intrinsic::vector_interleave5, Intrinsic::vector_deinterleave5},
1323 {Intrinsic::vector_interleave6, Intrinsic::vector_deinterleave6},
1324 {Intrinsic::vector_interleave7, Intrinsic::vector_deinterleave7},
1325 {Intrinsic::vector_interleave8, Intrinsic::vector_deinterleave8},
1326};
1327
1329 assert(Factor >= 2 && Factor <= 8 && "Unexpected factor");
1330 return InterleaveIntrinsics[Factor - 2].Interleave;
1331}
1332
1334 assert(Factor >= 2 && Factor <= 8 && "Unexpected factor");
1335 return InterleaveIntrinsics[Factor - 2].Deinterleave;
1336}
1337
1338#define GET_INTRINSIC_PRETTY_PRINT_ARGUMENTS
1339#include "llvm/IR/IntrinsicImpl.inc"
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ArrayRef< TableEntry > TableRef
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define _
Module.h This file contains the declarations for the Module class.
static bool matchIntrinsicType(Type *Ty, ArrayRef< Intrinsic::IITDescriptor > &Infos, MatchPosition Position, SmallVectorImpl< Type * > &OverloadTys, SmallVectorImpl< DeferredIntrinsicMatchInfo > &DeferredChecks, bool IsDeferredCheck, raw_ostream &OS)
static bool isSignatureValid(FunctionType *FTy, ArrayRef< Intrinsic::IITDescriptor > &Infos, unsigned NumArgs, bool IsVarArg, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS)
Return true if the function type FTy is a valid type signature for the type constraints specified in ...
static InterleaveIntrinsic InterleaveIntrinsics[]
std::tuple< Type *, ArrayRef< Intrinsic::IITDescriptor >, MatchPosition > DeferredIntrinsicMatchInfo
static std::pair< ArrayRef< unsigned >, StringRef > findTargetSubtable(StringRef Name)
Find the segment of IntrinsicNameOffsetTable for intrinsics with the same target as Name,...
static Function * getOrInsertIntrinsicDeclarationImpl(Module *M, Intrinsic::ID id, ArrayRef< Type * > OverloadTys, FunctionType *FT)
static void DecodeIITType(unsigned &NextElt, ArrayRef< unsigned char > Infos, SmallVectorImpl< Intrinsic::IITDescriptor > &OutputTable)
static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef< Type * > OverloadTys, Module *M, FunctionType *FT, bool EarlyModuleCheck)
IIT_Info
IIT_Info - These are enumerators that describe the entries returned by the getIntrinsicInfoTableEntri...
static Type * DecodeFixedType(ArrayRef< Intrinsic::IITDescriptor > &Infos, ArrayRef< Type * > OverloadTys, LLVMContext &Context)
static int lookupLLVMIntrinsicByName(ArrayRef< unsigned > NameOffsetTable, StringRef Name, StringRef Target="")
Looks up Name in NameTable via binary search.
static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType)
Returns a stable mangling for the type specified for use in the name mangling scheme used by 'any' ty...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t High
This file contains the definitions of the enumerations and flags associated with NVVM Intrinsics,...
static StringRef getName(Value *V)
This file contains some functions that are useful when dealing with strings.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
Definition ArrayRef.h:156
Tagged union holding either a T or a Error.
Definition Error.h:485
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:873
Class to represent function types.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:211
const Function & getFunction() const
Definition Function.h:166
void setCallingConv(CallingConv::ID CC)
Definition Function.h:276
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:354
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:483
Class to represent target extensions types, which are generally unintrospectable from target-independ...
static LLVM_ABI TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters.
Definition Type.cpp:978
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getX86_AMXTy(LLVMContext &C)
Definition Type.cpp:297
static LLVM_ABI Type * getMetadataTy(LLVMContext &C)
Definition Type.cpp:292
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:293
static LLVM_ABI Type * getPPC_FP128Ty(LLVMContext &C)
Definition Type.cpp:296
static LLVM_ABI Type * getFP128Ty(LLVMContext &C)
Definition Type.cpp:295
@ X86_AMXTyID
AMX vectors (8192 bits, X86 specific)
Definition Type.h:67
@ HalfTyID
16-bit floating point type
Definition Type.h:57
@ VoidTyID
type with no size
Definition Type.h:64
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:71
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition Type.h:58
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
@ X86_FP80TyID
80-bit floating point type (X87)
Definition Type.h:61
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition Type.h:63
@ MetadataTyID
Metadata.
Definition Type.h:66
@ ByteTyID
Arbitrary bit width bytes.
Definition Type.h:72
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:62
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:286
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:291
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:290
static LLVM_ABI Type * getBFloatTy(LLVMContext &C)
Definition Type.cpp:289
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:288
static VectorType * getOneNthElementsVectorType(VectorType *VTy, unsigned Denominator)
static VectorType * getSubdividedVectorType(VectorType *VTy, int NumSubdivs)
static VectorType * getInteger(VectorType *VTy)
This static method gets a VectorType with the same number of elements as the input type,...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
uint64_t tell() const
tell - Return the current offset with the file.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI std::optional< Function * > remangleIntrinsicFunction(Function *F)
LLVM_ABI bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics" that take r...
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI bool isConstrainedFPIntrinsic(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics".
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool hasPrettyPrintedArgs(ID id)
Returns true if the intrinsic has pretty printed immediate arguments.
LLVM_ABI std::tuple< ArrayRef< IITDescriptor >, unsigned, bool > getIntrinsicInfoTableEntries(ID id, SmallVectorImpl< IITDescriptor > &T)
Fill the IIT table descriptor for the intrinsic id into an array of IITDescriptors.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
LLVM_ABI Intrinsic::ID getInterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.interleaveN intrinsic for factor N.
LLVM_ABI bool isOverloaded(ID id)
Returns true if the intrinsic can be overloaded.
LLVM_ABI FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > OverloadTys={})
Return the function type for an intrinsic.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
LLVM_ABI bool hasStructReturnType(ID id)
Returns true if id has a struct return type.
LLVM_ABI bool isTriviallyScalarizable(ID id)
Returns true if the intrinsic is trivially scalarizable.
LLVM_ABI bool isTargetIntrinsic(ID IID)
isTargetIntrinsic - Returns true if IID is an intrinsic specific to a certain target.
LLVM_ABI std::string getNameNoUnnamedTypes(ID Id, ArrayRef< Type * > OverloadTys)
Return the LLVM name for an intrinsic.
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2553
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2128
std::string utostr(uint64_t X, bool isNeg=false)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1745
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
#define N
Intrinsic::ID Interleave
Intrinsic::ID Deinterleave