LLVM 24.0.0git
IRBuilder.cpp
Go to the documentation of this file.
1//===- IRBuilder.cpp - Builder for LLVM Instrs ----------------------------===//
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 the IRBuilder class, which is used as a convenient way
10// to create LLVM instructions with a consistent and simplified interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/IR/IRBuilder.h"
15#include "llvm/ADT/ArrayRef.h"
17#include "llvm/IR/Constant.h"
18#include "llvm/IR/Constants.h"
20#include "llvm/IR/Function.h"
22#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Intrinsics.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/NoFolder.h"
29#include "llvm/IR/Operator.h"
31#include "llvm/IR/Statepoint.h"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Value.h"
35#include <cassert>
36#include <cstdint>
37#include <optional>
38#include <vector>
39
40using namespace llvm;
41
42/// CreateGlobalString - Make a new global variable with an initializer that
43/// has array of i8 type filled in with the nul terminated string value
44/// specified. If Name is specified, it is the name of the global variable
45/// created.
47 const Twine &Name,
48 unsigned AddressSpace,
49 Module *M, bool AddNull) {
50 Constant *StrConstant = ConstantDataArray::getString(Context, Str, AddNull);
51 if (!M)
52 M = getModule();
53 auto *GV = new GlobalVariable(
54 *M, StrConstant->getType(), true, GlobalValue::PrivateLinkage,
55 StrConstant, Name, nullptr, GlobalVariable::NotThreadLocal, AddressSpace);
56 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
57 GV->setAlignment(M->getDataLayout().getPrefTypeAlign(getInt8Ty()));
58 return GV;
59}
60
63 assert(BB && BB->getParent() && "No current function!");
64 return BB->getParent()->getReturnType();
65}
66
69 // We prefer to set our current debug location if any has been set, but if
70 // our debug location is empty and I has a valid location, we shouldn't
71 // overwrite it.
72 I->setDebugLoc(StoredDL.orElse(I->getDebugLoc()));
73}
74
76 Type *SrcTy = V->getType();
77 if (SrcTy == DestTy)
78 return V;
79
80 if (SrcTy->isAggregateType()) {
81 unsigned NumElements;
82 if (SrcTy->isStructTy()) {
83 assert(DestTy->isStructTy() && "Expected StructType");
84 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements() &&
85 "Expected StructTypes with equal number of elements");
86 NumElements = SrcTy->getStructNumElements();
87 } else {
88 assert(SrcTy->isArrayTy() && DestTy->isArrayTy() && "Expected ArrayType");
89 assert(SrcTy->getArrayNumElements() == DestTy->getArrayNumElements() &&
90 "Expected ArrayTypes with equal number of elements");
91 NumElements = SrcTy->getArrayNumElements();
92 }
93
94 Value *Result = PoisonValue::get(DestTy);
95 for (unsigned I = 0; I < NumElements; ++I) {
96 Type *ElementTy = SrcTy->isStructTy() ? DestTy->getStructElementType(I)
97 : DestTy->getArrayElementType();
98 Value *Element =
100
101 Result = CreateInsertValue(Result, Element, ArrayRef(I));
102 }
103 return Result;
104 }
105
106 return CreateBitOrPointerCast(V, DestTy);
107}
108
110 Value *V, Type *NewTy) {
111 Type *OldTy = V->getType();
112
113 if (OldTy == NewTy)
114 return V;
115
116 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
117 "Integer types must be the exact same to convert.");
118
119 // A variant of bitcast that supports a mixture of fixed and scalable types
120 // that are know to have the same size.
121 auto CreateBitCastLike = [this](Value *In, Type *Ty) -> Value * {
122 Type *InTy = In->getType();
123 if (InTy == Ty)
124 return In;
125
127 // For vscale_range(2) expand <4 x i32> to <vscale x 4 x i16> -->
128 // <4 x i32> to <vscale x 2 x i32> to <vscale x 4 x i16>
130 return CreateBitCast(
131 CreateInsertVector(VTy, PoisonValue::get(VTy), In, getInt64(0)), Ty);
132 }
133
135 // For vscale_range(2) expand <vscale x 4 x i16> to <4 x i32> -->
136 // <vscale x 4 x i16> to <vscale x 2 x i32> to <4 x i32>
138 return CreateExtractVector(Ty, CreateBitCast(In, VTy), getInt64(0));
139 }
140
141 return CreateBitCast(In, Ty);
142 };
143
144 // See if we need inttoptr for this type pair. May require additional bitcast.
145 bool OldIsIntOrFP = OldTy->isIntOrIntVectorTy() || OldTy->isFPOrFPVectorTy();
146 if (OldIsIntOrFP && NewTy->isPtrOrPtrVectorTy()) {
147 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
148 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
149 // Expand <4 x i32> to <2 x i8*> --> <4 x i32> to <2 x i64> to <2 x i8*>
150 // Expand <2 x float> to i8* --> <2 x float> to i64 to i8*
151 // Directly handle i64 to i8*
152 return CreateIntToPtr(CreateBitCastLike(V, DL.getIntPtrType(NewTy)), NewTy);
153 }
154
155 // See if we need ptrtoint for this type pair. May require additional bitcast.
156 bool NewIsIntOrFP = NewTy->isIntOrIntVectorTy() || NewTy->isFPOrFPVectorTy();
157 if (OldTy->isPtrOrPtrVectorTy() && NewIsIntOrFP) {
158 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
159 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
160 // Expand <2 x i8*> to <4 x i32> --> <2 x i8*> to <2 x i64> to <4 x i32>
161 // Expand i8* to <2 x float> --> i8* to i64 to <2 x float>
162 // Expand i8* to i64 --> i8* to i64 to i64
163 return CreateBitCastLike(CreatePtrToInt(V, DL.getIntPtrType(OldTy)), NewTy);
164 }
165
166 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
167 unsigned OldAS = OldTy->getPointerAddressSpace();
168 unsigned NewAS = NewTy->getPointerAddressSpace();
169 // To convert pointers with different address spaces (they are already
170 // checked convertible, i.e. they have the same pointer size), so far we
171 // cannot use `bitcast` (which has restrict on the same address space) or
172 // `addrspacecast` (which is not always no-op casting). Instead, use a pair
173 // of no-op `ptrtoint`/`inttoptr` casts through an integer with the same bit
174 // size.
175 if (OldAS != NewAS) {
176 return CreateIntToPtr(
177 CreateBitCastLike(CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
178 DL.getIntPtrType(NewTy)),
179 NewTy);
180 }
181 }
182
183 return CreateBitCastLike(V, NewTy);
184}
185
186CallInst *
187IRBuilderBase::createCallHelper(Function *Callee, ArrayRef<Value *> Ops,
188 const Twine &Name, FMFSource FMFSource,
189 ArrayRef<OperandBundleDef> OpBundles) {
190 CallInst *CI = CreateCall(Callee, Ops, OpBundles, Name);
191 if (isa<FPMathOperator>(CI))
193 return CI;
194}
195
197 Value *VScale = B.CreateVScale(Ty);
198 if (Scale == 1)
199 return VScale;
200
201 return B.CreateNUWMul(VScale, ConstantInt::get(Ty, Scale));
202}
203
205 if (EC.isFixed() || EC.isZero())
206 return ConstantInt::get(Ty, EC.getKnownMinValue());
207
208 return CreateVScaleMultiple(*this, Ty, EC.getKnownMinValue());
209}
210
212 if (Size.isFixed() || Size.isZero())
213 return ConstantInt::get(Ty, Size.getKnownMinValue());
214
215 return CreateVScaleMultiple(*this, Ty, Size.getKnownMinValue());
216}
217
219 const DataLayout &DL = getDataLayout();
220 TypeSize ElemSize = AI->getAllocationBaseSize(DL);
221 Value *Size = CreateTypeSize(DestTy, ElemSize);
222 if (AI->isArrayAllocation())
224 return Size;
225}
226
228 Type *STy = DstType->getScalarType();
229 if (isa<ScalableVectorType>(DstType)) {
230 Type *StepVecType = DstType;
231 // TODO: We expect this special case (element type < 8 bits) to be
232 // temporary - once the intrinsic properly supports < 8 bits this code
233 // can be removed.
234 if (STy->getScalarSizeInBits() < 8)
235 StepVecType =
237 Value *Res = CreateIntrinsic(Intrinsic::stepvector, {StepVecType}, {},
238 nullptr, Name);
239 if (StepVecType != DstType)
240 Res = CreateTrunc(Res, DstType);
241 return Res;
242 }
243
244 unsigned NumEls = cast<FixedVectorType>(DstType)->getNumElements();
245
246 // Create a vector of consecutive numbers from zero to VF.
247 // It's okay if the values wrap around.
249 for (unsigned i = 0; i < NumEls; ++i)
250 Indices.push_back(
251 ConstantInt::get(STy, i, /*IsSigned=*/false, /*ImplicitTrunc=*/true));
252
253 // Add the consecutive indices to the vector value.
254 return ConstantVector::get(Indices);
255}
256
258 MaybeAlign Align, bool isVolatile,
259 const AAMDNodes &AAInfo) {
260 Value *Ops[] = {Ptr, Val, Size, getInt1(isVolatile)};
261 Type *Tys[] = {Ptr->getType(), Size->getType()};
262
263 auto *CI = cast<MemSetInst>(
264 CreateIntrinsicWithoutFolding(Intrinsic::memset, Tys, Ops));
265
266 if (Align)
267 CI->setDestAlignment(*Align);
268 CI->setAAMetadata(AAInfo);
269 return CI;
270}
271
273 Value *Val, Value *Size,
274 bool IsVolatile,
275 const AAMDNodes &AAInfo) {
276 Value *Ops[] = {Dst, Val, Size, getInt1(IsVolatile)};
277 Type *Tys[] = {Dst->getType(), Size->getType()};
278
279 auto *CI = cast<MemSetInst>(
280 CreateIntrinsicWithoutFolding(Intrinsic::memset_inline, Tys, Ops));
281
282 if (DstAlign)
283 CI->setDestAlignment(*DstAlign);
284 CI->setAAMetadata(AAInfo);
285 return CI;
286}
287
289 Value *Ptr, Value *Val, Value *Size, Align Alignment, uint32_t ElementSize,
290 const AAMDNodes &AAInfo) {
291
292 Value *Ops[] = {Ptr, Val, Size, getInt32(ElementSize)};
293 Type *Tys[] = {Ptr->getType(), Size->getType()};
294
296 Intrinsic::memset_element_unordered_atomic, Tys, Ops));
297 CI->setDestAlignment(Alignment);
298 CI->setAAMetadata(AAInfo);
299 return CI;
300}
301
303 MaybeAlign DstAlign, Value *Src,
304 MaybeAlign SrcAlign, Value *Size,
305 bool isVolatile,
306 const AAMDNodes &AAInfo) {
307 assert((IntrID == Intrinsic::memcpy || IntrID == Intrinsic::memcpy_inline ||
308 IntrID == Intrinsic::memmove) &&
309 "Unexpected intrinsic ID");
310 Value *Ops[] = {Dst, Src, Size, getInt1(isVolatile)};
311 Type *Tys[] = {Dst->getType(), Src->getType(), Size->getType()};
312
313 auto *MCI =
315
316 if (DstAlign)
317 MCI->setDestAlignment(*DstAlign);
318 if (SrcAlign)
319 MCI->setSourceAlignment(*SrcAlign);
320 MCI->setAAMetadata(AAInfo);
321 return MCI;
322}
323
325 Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
326 uint32_t ElementSize, const AAMDNodes &AAInfo) {
327 assert(DstAlign >= ElementSize &&
328 "Pointer alignment must be at least element size");
329 assert(SrcAlign >= ElementSize &&
330 "Pointer alignment must be at least element size");
331 Value *Ops[] = {Dst, Src, Size, getInt32(ElementSize)};
332 Type *Tys[] = {Dst->getType(), Src->getType(), Size->getType()};
333
335 Intrinsic::memcpy_element_unordered_atomic, Tys, Ops));
336
337 // Set the alignment of the pointer args.
338 AMCI->setDestAlignment(DstAlign);
339 AMCI->setSourceAlignment(SrcAlign);
340 AMCI->setAAMetadata(AAInfo);
341 return AMCI;
342}
343
344/// isConstantOne - Return true only if val is constant int 1
345static bool isConstantOne(const Value *Val) {
346 assert(Val && "isConstantOne does not work with nullptr Val");
347 const ConstantInt *CVal = dyn_cast<ConstantInt>(Val);
348 return CVal && CVal->isOne();
349}
350
352 Value *ArraySize,
354 Function *MallocF, const Twine &Name) {
355 // malloc(type) becomes:
356 // i8* malloc(typeSize)
357 // malloc(type, arraySize) becomes:
358 // i8* malloc(typeSize*arraySize)
359 if (!ArraySize)
360 ArraySize = ConstantInt::get(IntPtrTy, 1);
361 else if (ArraySize->getType() != IntPtrTy)
362 ArraySize = CreateIntCast(ArraySize, IntPtrTy, false);
363
364 if (!isConstantOne(ArraySize)) {
365 if (isConstantOne(AllocSize)) {
366 AllocSize = ArraySize; // Operand * 1 = Operand
367 } else {
368 // Multiply type size by the array size...
369 AllocSize = CreateMul(ArraySize, AllocSize, "mallocsize");
370 }
371 }
372
373 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
374 // Create the call to Malloc.
375 Module *M = getModule();
377 FunctionCallee MallocFunc = MallocF;
378 if (!MallocFunc)
379 // prototype malloc as "void *malloc(size_t)"
380 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
381 CallInst *MCall = CreateCall(MallocFunc, AllocSize, OpB, Name);
382
383 MCall->setTailCall();
384 if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) {
385 MCall->setCallingConv(F->getCallingConv());
386 F->setReturnDoesNotAlias();
387 }
388
389 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
390
391 return MCall;
392}
393
395 Value *ArraySize, Function *MallocF,
396 const Twine &Name) {
397
398 return CreateMalloc(IntPtrTy, AllocSize, ArraySize, {}, MallocF, Name);
399}
400
401/// CreateFree - Generate the IR for a call to the builtin free function.
404 assert(Source->getType()->isPointerTy() &&
405 "Can not free something of nonpointer type!");
406
407 Module *M = getModule();
408
409 Type *VoidTy = Type::getVoidTy(M->getContext());
410 Type *VoidPtrTy = PointerType::getUnqual(M->getContext());
411 // prototype free as "void free(void*)"
412 FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, VoidPtrTy);
413 CallInst *Result = CreateCall(FreeFunc, Source, Bundles, "");
414 Result->setTailCall();
415 if (Function *F = dyn_cast<Function>(FreeFunc.getCallee()))
416 Result->setCallingConv(F->getCallingConv());
417
418 return Result;
419}
420
422 Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
423 uint32_t ElementSize, const AAMDNodes &AAInfo) {
424 assert(DstAlign >= ElementSize &&
425 "Pointer alignment must be at least element size");
426 assert(SrcAlign >= ElementSize &&
427 "Pointer alignment must be at least element size");
428 Value *Ops[] = {Dst, Src, Size, getInt32(ElementSize)};
429 Type *Tys[] = {Dst->getType(), Src->getType(), Size->getType()};
430
432 Intrinsic::memmove_element_unordered_atomic, Tys, Ops);
433
434 // Set the alignment of the pointer args.
435 CI->addParamAttr(0, Attribute::getWithAlignment(CI->getContext(), DstAlign));
436 CI->addParamAttr(1, Attribute::getWithAlignment(CI->getContext(), SrcAlign));
437 CI->setAAMetadata(AAInfo);
438 return CI;
439}
440
441Value *IRBuilderBase::getReductionIntrinsic(Intrinsic::ID ID, Value *Src) {
442 Value *Ops[] = {Src};
443 Type *Tys[] = { Src->getType() };
444 return CreateIntrinsic(ID, Tys, Ops);
445}
446
448 Value *Ops[] = {Acc, Src};
449 return CreateIntrinsic(Intrinsic::vector_reduce_fadd, {Src->getType()}, Ops);
450}
451
453 Value *Ops[] = {Acc, Src};
454 return CreateIntrinsic(Intrinsic::vector_reduce_fmul, {Src->getType()}, Ops);
455}
456
458 return getReductionIntrinsic(Intrinsic::vector_reduce_add, Src);
459}
460
462 return getReductionIntrinsic(Intrinsic::vector_reduce_mul, Src);
463}
464
466 return getReductionIntrinsic(Intrinsic::vector_reduce_and, Src);
467}
468
470 return getReductionIntrinsic(Intrinsic::vector_reduce_or, Src);
471}
472
474 return getReductionIntrinsic(Intrinsic::vector_reduce_xor, Src);
475}
476
478 auto ID =
479 IsSigned ? Intrinsic::vector_reduce_smax : Intrinsic::vector_reduce_umax;
480 return getReductionIntrinsic(ID, Src);
481}
482
484 auto ID =
485 IsSigned ? Intrinsic::vector_reduce_smin : Intrinsic::vector_reduce_umin;
486 return getReductionIntrinsic(ID, Src);
487}
488
490 return getReductionIntrinsic(Intrinsic::vector_reduce_fmax, Src);
491}
492
494 return getReductionIntrinsic(Intrinsic::vector_reduce_fmin, Src);
495}
496
498 return getReductionIntrinsic(Intrinsic::vector_reduce_fmaximum, Src);
499}
500
502 return getReductionIntrinsic(Intrinsic::vector_reduce_fminimum, Src);
503}
504
506 return getReductionIntrinsic(Intrinsic::vector_reduce_fmaximumnum, Src);
507}
508
510 return getReductionIntrinsic(Intrinsic::vector_reduce_fminimumnum, Src);
511}
512
515 "lifetime.start only applies to pointers.");
516 return CreateIntrinsicWithoutFolding(Intrinsic::lifetime_start,
517 {Ptr->getType()}, {Ptr});
518}
519
522 "lifetime.end only applies to pointers.");
523 return CreateIntrinsicWithoutFolding(Intrinsic::lifetime_end,
524 {Ptr->getType()}, {Ptr});
525}
526
528
530 "invariant.start only applies to pointers.");
531 if (!Size)
532 Size = getInt64(-1);
533 else
534 assert(Size->getType() == getInt64Ty() &&
535 "invariant.start requires the size to be an i64");
536
537 Value *Ops[] = {Size, Ptr};
538 // Fill in the single overloaded type: memory object type.
539 Type *ObjectPtr[1] = {Ptr->getType()};
540 return CreateIntrinsicWithoutFolding(Intrinsic::invariant_start, ObjectPtr,
541 Ops);
542}
543
545 if (auto *V = dyn_cast<GlobalVariable>(Ptr))
546 return V->getAlign();
547 if (auto *A = dyn_cast<GlobalAlias>(Ptr))
548 return getAlign(A->getAliaseeObject());
549 return {};
550}
551
553 assert(isa<GlobalValue>(Ptr) && cast<GlobalValue>(Ptr)->isThreadLocal() &&
554 "threadlocal_address only applies to thread local variables.");
556 llvm::Intrinsic::threadlocal_address, {Ptr->getType()}, {Ptr});
557 if (MaybeAlign A = getAlign(Ptr)) {
560 }
561 return CI;
562}
563
565 assert(Cond->getType() == getInt1Ty() &&
566 "an assumption condition must be of type i1");
567 return CreateIntrinsicWithoutFolding(Intrinsic::assume, /*OverloadTypes=*/{},
568 {Cond});
569}
570
571CallInst *
575 Intrinsic::assume, /*OverloadTypes=*/{}, Args,
576 /*FMFSource=*/nullptr, /*Name=*/"", OpBundles);
577}
578
581 Intrinsic::experimental_noalias_scope_decl, {}, {Scope});
582}
583
584/// Create a call to a Masked Load intrinsic.
585/// \p Ty - vector type to load
586/// \p Ptr - base pointer for the load
587/// \p Alignment - alignment of the source location
588/// \p Mask - vector of booleans which indicates what vector lanes should
589/// be accessed in memory
590/// \p PassThru - pass-through value that is used to fill the masked-off lanes
591/// of the result
592/// \p Name - name of the result variable
594 Value *Mask, Value *PassThru,
595 const Twine &Name) {
596 auto *PtrTy = cast<PointerType>(Ptr->getType());
597 assert(Ty->isVectorTy() && "Type should be vector");
598 assert(Mask && "Mask should not be all-ones (null)");
599 if (!PassThru)
600 PassThru = PoisonValue::get(Ty);
601 Type *OverloadedTypes[] = { Ty, PtrTy };
602 Value *Ops[] = {Ptr, Mask, PassThru};
603 CallInst *CI =
604 CreateMaskedIntrinsic(Intrinsic::masked_load, Ops, OverloadedTypes, Name);
605 CI->addParamAttr(0, Attribute::getWithAlignment(CI->getContext(), Alignment));
606 return CI;
607}
608
609/// Create a call to a Masked Store intrinsic.
610/// \p Val - data to be stored,
611/// \p Ptr - base pointer for the store
612/// \p Alignment - alignment of the destination location
613/// \p Mask - vector of booleans which indicates what vector lanes should
614/// be accessed in memory
616 Align Alignment, Value *Mask) {
617 auto *PtrTy = cast<PointerType>(Ptr->getType());
618 Type *DataTy = Val->getType();
619 assert(DataTy->isVectorTy() && "Val should be a vector");
620 assert(Mask && "Mask should not be all-ones (null)");
621 Type *OverloadedTypes[] = { DataTy, PtrTy };
622 Value *Ops[] = {Val, Ptr, Mask};
623 CallInst *CI =
624 CreateMaskedIntrinsic(Intrinsic::masked_store, Ops, OverloadedTypes);
625 CI->addParamAttr(1, Attribute::getWithAlignment(CI->getContext(), Alignment));
626 return CI;
627}
628
629/// Create a call to a Masked intrinsic, with given intrinsic Id,
630/// an array of operands - Ops, and an array of overloaded types -
631/// OverloadedTypes.
632CallInst *IRBuilderBase::CreateMaskedIntrinsic(Intrinsic::ID Id,
634 ArrayRef<Type *> OverloadedTypes,
635 const Twine &Name) {
636 return CreateIntrinsicWithoutFolding(Id, OverloadedTypes, Ops, {}, Name);
637}
638
639/// Create a call to a Masked Gather intrinsic.
640/// \p Ty - vector type to gather
641/// \p Ptrs - vector of pointers for loading
642/// \p Align - alignment for one element
643/// \p Mask - vector of booleans which indicates what vector lanes should
644/// be accessed in memory
645/// \p PassThru - pass-through value that is used to fill the masked-off lanes
646/// of the result
647/// \p Name - name of the result variable
649 Align Alignment, Value *Mask,
650 Value *PassThru,
651 const Twine &Name) {
652 auto *VecTy = cast<VectorType>(Ty);
653 ElementCount NumElts = VecTy->getElementCount();
654 auto *PtrsTy = cast<VectorType>(Ptrs->getType());
655 assert(NumElts == PtrsTy->getElementCount() && "Element count mismatch");
656
657 if (!Mask)
658 Mask = getAllOnesMask(NumElts);
659
660 if (!PassThru)
661 PassThru = PoisonValue::get(Ty);
662
663 Type *OverloadedTypes[] = {Ty, PtrsTy};
664 Value *Ops[] = {Ptrs, Mask, PassThru};
665
666 // We specify only one type when we create this intrinsic. Types of other
667 // arguments are derived from this type.
668 CallInst *CI = CreateMaskedIntrinsic(Intrinsic::masked_gather, Ops,
669 OverloadedTypes, Name);
670 CI->addParamAttr(0, Attribute::getWithAlignment(CI->getContext(), Alignment));
671 return CI;
672}
673
674/// Create a call to a Masked Scatter intrinsic.
675/// \p Data - data to be stored,
676/// \p Ptrs - the vector of pointers, where the \p Data elements should be
677/// stored
678/// \p Align - alignment for one element
679/// \p Mask - vector of booleans which indicates what vector lanes should
680/// be accessed in memory
682 Align Alignment, Value *Mask) {
683 auto *PtrsTy = cast<VectorType>(Ptrs->getType());
684 auto *DataTy = cast<VectorType>(Data->getType());
685 ElementCount NumElts = PtrsTy->getElementCount();
686
687 if (!Mask)
688 Mask = getAllOnesMask(NumElts);
689
690 Type *OverloadedTypes[] = {DataTy, PtrsTy};
691 Value *Ops[] = {Data, Ptrs, Mask};
692
693 // We specify only one type when we create this intrinsic. Types of other
694 // arguments are derived from this type.
695 CallInst *CI =
696 CreateMaskedIntrinsic(Intrinsic::masked_scatter, Ops, OverloadedTypes);
697 CI->addParamAttr(1, Attribute::getWithAlignment(CI->getContext(), Alignment));
698 return CI;
699}
700
701/// Create a call to Masked Expand Load intrinsic
702/// \p Ty - vector type to load
703/// \p Ptr - base pointer for the load
704/// \p Align - alignment of \p Ptr
705/// \p Mask - vector of booleans which indicates what vector lanes should
706/// be accessed in memory
707/// \p PassThru - pass-through value that is used to fill the masked-off lanes
708/// of the result
709/// \p Name - name of the result variable
711 MaybeAlign Align, Value *Mask,
712 Value *PassThru,
713 const Twine &Name) {
714 assert(Ty->isVectorTy() && "Type should be vector");
715 assert(Mask && "Mask should not be all-ones (null)");
716 if (!PassThru)
717 PassThru = PoisonValue::get(Ty);
718 Type *PtrTy = Ptr->getType();
719 Type *OverloadedTypes[] = {Ty, PtrTy};
720 Value *Ops[] = {Ptr, Mask, PassThru};
721 CallInst *CI = CreateMaskedIntrinsic(Intrinsic::masked_expandload, Ops,
722 OverloadedTypes, Name);
723 if (Align)
725 return CI;
726}
727
728/// Create a call to Masked Compress Store intrinsic
729/// \p Val - data to be stored,
730/// \p Ptr - base pointer for the store
731/// \p Align - alignment of \p Ptr
732/// \p Mask - vector of booleans which indicates what vector lanes should
733/// be accessed in memory
736 Value *Mask) {
737 Type *DataTy = Val->getType();
738 assert(DataTy->isVectorTy() && "Val should be a vector");
739 assert(Mask && "Mask should not be all-ones (null)");
740 Type *PtrTy = Ptr->getType();
741 Type *OverloadedTypes[] = {DataTy, PtrTy};
742 Value *Ops[] = {Val, Ptr, Mask};
743 CallInst *CI = CreateMaskedIntrinsic(Intrinsic::masked_compressstore, Ops,
744 OverloadedTypes);
745 if (Align)
747 return CI;
748}
749
750template <typename T0>
751static std::vector<Value *>
753 Value *ActualCallee, uint32_t Flags, ArrayRef<T0> CallArgs) {
754 std::vector<Value *> Args;
755 Args.push_back(B.getInt64(ID));
756 Args.push_back(B.getInt32(NumPatchBytes));
757 Args.push_back(ActualCallee);
758 Args.push_back(B.getInt32(CallArgs.size()));
759 Args.push_back(B.getInt32(Flags));
760 llvm::append_range(Args, CallArgs);
761 // GC Transition and Deopt args are now always handled via operand bundle.
762 // They will be removed from the signature of gc.statepoint shortly.
763 Args.push_back(B.getInt32(0));
764 Args.push_back(B.getInt32(0));
765 // GC args are now encoded in the gc-live operand bundle
766 return Args;
767}
768
769template<typename T1, typename T2, typename T3>
770static std::vector<OperandBundleDef>
771getStatepointBundles(std::optional<ArrayRef<T1>> TransitionArgs,
772 std::optional<ArrayRef<T2>> DeoptArgs,
773 ArrayRef<T3> GCArgs) {
774 std::vector<OperandBundleDef> Rval;
775 if (DeoptArgs)
776 Rval.emplace_back("deopt", SmallVector<Value *, 16>(*DeoptArgs));
777 if (TransitionArgs)
778 Rval.emplace_back("gc-transition",
779 SmallVector<Value *, 16>(*TransitionArgs));
780 if (GCArgs.size())
781 Rval.emplace_back("gc-live", SmallVector<Value *, 16>(GCArgs));
782 return Rval;
783}
784
785template <typename T0, typename T1, typename T2, typename T3>
787 IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes,
788 FunctionCallee ActualCallee, uint32_t Flags, ArrayRef<T0> CallArgs,
789 std::optional<ArrayRef<T1>> TransitionArgs,
790 std::optional<ArrayRef<T2>> DeoptArgs, ArrayRef<T3> GCArgs,
791 const Twine &Name) {
792 Module *M = Builder->getModule();
793 // Fill in the one generic type'd argument (the function is also vararg)
795 M, Intrinsic::experimental_gc_statepoint,
796 {ActualCallee.getCallee()->getType()});
797
798 std::vector<Value *> Args = getStatepointArgs(
799 *Builder, ID, NumPatchBytes, ActualCallee.getCallee(), Flags, CallArgs);
800
801 CallInst *CI = Builder->CreateCall(
802 FnStatepoint, Args,
803 getStatepointBundles(TransitionArgs, DeoptArgs, GCArgs), Name);
804 CI->addParamAttr(2,
805 Attribute::get(Builder->getContext(), Attribute::ElementType,
806 ActualCallee.getFunctionType()));
807 return CI;
808}
809
811 uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualCallee,
812 ArrayRef<Value *> CallArgs, std::optional<ArrayRef<Value *>> DeoptArgs,
813 ArrayRef<Value *> GCArgs, const Twine &Name) {
815 this, ID, NumPatchBytes, ActualCallee, uint32_t(StatepointFlags::None),
816 CallArgs, std::nullopt /* No Transition Args */, DeoptArgs, GCArgs, Name);
817}
818
820 uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualCallee,
821 uint32_t Flags, ArrayRef<Value *> CallArgs,
822 std::optional<ArrayRef<Use>> TransitionArgs,
823 std::optional<ArrayRef<Use>> DeoptArgs, ArrayRef<Value *> GCArgs,
824 const Twine &Name) {
826 this, ID, NumPatchBytes, ActualCallee, Flags, CallArgs, TransitionArgs,
827 DeoptArgs, GCArgs, Name);
828}
829
831 uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualCallee,
832 ArrayRef<Use> CallArgs, std::optional<ArrayRef<Value *>> DeoptArgs,
833 ArrayRef<Value *> GCArgs, const Twine &Name) {
835 this, ID, NumPatchBytes, ActualCallee, uint32_t(StatepointFlags::None),
836 CallArgs, std::nullopt, DeoptArgs, GCArgs, Name);
837}
838
839template <typename T0, typename T1, typename T2, typename T3>
841 IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes,
842 FunctionCallee ActualInvokee, BasicBlock *NormalDest,
843 BasicBlock *UnwindDest, uint32_t Flags, ArrayRef<T0> InvokeArgs,
844 std::optional<ArrayRef<T1>> TransitionArgs,
845 std::optional<ArrayRef<T2>> DeoptArgs, ArrayRef<T3> GCArgs,
846 const Twine &Name) {
847 Module *M = Builder->getModule();
848 // Fill in the one generic type'd argument (the function is also vararg)
850 M, Intrinsic::experimental_gc_statepoint,
851 {ActualInvokee.getCallee()->getType()});
852
853 std::vector<Value *> Args =
854 getStatepointArgs(*Builder, ID, NumPatchBytes, ActualInvokee.getCallee(),
855 Flags, InvokeArgs);
856
857 InvokeInst *II = Builder->CreateInvoke(
858 FnStatepoint, NormalDest, UnwindDest, Args,
859 getStatepointBundles(TransitionArgs, DeoptArgs, GCArgs), Name);
860 II->addParamAttr(2,
861 Attribute::get(Builder->getContext(), Attribute::ElementType,
862 ActualInvokee.getFunctionType()));
863 return II;
864}
865
867 uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualInvokee,
868 BasicBlock *NormalDest, BasicBlock *UnwindDest,
869 ArrayRef<Value *> InvokeArgs, std::optional<ArrayRef<Value *>> DeoptArgs,
870 ArrayRef<Value *> GCArgs, const Twine &Name) {
872 this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest,
873 uint32_t(StatepointFlags::None), InvokeArgs,
874 std::nullopt /* No Transition Args*/, DeoptArgs, GCArgs, Name);
875}
876
878 uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualInvokee,
879 BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
880 ArrayRef<Value *> InvokeArgs, std::optional<ArrayRef<Use>> TransitionArgs,
881 std::optional<ArrayRef<Use>> DeoptArgs, ArrayRef<Value *> GCArgs,
882 const Twine &Name) {
884 this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest, Flags,
885 InvokeArgs, TransitionArgs, DeoptArgs, GCArgs, Name);
886}
887
889 uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualInvokee,
890 BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
891 std::optional<ArrayRef<Value *>> DeoptArgs, ArrayRef<Value *> GCArgs,
892 const Twine &Name) {
894 this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest,
895 uint32_t(StatepointFlags::None), InvokeArgs, std::nullopt, DeoptArgs,
896 GCArgs, Name);
897}
898
900 Type *ResultType, const Twine &Name) {
901 Intrinsic::ID ID = Intrinsic::experimental_gc_result;
902 Type *Types[] = {ResultType};
903
904 Value *Args[] = {Statepoint};
905 return CreateIntrinsicWithoutFolding(ID, Types, Args, {}, Name);
906}
907
909 int BaseOffset, int DerivedOffset,
910 Type *ResultType, const Twine &Name) {
911 Type *Types[] = {ResultType};
912
913 Value *Args[] = {Statepoint, getInt32(BaseOffset), getInt32(DerivedOffset)};
914 return CreateIntrinsicWithoutFolding(Intrinsic::experimental_gc_relocate,
915 Types, Args, {}, Name);
916}
917
919 const Twine &Name) {
920 Type *PtrTy = DerivedPtr->getType();
922 Intrinsic::experimental_gc_get_pointer_base, PtrTy, DerivedPtr, {}, Name);
923}
924
926 const Twine &Name) {
927 Type *PtrTy = DerivedPtr->getType();
929 Intrinsic::experimental_gc_get_pointer_offset, {PtrTy}, {DerivedPtr}, {},
930 Name);
931}
932
935 const Twine &Name) {
936 Module *M = getModule();
937 Function *Fn = Intrinsic::getOrInsertDeclaration(M, ID, Op->getType());
938 if (Value *V =
939 Folder.FoldIntrinsic(ID, Op, Fn->getReturnType(), FMFSource.get(FMF),
941 return V;
942 return createCallHelper(Fn, Op, Name, FMFSource);
943}
944
947 const Twine &Name) {
948 Module *M = getModule();
949 Function *Fn = Intrinsic::getOrInsertDeclaration(M, ID, {LHS->getType()});
950 if (Value *V = Folder.FoldIntrinsic(ID, {LHS, RHS}, Fn->getReturnType(),
953 return V;
954 return createCallHelper(Fn, {LHS, RHS}, Name, FMFSource);
955}
956
958 Intrinsic::ID ID, ArrayRef<Type *> OverloadTypes, ArrayRef<Value *> Args,
959 FMFSource FMFSource, const Twine &Name,
960 ArrayRef<OperandBundleDef> OpBundles) {
961 Module *M = getModule();
962 Function *Fn = Intrinsic::getOrInsertDeclaration(M, ID, OverloadTypes);
963 return createCallHelper(Fn, Args, Name, FMFSource, OpBundles);
964}
965
967 Intrinsic::ID ID,
970 const Twine &Name) {
971 Module *M = getModule();
973 Function *Fn = Intrinsic::getOrInsertDeclaration(M, ID, RetTy, ArgTys);
974 return createCallHelper(Fn, Args, Name, FMFSource);
975}
976
978 ArrayRef<Type *> OverloadTypes,
980 FMFSource FMFSource, const Twine &Name,
982 function_ref<void(CallInst *)> SetFn) {
983 Type *RetTy = Intrinsic::getType(Context, ID, OverloadTypes)->getReturnType();
984 if (Value *V = Folder.FoldIntrinsic(ID, Args, RetTy, FMFSource.get(FMF),
986 return V;
987 CallInst *CI = CreateIntrinsicWithoutFolding(ID, OverloadTypes, Args,
988 FMFSource, Name, OpBundles);
989 SetFn(CI);
990 return CI;
991}
992
995 FMFSource FMFSource, const Twine &Name,
996 function_ref<void(CallInst *)> SetFn) {
997 if (Value *V = Folder.FoldIntrinsic(ID, Args, RetTy, FMFSource.get(FMF),
999 return V;
1000 CallInst *CI =
1001 CreateIntrinsicWithoutFolding(RetTy, ID, Args, FMFSource, Name);
1002 SetFn(CI);
1003 return CI;
1004}
1005
1008 const Twine &Name, MDNode *FPMathTag, std::optional<RoundingMode> Rounding,
1009 std::optional<fp::ExceptionBehavior> Except) {
1010 Value *RoundingV = getConstrainedFPRounding(Rounding);
1011 Value *ExceptV = getConstrainedFPExcept(Except);
1012
1013 FastMathFlags UseFMF = FMFSource.get(FMF);
1015 ID, {L->getType()}, {L, R, RoundingV, ExceptV}, nullptr, Name, {});
1017 setFPAttrs(C, FPMathTag, UseFMF);
1018 return C;
1019}
1020
1023 FMFSource FMFSource, const Twine &Name, MDNode *FPMathTag,
1024 std::optional<RoundingMode> Rounding,
1025 std::optional<fp::ExceptionBehavior> Except) {
1026 Value *RoundingV = getConstrainedFPRounding(Rounding);
1027 Value *ExceptV = getConstrainedFPExcept(Except);
1028
1029 FastMathFlags UseFMF = FMFSource.get(FMF);
1030
1031 llvm::SmallVector<Value *, 5> ExtArgs(Args);
1032 ExtArgs.push_back(RoundingV);
1033 ExtArgs.push_back(ExceptV);
1034 CallInst *C =
1035 CreateIntrinsicWithoutFolding(ID, Types, ExtArgs, nullptr, Name, {});
1037 setFPAttrs(C, FPMathTag, UseFMF);
1038 return C;
1039}
1040
1043 const Twine &Name, MDNode *FPMathTag,
1044 std::optional<fp::ExceptionBehavior> Except) {
1045 Value *ExceptV = getConstrainedFPExcept(Except);
1046
1047 FastMathFlags UseFMF = FMFSource.get(FMF);
1049 ID, {L->getType()}, {L, R, ExceptV}, nullptr, Name, {});
1051 setFPAttrs(C, FPMathTag, UseFMF);
1052 return C;
1053}
1054
1056 const Twine &Name, MDNode *FPMathTag) {
1058 assert(Ops.size() == 2 && "Invalid number of operands!");
1059 return CreateBinOp(static_cast<Instruction::BinaryOps>(Opc),
1060 Ops[0], Ops[1], Name, FPMathTag);
1061 }
1063 assert(Ops.size() == 1 && "Invalid number of operands!");
1064 return CreateUnOp(static_cast<Instruction::UnaryOps>(Opc),
1065 Ops[0], Name, FPMathTag);
1066 }
1067 llvm_unreachable("Unexpected opcode!");
1068}
1069
1071 Intrinsic::ID ID, Value *V, Type *DestTy, FMFSource FMFSource,
1072 const Twine &Name, MDNode *FPMathTag, std::optional<RoundingMode> Rounding,
1073 std::optional<fp::ExceptionBehavior> Except) {
1074 Value *ExceptV = getConstrainedFPExcept(Except);
1075
1076 FastMathFlags UseFMF = FMFSource.get(FMF);
1077
1078 CallInst *C;
1080 Value *RoundingV = getConstrainedFPRounding(Rounding);
1082 ID, {DestTy, V->getType()}, {V, RoundingV, ExceptV}, nullptr, Name, {});
1083 } else
1084 C = CreateIntrinsicWithoutFolding(ID, {DestTy, V->getType()}, {V, ExceptV},
1085 nullptr, Name, {});
1087
1089 setFPAttrs(C, FPMathTag, UseFMF);
1090 return C;
1091}
1092
1093Value *IRBuilderBase::CreateFCmpHelper(CmpInst::Predicate P, Value *LHS,
1094 Value *RHS, const Twine &Name,
1095 MDNode *FPMathTag, FMFSource FMFSource,
1096 bool IsSignaling) {
1097 if (IsFPConstrained) {
1098 auto ID = IsSignaling ? Intrinsic::experimental_constrained_fcmps
1099 : Intrinsic::experimental_constrained_fcmp;
1100 return CreateConstrainedFPCmp(ID, P, LHS, RHS, Name);
1101 }
1102
1103 if (auto *V = Folder.FoldCmp(P, LHS, RHS))
1104 return V;
1105 return Insert(
1106 setFPAttrs(new FCmpInst(P, LHS, RHS), FPMathTag, FMFSource.get(FMF)),
1107 Name);
1108}
1109
1112 const Twine &Name, std::optional<fp::ExceptionBehavior> Except) {
1113 Value *PredicateV = getConstrainedFPPredicate(P);
1114 Value *ExceptV = getConstrainedFPExcept(Except);
1115
1117 ID, {L->getType()}, {L, R, PredicateV, ExceptV}, nullptr, Name, {});
1119 return C;
1120}
1121
1123 Function *Callee, ArrayRef<Value *> Args, const Twine &Name,
1124 std::optional<RoundingMode> Rounding,
1125 std::optional<fp::ExceptionBehavior> Except) {
1126 llvm::SmallVector<Value *, 6> UseArgs(Args);
1127
1128 if (Intrinsic::hasConstrainedFPRoundingModeOperand(Callee->getIntrinsicID()))
1129 UseArgs.push_back(getConstrainedFPRounding(Rounding));
1130 UseArgs.push_back(getConstrainedFPExcept(Except));
1131
1132 CallInst *C = CreateCall(Callee, UseArgs, Name);
1134 return C;
1135}
1136
1138 Value *False,
1140 const Twine &Name) {
1141 Value *Ret = CreateSelectFMF(C, True, False, {}, Name);
1142 if (auto *SI = dyn_cast<SelectInst>(Ret)) {
1144 }
1145 return Ret;
1146}
1147
1158
1160 const Twine &Name, Instruction *MDFrom) {
1161 return CreateSelectFMF(C, True, False, {}, Name, MDFrom);
1162}
1163
1165 FMFSource FMFSource, const Twine &Name,
1166 Instruction *MDFrom) {
1167 if (auto *V = Folder.FoldSelect(C, True, False, FMFSource.get(FMF)))
1168 return V;
1169
1171 if (MDFrom) {
1172 MDNode *Prof = MDFrom->getMetadata(LLVMContext::MD_prof);
1173 MDNode *Unpred = MDFrom->getMetadata(LLVMContext::MD_unpredictable);
1174 Sel = addBranchMetadata(Sel, Prof, Unpred);
1175 }
1176 if (isa<FPMathOperator>(Sel))
1177 setFPAttrs(Sel, /*MDNode=*/nullptr, FMFSource.get(FMF));
1178 return Insert(Sel, Name);
1179}
1180
1182 bool IsNUW) {
1183 assert(LHS->getType() == RHS->getType() &&
1184 "Pointer subtraction operand types must match!");
1185 Value *LHSAddr = CreatePtrToAddr(LHS);
1186 Value *RHSAddr = CreatePtrToAddr(RHS);
1187 return CreateSub(LHSAddr, RHSAddr, Name, IsNUW);
1188}
1190 const Twine &Name) {
1191 const DataLayout &DL = getDataLayout();
1192 TypeSize ElemSize = DL.getTypeAllocSize(ElemTy);
1193 if (ElemSize == TypeSize::getFixed(1))
1194 return CreatePtrDiff(LHS, RHS, Name);
1195
1196 Value *Diff = CreatePtrDiff(LHS, RHS);
1197 return CreateExactSDiv(Diff, CreateTypeSize(Diff->getType(), ElemSize), Name);
1198}
1199
1202 "launder.invariant.group only applies to pointers.");
1203 auto *PtrType = Ptr->getType();
1204 Module *M = getModule();
1205 Function *FnLaunderInvariantGroup = Intrinsic::getOrInsertDeclaration(
1206 M, Intrinsic::launder_invariant_group, {PtrType});
1207
1208 assert(FnLaunderInvariantGroup->getReturnType() == PtrType &&
1209 FnLaunderInvariantGroup->getFunctionType()->getParamType(0) ==
1210 PtrType &&
1211 "LaunderInvariantGroup should take and return the same type");
1212
1213 return CreateCall(FnLaunderInvariantGroup, {Ptr});
1214}
1215
1217 auto *Ty = cast<VectorType>(V->getType());
1218 if (isa<ScalableVectorType>(Ty)) {
1219 Module *M = getModule();
1220 Function *F =
1221 Intrinsic::getOrInsertDeclaration(M, Intrinsic::vector_reverse, Ty);
1222 return Insert(CallInst::Create(F, V), Name);
1223 }
1224 // Keep the original behaviour for fixed vector
1225 SmallVector<int, 8> ShuffleMask;
1226 int NumElts = Ty->getElementCount().getKnownMinValue();
1227 for (int i = 0; i < NumElts; ++i)
1228 ShuffleMask.push_back(NumElts - i - 1);
1229 return CreateShuffleVector(V, ShuffleMask, Name);
1230}
1231
1232static SmallVector<int, 8> getSpliceMask(int64_t Imm, unsigned NumElts) {
1233 unsigned Idx = (NumElts + Imm) % NumElts;
1235 for (unsigned I = 0; I < NumElts; ++I)
1236 Mask.push_back(Idx + I);
1237 return Mask;
1238}
1239
1241 Value *Offset, const Twine &Name) {
1242 assert(isa<VectorType>(V1->getType()) && "Unexpected type");
1243 assert(V1->getType() == V2->getType() &&
1244 "Splice expects matching operand types!");
1245
1246 // Emit a shufflevector for fixed vectors with a constant offset
1247 if (auto *COffset = dyn_cast<ConstantInt>(Offset))
1248 if (auto *FVTy = dyn_cast<FixedVectorType>(V1->getType()))
1249 return CreateShuffleVector(
1250 V1, V2,
1251 getSpliceMask(COffset->getZExtValue(), FVTy->getNumElements()));
1252
1253 return CreateIntrinsic(Intrinsic::vector_splice_left, V1->getType(),
1254 {V1, V2, Offset}, {}, Name);
1255}
1256
1258 Value *Offset,
1259 const Twine &Name) {
1260 assert(isa<VectorType>(V1->getType()) && "Unexpected type");
1261 assert(V1->getType() == V2->getType() &&
1262 "Splice expects matching operand types!");
1263
1264 // Emit a shufflevector for fixed vectors with a constant offset
1265 if (auto *COffset = dyn_cast<ConstantInt>(Offset))
1266 if (auto *FVTy = dyn_cast<FixedVectorType>(V1->getType()))
1267 return CreateShuffleVector(
1268 V1, V2,
1269 getSpliceMask(-COffset->getZExtValue(), FVTy->getNumElements()));
1270
1271 return CreateIntrinsic(Intrinsic::vector_splice_right, V1->getType(),
1272 {V1, V2, Offset}, {}, Name);
1273}
1274
1276 const Twine &Name) {
1277 auto EC = ElementCount::getFixed(NumElts);
1278 return CreateVectorSplat(EC, V, Name);
1279}
1280
1282 const Twine &Name) {
1283 assert(EC.isNonZero() && "Cannot splat to an empty vector!");
1284
1285 // First insert it into a poison vector so we can shuffle it.
1286 Value *Poison = PoisonValue::get(VectorType::get(V->getType(), EC));
1287 V = CreateInsertElement(Poison, V, getInt64(0), Name + ".splatinsert");
1288
1289 // Shuffle the value across the desired number of elements.
1291 Zeros.resize(EC.getKnownMinValue());
1292 return CreateShuffleVector(V, Zeros, Name + ".splat");
1293}
1294
1296 const Twine &Name) {
1297 assert(Ops.size() >= 2 && Ops.size() <= 8 &&
1298 "Unexpected number of operands to interleave");
1299
1300 // Make sure all operands are the same type.
1301 assert(isa<VectorType>(Ops[0]->getType()) && "Unexpected type");
1302
1303#ifndef NDEBUG
1304 for (unsigned I = 1; I < Ops.size(); I++) {
1305 assert(Ops[I]->getType() == Ops[0]->getType() &&
1306 "Vector interleave expects matching operand types!");
1307 }
1308#endif
1309
1310 unsigned IID = Intrinsic::getInterleaveIntrinsicID(Ops.size());
1311 auto *SubvecTy = cast<VectorType>(Ops[0]->getType());
1312 Type *DestTy = VectorType::get(SubvecTy->getElementType(),
1313 SubvecTy->getElementCount() * Ops.size());
1314 return CreateIntrinsic(IID, {DestTy}, Ops, {}, Name);
1315}
1316
1318 unsigned Dimension,
1319 unsigned LastIndex,
1320 MDNode *DbgInfo) {
1321 auto *BaseType = Base->getType();
1323 "Invalid Base ptr type for preserve.array.access.index.");
1324
1325 Value *LastIndexV = getInt32(LastIndex);
1326 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1327 SmallVector<Value *, 4> IdxList(Dimension, Zero);
1328 IdxList.push_back(LastIndexV);
1329
1330 Type *ResultType = GetElementPtrInst::getGEPReturnType(Base, IdxList);
1331
1332 Value *DimV = getInt32(Dimension);
1334 Intrinsic::preserve_array_access_index, {ResultType, BaseType},
1335 {Base, DimV, LastIndexV});
1336 Fn->addParamAttr(
1337 0, Attribute::get(Fn->getContext(), Attribute::ElementType, ElTy));
1338 if (DbgInfo)
1339 Fn->setMetadata(LLVMContext::MD_preserve_access_index, DbgInfo);
1340
1341 return Fn;
1342}
1343
1345 Value *Base, unsigned FieldIndex, MDNode *DbgInfo) {
1346 assert(isa<PointerType>(Base->getType()) &&
1347 "Invalid Base ptr type for preserve.union.access.index.");
1348 auto *BaseType = Base->getType();
1349
1350 Value *DIIndex = getInt32(FieldIndex);
1351 CallInst *Fn =
1352 CreateIntrinsicWithoutFolding(Intrinsic::preserve_union_access_index,
1353 {BaseType, BaseType}, {Base, DIIndex});
1354 if (DbgInfo)
1355 Fn->setMetadata(LLVMContext::MD_preserve_access_index, DbgInfo);
1356
1357 return Fn;
1358}
1359
1361 Type *ElTy, Value *Base, unsigned Index, unsigned FieldIndex,
1362 MDNode *DbgInfo) {
1363 auto *BaseType = Base->getType();
1365 "Invalid Base ptr type for preserve.struct.access.index.");
1366
1367 Value *GEPIndex = getInt32(Index);
1368 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1369 Type *ResultType =
1371
1372 Value *DIIndex = getInt32(FieldIndex);
1374 Intrinsic::preserve_struct_access_index, {ResultType, BaseType},
1375 {Base, GEPIndex, DIIndex});
1376 Fn->addParamAttr(
1377 0, Attribute::get(Fn->getContext(), Attribute::ElementType, ElTy));
1378 if (DbgInfo)
1379 Fn->setMetadata(LLVMContext::MD_preserve_access_index, DbgInfo);
1380
1381 return Fn;
1382}
1383
1385 ConstantInt *TestV = getInt32(Test);
1386 return CreateIntrinsic(Intrinsic::is_fpclass, {FPNum->getType()},
1387 {FPNum, TestV});
1388}
1389
1390CallInst *IRBuilderBase::CreateAlignmentAssumptionHelper(const DataLayout &DL,
1391 Value *PtrValue,
1392 Value *AlignValue,
1393 Value *OffsetValue) {
1394 SmallVector<Value *, 4> Vals({PtrValue, AlignValue});
1395 if (OffsetValue)
1396 Vals.push_back(OffsetValue);
1397 OperandBundleDefT<Value *> AlignOpB("align", Vals);
1398 return CreateAssumption({AlignOpB});
1399}
1400
1402 Value *PtrValue,
1403 uint64_t Alignment,
1404 Value *OffsetValue) {
1405 assert(isa<PointerType>(PtrValue->getType()) &&
1406 "trying to create an alignment assumption on a non-pointer?");
1407 assert(Alignment != 0 && "Invalid Alignment");
1408 Value *AlignValue = ConstantInt::get(getInt64Ty(), Alignment);
1409 return CreateAlignmentAssumptionHelper(DL, PtrValue, AlignValue, OffsetValue);
1410}
1411
1413 Value *PtrValue,
1414 Value *Alignment,
1415 Value *OffsetValue) {
1416 assert(isa<PointerType>(PtrValue->getType()) &&
1417 "trying to create an alignment assumption on a non-pointer?");
1418 return CreateAlignmentAssumptionHelper(DL, PtrValue, Alignment, OffsetValue);
1419}
1420
1422 Value *SizeValue) {
1423 assert(isa<PointerType>(PtrValue->getType()) &&
1424 "trying to create a deferenceable assumption on a non-pointer?");
1425 SmallVector<Value *, 4> Vals({PtrValue, SizeValue});
1426 OperandBundleDefT<Value *> DereferenceableOpB("dereferenceable", Vals);
1427 return CreateAssumption({DereferenceableOpB});
1428}
1429
1431 assert(isa<PointerType>(PtrValue->getType()) &&
1432 "trying to create a nonnull assumption on a non-pointer?");
1433 return CreateAssumption(OperandBundleDef("nonnull", PtrValue));
1434}
1435
1439 "trying to create a range assumption on a non-integer?");
1440 assert(!Range.isFullSet() &&
1441 "trying to create a range assumption which doesn't assume anything?");
1442 return CreateAssumption(
1443 OperandBundleDef("range", ArrayRef<Value *>{Val, getInt(Range.getLower()),
1444 getInt(Range.getUpper())}));
1445}
1446
1448 const Twine &Name, GEPNoWrapFlags NW) {
1449 const DataLayout &DL = getDataLayout();
1450 if (auto *V = Folder.FoldGEP(DL, Ty, Ptr, IdxList, NW))
1451 return V;
1452
1453 if (!CanonicalizeGEPs)
1454 return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList, NW), Name);
1455
1456 unsigned IdxSize = DL.getIndexTypeSizeInBits(Ptr->getType());
1457 if (Ty->isIntegerTy(8) && IdxList[0]->getType()->isIntOrIntVectorTy(IdxSize))
1458 return CreatePtrAdd(Ptr, IdxList[0], Name, NW);
1459
1460 auto GTI = gep_type_begin(Ty, IdxList), GTE = gep_type_end(Ty, IdxList);
1461 for (; GTI != GTE; ++GTI) {
1462 Value *Op = GTI.getOperand();
1463 Type *IdxTy = Op->getType()->getWithNewBitWidth(IdxSize);
1464 if (auto *OpC = dyn_cast<Constant>(Op)) {
1465 // Skip zero indices, except for vector splats.
1466 bool IsSplat = IdxTy->isVectorTy() && !Ptr->getType()->isVectorTy();
1467 if (OpC->isNullValue() && !IsSplat)
1468 continue;
1469
1470 if (StructType *STy = GTI.getStructTypeOrNull()) {
1471 uint64_t OpValue = OpC->getUniqueInteger().getZExtValue();
1472 uint64_t Offset = DL.getStructLayout(STy)->getElementOffset(OpValue);
1473 if (!Offset && !IsSplat)
1474 continue;
1475
1476 Constant *OffsetC = ConstantInt::get(IdxTy, Offset, /*IsSigned=*/false,
1477 /*ImplicitTrunc=*/true);
1478 Ptr = CreatePtrAdd(Ptr, OffsetC, Name, NW);
1479 continue;
1480 }
1481 }
1482
1483 if (Op->getType() != IdxTy)
1484 Op = CreateSExtOrTrunc(Op, IdxTy);
1485
1486 TypeSize Stride = GTI.getSequentialElementStride(DL);
1487 auto *OpC = dyn_cast<ConstantInt>(Op);
1488 if (OpC && !Stride.isScalable()) {
1489 APInt StrideInt(IdxSize, Stride.getFixedValue(), /*IsSigned=*/false,
1490 /*ImplicitTrunc=*/true);
1491 Ptr = CreatePtrAdd(
1492 Ptr, ConstantInt::get(IdxTy, OpC->getValue() * StrideInt), Name, NW);
1493 continue;
1494 }
1495
1496 Ptr = CreateScaledPtrAdd(Ptr, Stride, Op, Name, NW);
1497 }
1498 return Ptr;
1499}
1500
1501void IRBuilderFolder::anchor() {}
1502void ConstantFolder::anchor() {}
1503void NoFolder::anchor() {}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isConstantOne(const Value *Val)
isConstantOne - Return true only if val is constant int 1
static InvokeInst * CreateGCStatepointInvokeCommon(IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags, ArrayRef< T0 > InvokeArgs, std::optional< ArrayRef< T1 > > TransitionArgs, std::optional< ArrayRef< T2 > > DeoptArgs, ArrayRef< T3 > GCArgs, const Twine &Name)
static CallInst * CreateGCStatepointCallCommon(IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualCallee, uint32_t Flags, ArrayRef< T0 > CallArgs, std::optional< ArrayRef< T1 > > TransitionArgs, std::optional< ArrayRef< T2 > > DeoptArgs, ArrayRef< T3 > GCArgs, const Twine &Name)
static MaybeAlign getAlign(Value *Ptr)
static Value * CreateVScaleMultiple(IRBuilderBase &B, Type *Ty, uint64_t Scale)
static std::vector< OperandBundleDef > getStatepointBundles(std::optional< ArrayRef< T1 > > TransitionArgs, std::optional< ArrayRef< T2 > > DeoptArgs, ArrayRef< T3 > GCArgs)
static std::vector< Value * > getStatepointArgs(IRBuilderBase &B, uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, uint32_t Flags, ArrayRef< T0 > CallArgs)
static SmallVector< int, 8 > getSpliceMask(int64_t Imm, unsigned NumElts)
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
This file defines less commonly used SmallVector utilities.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static const char PassName[]
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
an instruction to allocate memory on the stack
LLVM_ABI TypeSize getAllocationBaseSize(const DataLayout &DL) const
Get the size of the allocated type.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
void setCallingConv(CallingConv::ID CC)
void addRetAttr(Attribute::AttrKind Kind)
Adds the attribute to the return value.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void setTailCall(bool IsTc=true)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This class represents a range of values.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
This instruction compares its operands according to the predicate given to the constructor.
This provides a helper for copying FMF from an instruction or setting specified flags.
Definition IRBuilder.h:90
FastMathFlags get(FastMathFlags Default) const
Definition IRBuilder.h:100
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
FunctionType * getFunctionType()
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
Represents flags for the getelementptr instruction/expression.
static Type * getGEPReturnType(Value *Ptr, ArrayRef< Value * > IdxList)
Returns the pointer type returned by the GEP instruction, which may be a vector of pointers.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1497
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition IRBuilder.h:446
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
LLVM_ABI Value * CreateAndReduce(Value *Src)
Create a vector int AND reduction intrinsic of the source vector.
LLVM_ABI Value * CreateXorReduce(Value *Src)
Create a vector int XOR reduction intrinsic of the source vector.
LLVM_ABI Value * CreateLaunderInvariantGroup(Value *Ptr)
Create a launder.invariant.group intrinsic call.
LLVM_ABI Value * CreateSelectFMFWithUnknownProfile(Value *C, Value *True, Value *False, FMFSource FMFSource, StringRef PassName, const Twine &Name="")
const DataLayout & getDataLayout() const
Get data layout.
Definition IRBuilder.h:182
LLVM_ABI Value * CreateFPMinReduce(Value *Src)
Create a vector float min reduction intrinsic of the source vector.
LLVM_ABI CallInst * CreateConstrainedFPUnroundedBinOp(Intrinsic::ID ID, Value *L, Value *R, FMFSource FMFSource={}, const Twine &Name="", MDNode *FPMathTag=nullptr, std::optional< fp::ExceptionBehavior > Except=std::nullopt)
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2745
LLVM_ABI CallInst * CreateThreadLocalAddress(Value *Ptr)
Create a call to llvm.threadlocal.address intrinsic.
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:513
LLVM_ABI CallInst * CreateMaskedCompressStore(Value *Val, Value *Ptr, MaybeAlign Align, Value *Mask=nullptr)
Create a call to Masked Compress Store intrinsic.
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2799
LLVM_ABI Value * CreateAllocationSize(Type *DestTy, AllocaInst *AI)
Get allocation size of an alloca as a runtime Value* (handles both static and dynamic allocas and vsc...
Value * CreateScaledPtrAdd(Value *Ptr, uint64_t Scale, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2148
LLVM_ABI Type * getCurrentFunctionReturnType() const
Get the return type of the current function that we're emitting into.
Definition IRBuilder.cpp:61
LLVM_ABI CallInst * CreateGCGetPointerBase(Value *DerivedPtr, const Twine &Name="")
Create a call to the experimental.gc.pointer.base intrinsic to get the base pointer for the specified...
LLVM_ABI CallInst * CreateLifetimeStart(Value *Ptr)
Create a lifetime.start intrinsic.
LLVM_ABI CallInst * CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualCallee, ArrayRef< Value * > CallArgs, std::optional< ArrayRef< Value * > > DeoptArgs, ArrayRef< Value * > GCArgs, const Twine &Name="")
Create a call to the experimental.gc.statepoint intrinsic to start a new statepoint sequence.
LLVM_ABI CallInst * CreateNonnullAssumption(Value *PtrValue)
Create an assume intrinsic call that represents a nonnull assumption on the provided pointer.
LLVM_ABI Value * CreateFPMaximumNumReduce(Value *Src)
Create a vector float maximum reduction intrinsic of the source vector.
LLVM_ABI Value * CreateFPMaximumReduce(Value *Src)
Create a vector float maximum reduction intrinsic of the source vector.
LLVM_ABI Value * CreateVectorSpliceRight(Value *V1, Value *V2, Value *Offset, const Twine &Name="")
Create a vector.splice.right intrinsic call, or a shufflevector that produces the same result if the ...
LLVM_ABI CallInst * CreateLifetimeEnd(Value *Ptr)
Create a lifetime.end intrinsic.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2215
LLVM_ABI CallInst * CreateConstrainedFPCmp(Intrinsic::ID ID, CmpInst::Predicate P, Value *L, Value *R, const Twine &Name="", std::optional< fp::ExceptionBehavior > Except=std::nullopt)
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
LLVM_ABI Value * CreateIntMaxReduce(Value *Src, bool IsSigned=false)
Create a vector integer max reduction intrinsic of the source vector.
Value * CreatePtrToAddr(Value *V, const Twine &Name="")
Definition IRBuilder.h:2305
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2792
LLVM_ABI Value * CreatePreserveStructAccessIndex(Type *ElTy, Value *Base, unsigned Index, unsigned FieldIndex, MDNode *DbgInfo)
LLVM_ABI CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
LLVM_ABI CallInst * CreateConstrainedFPCall(Function *Callee, ArrayRef< Value * > Args, const Twine &Name="", std::optional< RoundingMode > Rounding=std::nullopt, std::optional< fp::ExceptionBehavior > Except=std::nullopt)
LLVM_ABI Value * CreateFPMinimumNumReduce(Value *Src)
Create a vector float minimum reduction intrinsic of the source vector.
LLVMContext & Context
Definition IRBuilder.h:121
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
LLVM_ABI CallInst * CreateMalloc(Type *IntPtrTy, Value *AllocSize, Value *ArraySize, ArrayRef< OperandBundleDef > OpB, Function *MallocF=nullptr, const Twine &Name="")
LLVM_ABI Value * CreateIntMinReduce(Value *Src, bool IsSigned=false)
Create a vector integer min reduction intrinsic of the source vector.
LLVM_ABI CallInst * CreateGCGetPointerOffset(Value *DerivedPtr, const Twine &Name="")
Create a call to the experimental.gc.get.pointer.offset intrinsic to get the offset of the specified ...
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2314
LLVM_ABI CallInst * CreateConstrainedFPBinOp(Intrinsic::ID ID, Value *L, Value *R, FMFSource FMFSource={}, const Twine &Name="", MDNode *FPMathTag=nullptr, std::optional< RoundingMode > Rounding=std::nullopt, std::optional< fp::ExceptionBehavior > Except=std::nullopt)
Value * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Definition IRBuilder.h:1114
LLVM_ABI Value * CreateAggregateCast(Value *V, Type *DestTy)
Cast between aggregate types that must have identical structure but may differ in their leaf types.
Definition IRBuilder.cpp:75
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2094
LLVM_ABI CallInst * CreateRangeAssumption(Value *Int, ConstantRange Range)
LLVM_ABI CallInst * CreateAssumption(Value *Cond)
Create an assume intrinsic call that allows the optimizer to assume that the provided condition will ...
BasicBlock * GetInsertBlock() const
Definition IRBuilder.h:174
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:533
LLVM_ABI CallInst * CreateElementUnorderedAtomicMemMove(Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size, uint32_t ElementSize, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert an element unordered-atomic memmove between the specified pointers.
Module * getModule() const
Get the module.
Definition IRBuilder.h:190
LLVM_ABI Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
LLVM_ABI Value * CreateVectorReverse(Value *V, const Twine &Name="")
Return a vector value that contains the vector V reversed.
FastMathFlags FMF
Definition IRBuilder.h:126
LLVM_ABI Value * CreateMulReduce(Value *Src)
Create a vector int mul reduction intrinsic of the source vector.
LLVM_ABI Value * CreateBitPreservingCastChain(const DataLayout &DL, Value *V, Type *NewTy)
Create a chain of casts to convert V to NewTy, preserving the bit pattern of V.
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:476
LLVM_ABI Value * CreateVectorSpliceLeft(Value *V1, Value *V2, Value *Offset, const Twine &Name="")
Create a vector.splice.left intrinsic call, or a shufflevector that produces the same result if the r...
Value * getAllOnesMask(ElementCount NumElts)
Return an all true boolean vector (mask) with NumElts lanes.
Definition IRBuilder.h:842
LLVM_ABI Value * CreateFPMaxReduce(Value *Src)
Create a vector float max reduction intrinsic of the source vector.
Value * CreateUnOp(Instruction::UnaryOps Opc, Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1860
LLVM_ABI Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
LLVM_ABI Value * createIsFPClass(Value *FPNum, unsigned Test)
LLVM_ABI Value * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:471
LLVM_ABI CallInst * CreateFree(Value *Source, ArrayRef< OperandBundleDef > Bundles={})
Generate the IR for a call to the builtin free function.
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2408
LLVM_ABI Value * CreateAddReduce(Value *Src)
Create a vector int add reduction intrinsic of the source vector.
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition IRBuilder.h:148
LLVM_ABI Value * CreateFPMinimumReduce(Value *Src)
Create a vector float minimum reduction intrinsic of the source vector.
LLVM_ABI DebugLoc getCurrentDebugLocation() const
Get location information used by debugging information.
Definition IRBuilder.cpp:67
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
LLVM_ABI Value * CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name="", bool IsNUW=false)
Return the difference between two pointer values.
CallInst * CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val, uint64_t Size, Align Alignment, uint32_t ElementSize, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert an element unordered-atomic memset of the region of memory starting at the given po...
Definition IRBuilder.h:623
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, MaybeAlign Align, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memset to the specified pointer and the specified value.
Definition IRBuilder.h:602
LLVM_ABI Value * CreateNAryOp(unsigned Opc, ArrayRef< Value * > Ops, const Twine &Name="", MDNode *FPMathTag=nullptr)
Create either a UnaryOperator or BinaryOperator depending on Opc.
LLVM_ABI CallInst * CreateConstrainedFPIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource, const Twine &Name, MDNode *FPMathTag=nullptr, std::optional< RoundingMode > Rounding=std::nullopt, std::optional< fp::ExceptionBehavior > Except=std::nullopt)
This function is like CreateIntrinsic for constrained fp intrinsics.
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2767
LLVMContext & getContext() const
Definition IRBuilder.h:178
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
LLVM_ABI Value * CreatePreserveUnionAccessIndex(Value *Base, unsigned FieldIndex, MDNode *DbgInfo)
LLVM_ABI Value * CreateSelectWithUnknownProfile(Value *C, Value *True, Value *False, StringRef PassName, const Twine &Name="")
LLVM_ABI CallInst * CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, Value *Mask)
Create a call to Masked Store intrinsic.
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2309
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2637
LLVM_ABI CallInst * CreateGCResult(Instruction *Statepoint, Type *ResultType, const Twine &Name="")
Create a call to the experimental.gc.result intrinsic to extract the result from a call wrapped in a ...
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2183
LLVM_ABI CallInst * CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue, uint64_t Alignment, Value *OffsetValue=nullptr)
Create an assume intrinsic call that represents an alignment assumption on the provided pointer.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
LLVM_ABI Value * CreateTypeSize(Type *Ty, TypeSize Size)
Create an expression which evaluates to the number of units in Size at runtime.
LLVM_ABI CallInst * CreateDereferenceableAssumption(Value *PtrValue, Value *SizeValue)
Create an assume intrinsic call that represents a dereferencable assumption on the provided pointer.
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2399
LLVM_ABI CallInst * CreateElementUnorderedAtomicMemCpy(Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size, uint32_t ElementSize, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert an element unordered-atomic memcpy between the specified pointers.
void setConstrainedFPCallAttr(CallBase *I)
Definition IRBuilder.h:340
LLVM_ABI Value * CreateFAddReduce(Value *Acc, Value *Src)
Create a sequential vector fadd reduction intrinsic of the source vector.
LLVM_ABI InvokeInst * CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef< Value * > InvokeArgs, std::optional< ArrayRef< Value * > > DeoptArgs, ArrayRef< Value * > GCArgs, const Twine &Name="")
Create an invoke to the experimental.gc.statepoint intrinsic to start a new statepoint sequence.
LLVM_ABI CallInst * CreateMaskedExpandLoad(Type *Ty, Value *Ptr, MaybeAlign Align, Value *Mask=nullptr, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Expand Load intrinsic.
const IRBuilderFolder & Folder
Definition IRBuilder.h:122
LLVM_ABI CallInst * CreateMemTransferInst(Intrinsic::ID IntrID, Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, Value *Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI Value * CreateVectorInterleave(ArrayRef< Value * > Ops, const Twine &Name="")
LLVM_ABI Value * CreateFMulReduce(Value *Acc, Value *Src)
Create a sequential vector fmul reduction intrinsic of the source vector.
LLVM_ABI CallInst * CreateMemSetInline(Value *Dst, MaybeAlign DstAlign, Value *Val, Value *Size, bool IsVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI void SetInstDebugLocation(Instruction *I) const
If this builder has a current debug location, set it on the specified instruction.
Definition IRBuilder.cpp:68
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:518
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:486
LLVM_ABI CallInst * CreateGCRelocate(Instruction *Statepoint, int BaseOffset, int DerivedOffset, Type *ResultType, const Twine &Name="")
Create a call to the experimental.gc.relocate intrinsics to project the relocated value of one pointe...
LLVM_ABI Value * CreateStepVector(Type *DstType, const Twine &Name="")
Creates a vector of type DstType with the linear sequence <0, 1, ...>
LLVM_ABI Value * CreatePreserveArrayAccessIndex(Type *ElTy, Value *Base, unsigned Dimension, unsigned LastIndex, MDNode *DbgInfo)
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2230
Value * CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec, Value *Idx, const Twine &Name="")
Create a call to the vector.insert intrinsic.
Definition IRBuilder.h:1128
LLVM_ABI CallInst * CreateInvariantStart(Value *Ptr, ConstantInt *Size=nullptr)
Create a call to invariant.start intrinsic.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1458
LLVM_ABI Instruction * CreateNoAliasScopeDeclaration(Value *Scope)
Create a llvm.experimental.noalias.scope.decl intrinsic call.
LLVM_ABI CallInst * CreateMaskedScatter(Value *Val, Value *Ptrs, Align Alignment, Value *Mask=nullptr)
Create a call to Masked Scatter intrinsic.
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
LLVM_ABI GlobalVariable * CreateGlobalString(StringRef Str, const Twine &Name="", unsigned AddressSpace=0, Module *M=nullptr, bool AddNull=true)
Make a new global variable with initializer type i8*.
Definition IRBuilder.cpp:46
LLVM_ABI Value * CreateElementCount(Type *Ty, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
LLVM_ABI CallInst * CreateConstrainedFPCast(Intrinsic::ID ID, Value *V, Type *DestTy, FMFSource FMFSource={}, const Twine &Name="", MDNode *FPMathTag=nullptr, std::optional< RoundingMode > Rounding=std::nullopt, std::optional< fp::ExceptionBehavior > Except=std::nullopt)
LLVM_ABI CallInst * CreateMaskedGather(Type *Ty, Value *Ptrs, Align Alignment, Value *Mask=nullptr, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Gather intrinsic.
virtual Value * FoldCmp(CmpInst::Predicate P, Value *LHS, Value *RHS) const =0
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
bool isBinaryOp() const
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
bool isUnaryOp() const
Invoke instruction.
Metadata node.
Definition Metadata.h:1081
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A container for an operand bundle being viewed as a set of values rather than a set of uses.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
void resize(size_type N)
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
Class to represent struct types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:274
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
Type * getArrayElementType() const
Definition Type.h:420
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static VectorType * getWithSizeAndScalar(VectorType *SizeTy, Type *EltTy)
This static method attempts to construct a VectorType with the same size-in-bits as SizeTy but with a...
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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 Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI Intrinsic::ID getInterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.interleaveN intrinsic for factor N.
LLVM_ABI FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > OverloadTys={})
Return the function type for an intrinsic.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
gep_type_iterator gep_type_end(const User *GEP)
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
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:34
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
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
gep_type_iterator gep_type_begin(const User *GEP)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:774
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111