1 //===---- IRBuilder.cpp - Builder for LLVM Instrs -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the IRBuilder class, which is used as a convenient way
11 // to create LLVM instructions with a consistent and simplified interface.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/Function.h"
16 #include "llvm/IR/GlobalVariable.h"
17 #include "llvm/IR/IRBuilder.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Statepoint.h"
23 /// CreateGlobalString - Make a new global variable with an initializer that
24 /// has array of i8 type filled in with the nul terminated string value
25 /// specified. If Name is specified, it is the name of the global variable
27 GlobalVariable *IRBuilderBase::CreateGlobalString(StringRef Str,
29 unsigned AddressSpace) {
30 Constant *StrConstant = ConstantDataArray::getString(Context, Str);
31 Module &M = *BB->getParent()->getParent();
32 GlobalVariable *GV = new GlobalVariable(M, StrConstant->getType(),
33 true, GlobalValue::PrivateLinkage,
34 StrConstant, Name, nullptr,
35 GlobalVariable::NotThreadLocal,
37 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
41 Type *IRBuilderBase::getCurrentFunctionReturnType() const {
42 assert(BB && BB->getParent() && "No current function!");
43 return BB->getParent()->getReturnType();
46 Value *IRBuilderBase::getCastedInt8PtrValue(Value *Ptr) {
47 PointerType *PT = cast<PointerType>(Ptr->getType());
48 if (PT->getElementType()->isIntegerTy(8))
51 // Otherwise, we need to insert a bitcast.
52 PT = getInt8PtrTy(PT->getAddressSpace());
53 BitCastInst *BCI = new BitCastInst(Ptr, PT, "");
54 BB->getInstList().insert(InsertPt, BCI);
55 SetInstDebugLocation(BCI);
59 static CallInst *createCallHelper(Value *Callee, ArrayRef<Value *> Ops,
60 IRBuilderBase *Builder,
61 const Twine& Name="") {
62 CallInst *CI = CallInst::Create(Callee, Ops, Name);
63 Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),CI);
64 Builder->SetInstDebugLocation(CI);
68 static InvokeInst *createInvokeHelper(Value *Invokee, BasicBlock *NormalDest,
69 BasicBlock *UnwindDest,
70 ArrayRef<Value *> Ops,
71 IRBuilderBase *Builder,
72 const Twine &Name = "") {
74 InvokeInst::Create(Invokee, NormalDest, UnwindDest, Ops, Name);
75 Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),
77 Builder->SetInstDebugLocation(II);
81 CallInst *IRBuilderBase::
82 CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
83 bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag,
85 Ptr = getCastedInt8PtrValue(Ptr);
86 Value *Ops[] = { Ptr, Val, Size, getInt32(Align), getInt1(isVolatile) };
87 Type *Tys[] = { Ptr->getType(), Size->getType() };
88 Module *M = BB->getParent()->getParent();
89 Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys);
91 CallInst *CI = createCallHelper(TheFn, Ops, this);
93 // Set the TBAA info if present.
95 CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
98 CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
101 CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
106 CallInst *IRBuilderBase::
107 CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
108 bool isVolatile, MDNode *TBAATag, MDNode *TBAAStructTag,
109 MDNode *ScopeTag, MDNode *NoAliasTag) {
110 Dst = getCastedInt8PtrValue(Dst);
111 Src = getCastedInt8PtrValue(Src);
113 Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) };
114 Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
115 Module *M = BB->getParent()->getParent();
116 Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
118 CallInst *CI = createCallHelper(TheFn, Ops, this);
120 // Set the TBAA info if present.
122 CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
124 // Set the TBAA Struct info if present.
126 CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag);
129 CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
132 CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
137 CallInst *IRBuilderBase::
138 CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
139 bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag,
140 MDNode *NoAliasTag) {
141 Dst = getCastedInt8PtrValue(Dst);
142 Src = getCastedInt8PtrValue(Src);
144 Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) };
145 Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
146 Module *M = BB->getParent()->getParent();
147 Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memmove, Tys);
149 CallInst *CI = createCallHelper(TheFn, Ops, this);
151 // Set the TBAA info if present.
153 CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
156 CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
159 CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
164 CallInst *IRBuilderBase::CreateLifetimeStart(Value *Ptr, ConstantInt *Size) {
165 assert(isa<PointerType>(Ptr->getType()) &&
166 "lifetime.start only applies to pointers.");
167 Ptr = getCastedInt8PtrValue(Ptr);
171 assert(Size->getType() == getInt64Ty() &&
172 "lifetime.start requires the size to be an i64");
173 Value *Ops[] = { Size, Ptr };
174 Module *M = BB->getParent()->getParent();
175 Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_start);
176 return createCallHelper(TheFn, Ops, this);
179 CallInst *IRBuilderBase::CreateLifetimeEnd(Value *Ptr, ConstantInt *Size) {
180 assert(isa<PointerType>(Ptr->getType()) &&
181 "lifetime.end only applies to pointers.");
182 Ptr = getCastedInt8PtrValue(Ptr);
186 assert(Size->getType() == getInt64Ty() &&
187 "lifetime.end requires the size to be an i64");
188 Value *Ops[] = { Size, Ptr };
189 Module *M = BB->getParent()->getParent();
190 Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_end);
191 return createCallHelper(TheFn, Ops, this);
194 CallInst *IRBuilderBase::CreateAssumption(Value *Cond) {
195 assert(Cond->getType() == getInt1Ty() &&
196 "an assumption condition must be of type i1");
198 Value *Ops[] = { Cond };
199 Module *M = BB->getParent()->getParent();
200 Value *FnAssume = Intrinsic::getDeclaration(M, Intrinsic::assume);
201 return createCallHelper(FnAssume, Ops, this);
204 /// \brief Create a call to a Masked Load intrinsic.
205 /// \p Ptr - base pointer for the load
206 /// \p Align - alignment of the source location
207 /// \p Mask - vector of booleans which indicates what vector lanes should
208 /// be accessed in memory
209 /// \p PassThru - pass-through value that is used to fill the masked-off lanes
211 /// \p Name - name of the result variable
212 CallInst *IRBuilderBase::CreateMaskedLoad(Value *Ptr, unsigned Align,
213 Value *Mask, Value *PassThru,
215 PointerType *PtrTy = cast<PointerType>(Ptr->getType());
216 Type *DataTy = PtrTy->getElementType();
217 assert(DataTy->isVectorTy() && "Ptr should point to a vector");
219 PassThru = UndefValue::get(DataTy);
220 Type *OverloadedTypes[] = { DataTy, PtrTy };
221 Value *Ops[] = { Ptr, getInt32(Align), Mask, PassThru};
222 return CreateMaskedIntrinsic(Intrinsic::masked_load, Ops,
223 OverloadedTypes, Name);
226 /// \brief Create a call to a Masked Store intrinsic.
227 /// \p Val - data to be stored,
228 /// \p Ptr - base pointer for the store
229 /// \p Align - alignment of the destination location
230 /// \p Mask - vector of booleans which indicates what vector lanes should
231 /// be accessed in memory
232 CallInst *IRBuilderBase::CreateMaskedStore(Value *Val, Value *Ptr,
233 unsigned Align, Value *Mask) {
234 PointerType *PtrTy = cast<PointerType>(Ptr->getType());
235 Type *DataTy = PtrTy->getElementType();
236 assert(DataTy->isVectorTy() && "Ptr should point to a vector");
237 Type *OverloadedTypes[] = { DataTy, PtrTy };
238 Value *Ops[] = { Val, Ptr, getInt32(Align), Mask };
239 return CreateMaskedIntrinsic(Intrinsic::masked_store, Ops, OverloadedTypes);
242 /// Create a call to a Masked intrinsic, with given intrinsic Id,
243 /// an array of operands - Ops, and an array of overloaded types -
245 CallInst *IRBuilderBase::CreateMaskedIntrinsic(Intrinsic::ID Id,
246 ArrayRef<Value *> Ops,
247 ArrayRef<Type *> OverloadedTypes,
249 Module *M = BB->getParent()->getParent();
250 Value *TheFn = Intrinsic::getDeclaration(M, Id, OverloadedTypes);
251 return createCallHelper(TheFn, Ops, this, Name);
254 /// \brief Create a call to a Masked Gather intrinsic.
255 /// \p Ptrs - vector of pointers for loading
256 /// \p Align - alignment for one element
257 /// \p Mask - vector of booleans which indicates what vector lanes should
258 /// be accessed in memory
259 /// \p PassThru - pass-through value that is used to fill the masked-off lanes
261 /// \p Name - name of the result variable
262 CallInst *IRBuilderBase::CreateMaskedGather(Value *Ptrs, unsigned Align,
263 Value *Mask, Value *PassThru,
265 auto PtrsTy = cast<VectorType>(Ptrs->getType());
266 auto PtrTy = cast<PointerType>(PtrsTy->getElementType());
267 unsigned NumElts = PtrsTy->getVectorNumElements();
268 Type *DataTy = VectorType::get(PtrTy->getElementType(), NumElts);
271 Mask = Constant::getAllOnesValue(VectorType::get(Type::getInt1Ty(Context),
274 Value * Ops[] = {Ptrs, getInt32(Align), Mask, UndefValue::get(DataTy)};
276 // We specify only one type when we create this intrinsic. Types of other
277 // arguments are derived from this type.
278 return CreateMaskedIntrinsic(Intrinsic::masked_gather, Ops, { DataTy }, Name);
281 /// \brief Create a call to a Masked Scatter intrinsic.
282 /// \p Data - data to be stored,
283 /// \p Ptrs - the vector of pointers, where the \p Data elements should be
285 /// \p Align - alignment for one element
286 /// \p Mask - vector of booleans which indicates what vector lanes should
287 /// be accessed in memory
288 CallInst *IRBuilderBase::CreateMaskedScatter(Value *Data, Value *Ptrs,
289 unsigned Align, Value *Mask) {
290 auto PtrsTy = cast<VectorType>(Ptrs->getType());
291 auto DataTy = cast<VectorType>(Data->getType());
292 unsigned NumElts = PtrsTy->getVectorNumElements();
295 auto PtrTy = cast<PointerType>(PtrsTy->getElementType());
296 assert(NumElts == DataTy->getVectorNumElements() &&
297 PtrTy->getElementType() == DataTy->getElementType() &&
298 "Incompatible pointer and data types");
302 Mask = Constant::getAllOnesValue(VectorType::get(Type::getInt1Ty(Context),
304 Value * Ops[] = {Data, Ptrs, getInt32(Align), Mask};
306 // We specify only one type when we create this intrinsic. Types of other
307 // arguments are derived from this type.
308 return CreateMaskedIntrinsic(Intrinsic::masked_scatter, Ops, { DataTy });
311 template <typename T0, typename T1, typename T2, typename T3>
312 static std::vector<Value *>
313 getStatepointArgs(IRBuilderBase &B, uint64_t ID, uint32_t NumPatchBytes,
314 Value *ActualCallee, uint32_t Flags, ArrayRef<T0> CallArgs,
315 ArrayRef<T1> TransitionArgs, ArrayRef<T2> DeoptArgs,
316 ArrayRef<T3> GCArgs) {
317 std::vector<Value *> Args;
318 Args.push_back(B.getInt64(ID));
319 Args.push_back(B.getInt32(NumPatchBytes));
320 Args.push_back(ActualCallee);
321 Args.push_back(B.getInt32(CallArgs.size()));
322 Args.push_back(B.getInt32(Flags));
323 Args.insert(Args.end(), CallArgs.begin(), CallArgs.end());
324 Args.push_back(B.getInt32(TransitionArgs.size()));
325 Args.insert(Args.end(), TransitionArgs.begin(), TransitionArgs.end());
326 Args.push_back(B.getInt32(DeoptArgs.size()));
327 Args.insert(Args.end(), DeoptArgs.begin(), DeoptArgs.end());
328 Args.insert(Args.end(), GCArgs.begin(), GCArgs.end());
333 template <typename T0, typename T1, typename T2, typename T3>
334 static CallInst *CreateGCStatepointCallCommon(
335 IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes,
336 Value *ActualCallee, uint32_t Flags, ArrayRef<T0> CallArgs,
337 ArrayRef<T1> TransitionArgs, ArrayRef<T2> DeoptArgs, ArrayRef<T3> GCArgs,
339 // Extract out the type of the callee.
340 PointerType *FuncPtrType = cast<PointerType>(ActualCallee->getType());
341 assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
342 "actual callee must be a callable value");
344 Module *M = Builder->GetInsertBlock()->getParent()->getParent();
345 // Fill in the one generic type'd argument (the function is also vararg)
346 Type *ArgTypes[] = { FuncPtrType };
347 Function *FnStatepoint =
348 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_statepoint,
351 std::vector<llvm::Value *> Args =
352 getStatepointArgs(*Builder, ID, NumPatchBytes, ActualCallee, Flags,
353 CallArgs, TransitionArgs, DeoptArgs, GCArgs);
354 return createCallHelper(FnStatepoint, Args, Builder, Name);
357 CallInst *IRBuilderBase::CreateGCStatepointCall(
358 uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
359 ArrayRef<Value *> CallArgs, ArrayRef<Value *> DeoptArgs,
360 ArrayRef<Value *> GCArgs, const Twine &Name) {
361 return CreateGCStatepointCallCommon<Value *, Value *, Value *, Value *>(
362 this, ID, NumPatchBytes, ActualCallee, uint32_t(StatepointFlags::None),
363 CallArgs, None /* No Transition Args */, DeoptArgs, GCArgs, Name);
366 CallInst *IRBuilderBase::CreateGCStatepointCall(
367 uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, uint32_t Flags,
368 ArrayRef<Use> CallArgs, ArrayRef<Use> TransitionArgs,
369 ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
370 return CreateGCStatepointCallCommon<Use, Use, Use, Value *>(
371 this, ID, NumPatchBytes, ActualCallee, Flags, CallArgs, TransitionArgs,
372 DeoptArgs, GCArgs, Name);
375 CallInst *IRBuilderBase::CreateGCStatepointCall(
376 uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
377 ArrayRef<Use> CallArgs, ArrayRef<Value *> DeoptArgs,
378 ArrayRef<Value *> GCArgs, const Twine &Name) {
379 return CreateGCStatepointCallCommon<Use, Value *, Value *, Value *>(
380 this, ID, NumPatchBytes, ActualCallee, uint32_t(StatepointFlags::None),
381 CallArgs, None, DeoptArgs, GCArgs, Name);
384 template <typename T0, typename T1, typename T2, typename T3>
385 static InvokeInst *CreateGCStatepointInvokeCommon(
386 IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes,
387 Value *ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest,
388 uint32_t Flags, ArrayRef<T0> InvokeArgs, ArrayRef<T1> TransitionArgs,
389 ArrayRef<T2> DeoptArgs, ArrayRef<T3> GCArgs, const Twine &Name) {
390 // Extract out the type of the callee.
391 PointerType *FuncPtrType = cast<PointerType>(ActualInvokee->getType());
392 assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
393 "actual callee must be a callable value");
395 Module *M = Builder->GetInsertBlock()->getParent()->getParent();
396 // Fill in the one generic type'd argument (the function is also vararg)
397 Function *FnStatepoint = Intrinsic::getDeclaration(
398 M, Intrinsic::experimental_gc_statepoint, {FuncPtrType});
400 std::vector<llvm::Value *> Args =
401 getStatepointArgs(*Builder, ID, NumPatchBytes, ActualInvokee, Flags,
402 InvokeArgs, TransitionArgs, DeoptArgs, GCArgs);
403 return createInvokeHelper(FnStatepoint, NormalDest, UnwindDest, Args, Builder,
407 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
408 uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
409 BasicBlock *NormalDest, BasicBlock *UnwindDest,
410 ArrayRef<Value *> InvokeArgs, ArrayRef<Value *> DeoptArgs,
411 ArrayRef<Value *> GCArgs, const Twine &Name) {
412 return CreateGCStatepointInvokeCommon<Value *, Value *, Value *, Value *>(
413 this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest,
414 uint32_t(StatepointFlags::None), InvokeArgs, None /* No Transition Args*/,
415 DeoptArgs, GCArgs, Name);
418 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
419 uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
420 BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
421 ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
422 ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
423 return CreateGCStatepointInvokeCommon<Use, Use, Use, Value *>(
424 this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest, Flags,
425 InvokeArgs, TransitionArgs, DeoptArgs, GCArgs, Name);
428 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
429 uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
430 BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
431 ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
432 return CreateGCStatepointInvokeCommon<Use, Value *, Value *, Value *>(
433 this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest,
434 uint32_t(StatepointFlags::None), InvokeArgs, None, DeoptArgs, GCArgs,
438 CallInst *IRBuilderBase::CreateGCResult(Instruction *Statepoint,
441 Intrinsic::ID ID = Intrinsic::experimental_gc_result;
442 Module *M = BB->getParent()->getParent();
443 Type *Types[] = {ResultType};
444 Value *FnGCResult = Intrinsic::getDeclaration(M, ID, Types);
446 Value *Args[] = {Statepoint};
447 return createCallHelper(FnGCResult, Args, this, Name);
450 CallInst *IRBuilderBase::CreateGCRelocate(Instruction *Statepoint,
455 Module *M = BB->getParent()->getParent();
456 Type *Types[] = {ResultType};
457 Value *FnGCRelocate =
458 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
460 Value *Args[] = {Statepoint,
461 getInt32(BaseOffset),
462 getInt32(DerivedOffset)};
463 return createCallHelper(FnGCRelocate, Args, this, Name);