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"
16 #include "llvm/ADT/None.h"
17 #include "llvm/IR/Constant.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/Statepoint.h"
28 #include "llvm/IR/Type.h"
29 #include "llvm/IR/Value.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <cassert>
33 #include <cstdint>
34 #include <vector>
35 
36 using namespace llvm;
37 
38 /// CreateGlobalString - Make a new global variable with an initializer that
39 /// has array of i8 type filled in with the nul terminated string value
40 /// specified.  If Name is specified, it is the name of the global variable
41 /// created.
42 GlobalVariable *IRBuilderBase::CreateGlobalString(StringRef Str,
43                                                   const Twine &Name,
44                                                   unsigned AddressSpace) {
45   Constant *StrConstant = ConstantDataArray::getString(Context, Str);
46   Module &M = *BB->getParent()->getParent();
47   auto *GV = new GlobalVariable(M, StrConstant->getType(), true,
48                                 GlobalValue::PrivateLinkage, StrConstant, Name,
49                                 nullptr, GlobalVariable::NotThreadLocal,
50                                 AddressSpace);
51   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
52   GV->setAlignment(Align(1));
53   return GV;
54 }
55 
56 Type *IRBuilderBase::getCurrentFunctionReturnType() const {
57   assert(BB && BB->getParent() && "No current function!");
58   return BB->getParent()->getReturnType();
59 }
60 
61 Value *IRBuilderBase::getCastedInt8PtrValue(Value *Ptr) {
62   auto *PT = cast<PointerType>(Ptr->getType());
63   if (PT->getElementType()->isIntegerTy(8))
64     return Ptr;
65 
66   // Otherwise, we need to insert a bitcast.
67   PT = getInt8PtrTy(PT->getAddressSpace());
68   BitCastInst *BCI = new BitCastInst(Ptr, PT, "");
69   BB->getInstList().insert(InsertPt, BCI);
70   SetInstDebugLocation(BCI);
71   return BCI;
72 }
73 
74 static CallInst *createCallHelper(Function *Callee, ArrayRef<Value *> Ops,
75                                   IRBuilderBase *Builder,
76                                   const Twine &Name = "",
77                                   Instruction *FMFSource = nullptr) {
78   CallInst *CI = CallInst::Create(Callee, Ops, Name);
79   if (FMFSource)
80     CI->copyFastMathFlags(FMFSource);
81   Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),CI);
82   Builder->SetInstDebugLocation(CI);
83   return CI;
84 }
85 
86 static InvokeInst *createInvokeHelper(Function *Invokee, BasicBlock *NormalDest,
87                                       BasicBlock *UnwindDest,
88                                       ArrayRef<Value *> Ops,
89                                       IRBuilderBase *Builder,
90                                       const Twine &Name = "") {
91   InvokeInst *II =
92       InvokeInst::Create(Invokee, NormalDest, UnwindDest, Ops, Name);
93   Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),
94                                                   II);
95   Builder->SetInstDebugLocation(II);
96   return II;
97 }
98 
99 CallInst *IRBuilderBase::CreateMemSet(Value *Ptr, Value *Val, Value *Size,
100                                       MaybeAlign Align, bool isVolatile,
101                                       MDNode *TBAATag, MDNode *ScopeTag,
102                                       MDNode *NoAliasTag) {
103   Ptr = getCastedInt8PtrValue(Ptr);
104   Value *Ops[] = {Ptr, Val, Size, getInt1(isVolatile)};
105   Type *Tys[] = { Ptr->getType(), Size->getType() };
106   Module *M = BB->getParent()->getParent();
107   Function *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys);
108 
109   CallInst *CI = createCallHelper(TheFn, Ops, this);
110 
111   if (Align)
112     cast<MemSetInst>(CI)->setDestAlignment(Align->value());
113 
114   // Set the TBAA info if present.
115   if (TBAATag)
116     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
117 
118   if (ScopeTag)
119     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
120 
121   if (NoAliasTag)
122     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
123 
124   return CI;
125 }
126 
127 CallInst *IRBuilderBase::CreateElementUnorderedAtomicMemSet(
128     Value *Ptr, Value *Val, Value *Size, Align Alignment, uint32_t ElementSize,
129     MDNode *TBAATag, MDNode *ScopeTag, MDNode *NoAliasTag) {
130 
131   Ptr = getCastedInt8PtrValue(Ptr);
132   Value *Ops[] = {Ptr, Val, Size, getInt32(ElementSize)};
133   Type *Tys[] = {Ptr->getType(), Size->getType()};
134   Module *M = BB->getParent()->getParent();
135   Function *TheFn = Intrinsic::getDeclaration(
136       M, Intrinsic::memset_element_unordered_atomic, Tys);
137 
138   CallInst *CI = createCallHelper(TheFn, Ops, this);
139 
140   cast<AtomicMemSetInst>(CI)->setDestAlignment(Alignment);
141 
142   // Set the TBAA info if present.
143   if (TBAATag)
144     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
145 
146   if (ScopeTag)
147     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
148 
149   if (NoAliasTag)
150     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
151 
152   return CI;
153 }
154 
155 CallInst *IRBuilderBase::CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src,
156                                       unsigned SrcAlign, Value *Size,
157                                       bool isVolatile, MDNode *TBAATag,
158                                       MDNode *TBAAStructTag, MDNode *ScopeTag,
159                                       MDNode *NoAliasTag) {
160   return CreateMemCpy(Dst, MaybeAlign(DstAlign), Src, MaybeAlign(SrcAlign),
161                       Size, isVolatile, TBAATag, TBAAStructTag, ScopeTag,
162                       NoAliasTag);
163 }
164 
165 CallInst *IRBuilderBase::CreateMemCpy(Value *Dst, MaybeAlign DstAlign,
166                                       Value *Src, MaybeAlign SrcAlign,
167                                       Value *Size, bool isVolatile,
168                                       MDNode *TBAATag, MDNode *TBAAStructTag,
169                                       MDNode *ScopeTag, MDNode *NoAliasTag) {
170   Dst = getCastedInt8PtrValue(Dst);
171   Src = getCastedInt8PtrValue(Src);
172 
173   Value *Ops[] = {Dst, Src, Size, getInt1(isVolatile)};
174   Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
175   Module *M = BB->getParent()->getParent();
176   Function *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
177 
178   CallInst *CI = createCallHelper(TheFn, Ops, this);
179 
180   auto* MCI = cast<MemCpyInst>(CI);
181   if (DstAlign)
182     MCI->setDestAlignment(*DstAlign);
183   if (SrcAlign)
184     MCI->setSourceAlignment(*SrcAlign);
185 
186   // Set the TBAA info if present.
187   if (TBAATag)
188     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
189 
190   // Set the TBAA Struct info if present.
191   if (TBAAStructTag)
192     CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag);
193 
194   if (ScopeTag)
195     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
196 
197   if (NoAliasTag)
198     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
199 
200   return CI;
201 }
202 
203 CallInst *IRBuilderBase::CreateMemCpyInline(Value *Dst, MaybeAlign DstAlign,
204                                             Value *Src, MaybeAlign SrcAlign,
205                                             Value *Size) {
206   Dst = getCastedInt8PtrValue(Dst);
207   Src = getCastedInt8PtrValue(Src);
208   Value *IsVolatile = getInt1(false);
209 
210   Value *Ops[] = {Dst, Src, Size, IsVolatile};
211   Type *Tys[] = {Dst->getType(), Src->getType(), Size->getType()};
212   Function *F = BB->getParent();
213   Module *M = F->getParent();
214   Function *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy_inline, Tys);
215 
216   CallInst *CI = createCallHelper(TheFn, Ops, this);
217 
218   auto *MCI = cast<MemCpyInlineInst>(CI);
219   if (DstAlign)
220     MCI->setDestAlignment(*DstAlign);
221   if (SrcAlign)
222     MCI->setSourceAlignment(*SrcAlign);
223 
224   return CI;
225 }
226 
227 CallInst *IRBuilderBase::CreateElementUnorderedAtomicMemCpy(
228     Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
229     uint32_t ElementSize, MDNode *TBAATag, MDNode *TBAAStructTag,
230     MDNode *ScopeTag, MDNode *NoAliasTag) {
231   assert(DstAlign >= ElementSize &&
232          "Pointer alignment must be at least element size");
233   assert(SrcAlign >= ElementSize &&
234          "Pointer alignment must be at least element size");
235   Dst = getCastedInt8PtrValue(Dst);
236   Src = getCastedInt8PtrValue(Src);
237 
238   Value *Ops[] = {Dst, Src, Size, getInt32(ElementSize)};
239   Type *Tys[] = {Dst->getType(), Src->getType(), Size->getType()};
240   Module *M = BB->getParent()->getParent();
241   Function *TheFn = Intrinsic::getDeclaration(
242       M, Intrinsic::memcpy_element_unordered_atomic, Tys);
243 
244   CallInst *CI = createCallHelper(TheFn, Ops, this);
245 
246   // Set the alignment of the pointer args.
247   auto *AMCI = cast<AtomicMemCpyInst>(CI);
248   AMCI->setDestAlignment(DstAlign);
249   AMCI->setSourceAlignment(SrcAlign);
250 
251   // Set the TBAA info if present.
252   if (TBAATag)
253     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
254 
255   // Set the TBAA Struct info if present.
256   if (TBAAStructTag)
257     CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag);
258 
259   if (ScopeTag)
260     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
261 
262   if (NoAliasTag)
263     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
264 
265   return CI;
266 }
267 
268 CallInst *IRBuilderBase::CreateMemMove(Value *Dst, MaybeAlign DstAlign,
269                                        Value *Src, MaybeAlign SrcAlign,
270                                        Value *Size, bool isVolatile,
271                                        MDNode *TBAATag, MDNode *ScopeTag,
272                                        MDNode *NoAliasTag) {
273   Dst = getCastedInt8PtrValue(Dst);
274   Src = getCastedInt8PtrValue(Src);
275 
276   Value *Ops[] = {Dst, Src, Size, getInt1(isVolatile)};
277   Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
278   Module *M = BB->getParent()->getParent();
279   Function *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memmove, Tys);
280 
281   CallInst *CI = createCallHelper(TheFn, Ops, this);
282 
283   auto *MMI = cast<MemMoveInst>(CI);
284   if (DstAlign)
285     MMI->setDestAlignment(*DstAlign);
286   if (SrcAlign)
287     MMI->setSourceAlignment(*SrcAlign);
288 
289   // Set the TBAA info if present.
290   if (TBAATag)
291     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
292 
293   if (ScopeTag)
294     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
295 
296   if (NoAliasTag)
297     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
298 
299   return CI;
300 }
301 
302 CallInst *IRBuilderBase::CreateElementUnorderedAtomicMemMove(
303     Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
304     uint32_t ElementSize, MDNode *TBAATag, MDNode *TBAAStructTag,
305     MDNode *ScopeTag, MDNode *NoAliasTag) {
306   assert(DstAlign >= ElementSize &&
307          "Pointer alignment must be at least element size");
308   assert(SrcAlign >= ElementSize &&
309          "Pointer alignment must be at least element size");
310   Dst = getCastedInt8PtrValue(Dst);
311   Src = getCastedInt8PtrValue(Src);
312 
313   Value *Ops[] = {Dst, Src, Size, getInt32(ElementSize)};
314   Type *Tys[] = {Dst->getType(), Src->getType(), Size->getType()};
315   Module *M = BB->getParent()->getParent();
316   Function *TheFn = Intrinsic::getDeclaration(
317       M, Intrinsic::memmove_element_unordered_atomic, Tys);
318 
319   CallInst *CI = createCallHelper(TheFn, Ops, this);
320 
321   // Set the alignment of the pointer args.
322   CI->addParamAttr(0, Attribute::getWithAlignment(CI->getContext(), DstAlign));
323   CI->addParamAttr(1, Attribute::getWithAlignment(CI->getContext(), SrcAlign));
324 
325   // Set the TBAA info if present.
326   if (TBAATag)
327     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
328 
329   // Set the TBAA Struct info if present.
330   if (TBAAStructTag)
331     CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag);
332 
333   if (ScopeTag)
334     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
335 
336   if (NoAliasTag)
337     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
338 
339   return CI;
340 }
341 
342 static CallInst *getReductionIntrinsic(IRBuilderBase *Builder, Intrinsic::ID ID,
343                                     Value *Src) {
344   Module *M = Builder->GetInsertBlock()->getParent()->getParent();
345   Value *Ops[] = {Src};
346   Type *Tys[] = { Src->getType() };
347   auto Decl = Intrinsic::getDeclaration(M, ID, Tys);
348   return createCallHelper(Decl, Ops, Builder);
349 }
350 
351 CallInst *IRBuilderBase::CreateFAddReduce(Value *Acc, Value *Src) {
352   Module *M = GetInsertBlock()->getParent()->getParent();
353   Value *Ops[] = {Acc, Src};
354   Type *Tys[] = {Acc->getType(), Src->getType()};
355   auto Decl = Intrinsic::getDeclaration(
356       M, Intrinsic::experimental_vector_reduce_v2_fadd, Tys);
357   return createCallHelper(Decl, Ops, this);
358 }
359 
360 CallInst *IRBuilderBase::CreateFMulReduce(Value *Acc, Value *Src) {
361   Module *M = GetInsertBlock()->getParent()->getParent();
362   Value *Ops[] = {Acc, Src};
363   Type *Tys[] = {Acc->getType(), Src->getType()};
364   auto Decl = Intrinsic::getDeclaration(
365       M, Intrinsic::experimental_vector_reduce_v2_fmul, Tys);
366   return createCallHelper(Decl, Ops, this);
367 }
368 
369 CallInst *IRBuilderBase::CreateAddReduce(Value *Src) {
370   return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_add,
371                                Src);
372 }
373 
374 CallInst *IRBuilderBase::CreateMulReduce(Value *Src) {
375   return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_mul,
376                                Src);
377 }
378 
379 CallInst *IRBuilderBase::CreateAndReduce(Value *Src) {
380   return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_and,
381                                Src);
382 }
383 
384 CallInst *IRBuilderBase::CreateOrReduce(Value *Src) {
385   return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_or,
386                                Src);
387 }
388 
389 CallInst *IRBuilderBase::CreateXorReduce(Value *Src) {
390   return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_xor,
391                                Src);
392 }
393 
394 CallInst *IRBuilderBase::CreateIntMaxReduce(Value *Src, bool IsSigned) {
395   auto ID = IsSigned ? Intrinsic::experimental_vector_reduce_smax
396                      : Intrinsic::experimental_vector_reduce_umax;
397   return getReductionIntrinsic(this, ID, Src);
398 }
399 
400 CallInst *IRBuilderBase::CreateIntMinReduce(Value *Src, bool IsSigned) {
401   auto ID = IsSigned ? Intrinsic::experimental_vector_reduce_smin
402                      : Intrinsic::experimental_vector_reduce_umin;
403   return getReductionIntrinsic(this, ID, Src);
404 }
405 
406 CallInst *IRBuilderBase::CreateFPMaxReduce(Value *Src, bool NoNaN) {
407   auto Rdx = getReductionIntrinsic(
408       this, Intrinsic::experimental_vector_reduce_fmax, Src);
409   if (NoNaN) {
410     FastMathFlags FMF;
411     FMF.setNoNaNs();
412     Rdx->setFastMathFlags(FMF);
413   }
414   return Rdx;
415 }
416 
417 CallInst *IRBuilderBase::CreateFPMinReduce(Value *Src, bool NoNaN) {
418   auto Rdx = getReductionIntrinsic(
419       this, Intrinsic::experimental_vector_reduce_fmin, Src);
420   if (NoNaN) {
421     FastMathFlags FMF;
422     FMF.setNoNaNs();
423     Rdx->setFastMathFlags(FMF);
424   }
425   return Rdx;
426 }
427 
428 CallInst *IRBuilderBase::CreateLifetimeStart(Value *Ptr, ConstantInt *Size) {
429   assert(isa<PointerType>(Ptr->getType()) &&
430          "lifetime.start only applies to pointers.");
431   Ptr = getCastedInt8PtrValue(Ptr);
432   if (!Size)
433     Size = getInt64(-1);
434   else
435     assert(Size->getType() == getInt64Ty() &&
436            "lifetime.start requires the size to be an i64");
437   Value *Ops[] = { Size, Ptr };
438   Module *M = BB->getParent()->getParent();
439   Function *TheFn =
440       Intrinsic::getDeclaration(M, Intrinsic::lifetime_start, {Ptr->getType()});
441   return createCallHelper(TheFn, Ops, this);
442 }
443 
444 CallInst *IRBuilderBase::CreateLifetimeEnd(Value *Ptr, ConstantInt *Size) {
445   assert(isa<PointerType>(Ptr->getType()) &&
446          "lifetime.end only applies to pointers.");
447   Ptr = getCastedInt8PtrValue(Ptr);
448   if (!Size)
449     Size = getInt64(-1);
450   else
451     assert(Size->getType() == getInt64Ty() &&
452            "lifetime.end requires the size to be an i64");
453   Value *Ops[] = { Size, Ptr };
454   Module *M = BB->getParent()->getParent();
455   Function *TheFn =
456       Intrinsic::getDeclaration(M, Intrinsic::lifetime_end, {Ptr->getType()});
457   return createCallHelper(TheFn, Ops, this);
458 }
459 
460 CallInst *IRBuilderBase::CreateInvariantStart(Value *Ptr, ConstantInt *Size) {
461 
462   assert(isa<PointerType>(Ptr->getType()) &&
463          "invariant.start only applies to pointers.");
464   Ptr = getCastedInt8PtrValue(Ptr);
465   if (!Size)
466     Size = getInt64(-1);
467   else
468     assert(Size->getType() == getInt64Ty() &&
469            "invariant.start requires the size to be an i64");
470 
471   Value *Ops[] = {Size, Ptr};
472   // Fill in the single overloaded type: memory object type.
473   Type *ObjectPtr[1] = {Ptr->getType()};
474   Module *M = BB->getParent()->getParent();
475   Function *TheFn =
476       Intrinsic::getDeclaration(M, Intrinsic::invariant_start, ObjectPtr);
477   return createCallHelper(TheFn, Ops, this);
478 }
479 
480 CallInst *IRBuilderBase::CreateAssumption(Value *Cond) {
481   assert(Cond->getType() == getInt1Ty() &&
482          "an assumption condition must be of type i1");
483 
484   Value *Ops[] = { Cond };
485   Module *M = BB->getParent()->getParent();
486   Function *FnAssume = Intrinsic::getDeclaration(M, Intrinsic::assume);
487   return createCallHelper(FnAssume, Ops, this);
488 }
489 
490 /// Create a call to a Masked Load intrinsic.
491 /// \p Ptr       - base pointer for the load
492 /// \p Alignment - alignment of the source location
493 /// \p Mask      - vector of booleans which indicates what vector lanes should
494 ///                be accessed in memory
495 /// \p PassThru  - pass-through value that is used to fill the masked-off lanes
496 ///                of the result
497 /// \p Name      - name of the result variable
498 CallInst *IRBuilderBase::CreateMaskedLoad(Value *Ptr, Align Alignment,
499                                           Value *Mask, Value *PassThru,
500                                           const Twine &Name) {
501   auto *PtrTy = cast<PointerType>(Ptr->getType());
502   Type *DataTy = PtrTy->getElementType();
503   assert(DataTy->isVectorTy() && "Ptr should point to a vector");
504   assert(Mask && "Mask should not be all-ones (null)");
505   if (!PassThru)
506     PassThru = UndefValue::get(DataTy);
507   Type *OverloadedTypes[] = { DataTy, PtrTy };
508   Value *Ops[] = {Ptr, getInt32(Alignment.value()), Mask, PassThru};
509   return CreateMaskedIntrinsic(Intrinsic::masked_load, Ops,
510                                OverloadedTypes, Name);
511 }
512 
513 /// Create a call to a Masked Store intrinsic.
514 /// \p Val       - data to be stored,
515 /// \p Ptr       - base pointer for the store
516 /// \p Alignment - alignment of the destination location
517 /// \p Mask      - vector of booleans which indicates what vector lanes should
518 ///                be accessed in memory
519 CallInst *IRBuilderBase::CreateMaskedStore(Value *Val, Value *Ptr,
520                                            Align Alignment, Value *Mask) {
521   auto *PtrTy = cast<PointerType>(Ptr->getType());
522   Type *DataTy = PtrTy->getElementType();
523   assert(DataTy->isVectorTy() && "Ptr should point to a vector");
524   assert(Mask && "Mask should not be all-ones (null)");
525   Type *OverloadedTypes[] = { DataTy, PtrTy };
526   Value *Ops[] = {Val, Ptr, getInt32(Alignment.value()), Mask};
527   return CreateMaskedIntrinsic(Intrinsic::masked_store, Ops, OverloadedTypes);
528 }
529 
530 /// Create a call to a Masked intrinsic, with given intrinsic Id,
531 /// an array of operands - Ops, and an array of overloaded types -
532 /// OverloadedTypes.
533 CallInst *IRBuilderBase::CreateMaskedIntrinsic(Intrinsic::ID Id,
534                                                ArrayRef<Value *> Ops,
535                                                ArrayRef<Type *> OverloadedTypes,
536                                                const Twine &Name) {
537   Module *M = BB->getParent()->getParent();
538   Function *TheFn = Intrinsic::getDeclaration(M, Id, OverloadedTypes);
539   return createCallHelper(TheFn, Ops, this, Name);
540 }
541 
542 /// Create a call to a Masked Gather intrinsic.
543 /// \p Ptrs     - vector of pointers for loading
544 /// \p Align    - alignment for one element
545 /// \p Mask     - vector of booleans which indicates what vector lanes should
546 ///               be accessed in memory
547 /// \p PassThru - pass-through value that is used to fill the masked-off lanes
548 ///               of the result
549 /// \p Name     - name of the result variable
550 CallInst *IRBuilderBase::CreateMaskedGather(Value *Ptrs, Align Alignment,
551                                             Value *Mask, Value *PassThru,
552                                             const Twine &Name) {
553   auto PtrsTy = cast<VectorType>(Ptrs->getType());
554   auto PtrTy = cast<PointerType>(PtrsTy->getElementType());
555   unsigned NumElts = PtrsTy->getVectorNumElements();
556   Type *DataTy = VectorType::get(PtrTy->getElementType(), NumElts);
557 
558   if (!Mask)
559     Mask = Constant::getAllOnesValue(VectorType::get(Type::getInt1Ty(Context),
560                                      NumElts));
561 
562   if (!PassThru)
563     PassThru = UndefValue::get(DataTy);
564 
565   Type *OverloadedTypes[] = {DataTy, PtrsTy};
566   Value *Ops[] = {Ptrs, getInt32(Alignment.value()), Mask, PassThru};
567 
568   // We specify only one type when we create this intrinsic. Types of other
569   // arguments are derived from this type.
570   return CreateMaskedIntrinsic(Intrinsic::masked_gather, Ops, OverloadedTypes,
571                                Name);
572 }
573 
574 /// Create a call to a Masked Scatter intrinsic.
575 /// \p Data  - data to be stored,
576 /// \p Ptrs  - the vector of pointers, where the \p Data elements should be
577 ///            stored
578 /// \p Align - alignment for one element
579 /// \p Mask  - vector of booleans which indicates what vector lanes should
580 ///            be accessed in memory
581 CallInst *IRBuilderBase::CreateMaskedScatter(Value *Data, Value *Ptrs,
582                                              Align Alignment, Value *Mask) {
583   auto PtrsTy = cast<VectorType>(Ptrs->getType());
584   auto DataTy = cast<VectorType>(Data->getType());
585   unsigned NumElts = PtrsTy->getVectorNumElements();
586 
587 #ifndef NDEBUG
588   auto PtrTy = cast<PointerType>(PtrsTy->getElementType());
589   assert(NumElts == DataTy->getVectorNumElements() &&
590          PtrTy->getElementType() == DataTy->getElementType() &&
591          "Incompatible pointer and data types");
592 #endif
593 
594   if (!Mask)
595     Mask = Constant::getAllOnesValue(VectorType::get(Type::getInt1Ty(Context),
596                                      NumElts));
597 
598   Type *OverloadedTypes[] = {DataTy, PtrsTy};
599   Value *Ops[] = {Data, Ptrs, getInt32(Alignment.value()), Mask};
600 
601   // We specify only one type when we create this intrinsic. Types of other
602   // arguments are derived from this type.
603   return CreateMaskedIntrinsic(Intrinsic::masked_scatter, Ops, OverloadedTypes);
604 }
605 
606 template <typename T0, typename T1, typename T2, typename T3>
607 static std::vector<Value *>
608 getStatepointArgs(IRBuilderBase &B, uint64_t ID, uint32_t NumPatchBytes,
609                   Value *ActualCallee, uint32_t Flags, ArrayRef<T0> CallArgs,
610                   ArrayRef<T1> TransitionArgs, ArrayRef<T2> DeoptArgs,
611                   ArrayRef<T3> GCArgs) {
612   std::vector<Value *> Args;
613   Args.push_back(B.getInt64(ID));
614   Args.push_back(B.getInt32(NumPatchBytes));
615   Args.push_back(ActualCallee);
616   Args.push_back(B.getInt32(CallArgs.size()));
617   Args.push_back(B.getInt32(Flags));
618   Args.insert(Args.end(), CallArgs.begin(), CallArgs.end());
619   Args.push_back(B.getInt32(TransitionArgs.size()));
620   Args.insert(Args.end(), TransitionArgs.begin(), TransitionArgs.end());
621   Args.push_back(B.getInt32(DeoptArgs.size()));
622   Args.insert(Args.end(), DeoptArgs.begin(), DeoptArgs.end());
623   Args.insert(Args.end(), GCArgs.begin(), GCArgs.end());
624 
625   return Args;
626 }
627 
628 template <typename T0, typename T1, typename T2, typename T3>
629 static CallInst *CreateGCStatepointCallCommon(
630     IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes,
631     Value *ActualCallee, uint32_t Flags, ArrayRef<T0> CallArgs,
632     ArrayRef<T1> TransitionArgs, ArrayRef<T2> DeoptArgs, ArrayRef<T3> GCArgs,
633     const Twine &Name) {
634   // Extract out the type of the callee.
635   auto *FuncPtrType = cast<PointerType>(ActualCallee->getType());
636   assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
637          "actual callee must be a callable value");
638 
639   Module *M = Builder->GetInsertBlock()->getParent()->getParent();
640   // Fill in the one generic type'd argument (the function is also vararg)
641   Type *ArgTypes[] = { FuncPtrType };
642   Function *FnStatepoint =
643     Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_statepoint,
644                               ArgTypes);
645 
646   std::vector<Value *> Args =
647       getStatepointArgs(*Builder, ID, NumPatchBytes, ActualCallee, Flags,
648                         CallArgs, TransitionArgs, DeoptArgs, GCArgs);
649   return createCallHelper(FnStatepoint, Args, Builder, Name);
650 }
651 
652 CallInst *IRBuilderBase::CreateGCStatepointCall(
653     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
654     ArrayRef<Value *> CallArgs, ArrayRef<Value *> DeoptArgs,
655     ArrayRef<Value *> GCArgs, const Twine &Name) {
656   return CreateGCStatepointCallCommon<Value *, Value *, Value *, Value *>(
657       this, ID, NumPatchBytes, ActualCallee, uint32_t(StatepointFlags::None),
658       CallArgs, None /* No Transition Args */, DeoptArgs, GCArgs, Name);
659 }
660 
661 CallInst *IRBuilderBase::CreateGCStatepointCall(
662     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, uint32_t Flags,
663     ArrayRef<Use> CallArgs, ArrayRef<Use> TransitionArgs,
664     ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
665   return CreateGCStatepointCallCommon<Use, Use, Use, Value *>(
666       this, ID, NumPatchBytes, ActualCallee, Flags, CallArgs, TransitionArgs,
667       DeoptArgs, GCArgs, Name);
668 }
669 
670 CallInst *IRBuilderBase::CreateGCStatepointCall(
671     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
672     ArrayRef<Use> CallArgs, ArrayRef<Value *> DeoptArgs,
673     ArrayRef<Value *> GCArgs, const Twine &Name) {
674   return CreateGCStatepointCallCommon<Use, Value *, Value *, Value *>(
675       this, ID, NumPatchBytes, ActualCallee, uint32_t(StatepointFlags::None),
676       CallArgs, None, DeoptArgs, GCArgs, Name);
677 }
678 
679 template <typename T0, typename T1, typename T2, typename T3>
680 static InvokeInst *CreateGCStatepointInvokeCommon(
681     IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes,
682     Value *ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest,
683     uint32_t Flags, ArrayRef<T0> InvokeArgs, ArrayRef<T1> TransitionArgs,
684     ArrayRef<T2> DeoptArgs, ArrayRef<T3> GCArgs, const Twine &Name) {
685   // Extract out the type of the callee.
686   auto *FuncPtrType = cast<PointerType>(ActualInvokee->getType());
687   assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
688          "actual callee must be a callable value");
689 
690   Module *M = Builder->GetInsertBlock()->getParent()->getParent();
691   // Fill in the one generic type'd argument (the function is also vararg)
692   Function *FnStatepoint = Intrinsic::getDeclaration(
693       M, Intrinsic::experimental_gc_statepoint, {FuncPtrType});
694 
695   std::vector<Value *> Args =
696       getStatepointArgs(*Builder, ID, NumPatchBytes, ActualInvokee, Flags,
697                         InvokeArgs, TransitionArgs, DeoptArgs, GCArgs);
698   return createInvokeHelper(FnStatepoint, NormalDest, UnwindDest, Args, Builder,
699                             Name);
700 }
701 
702 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
703     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
704     BasicBlock *NormalDest, BasicBlock *UnwindDest,
705     ArrayRef<Value *> InvokeArgs, ArrayRef<Value *> DeoptArgs,
706     ArrayRef<Value *> GCArgs, const Twine &Name) {
707   return CreateGCStatepointInvokeCommon<Value *, Value *, Value *, Value *>(
708       this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest,
709       uint32_t(StatepointFlags::None), InvokeArgs, None /* No Transition Args*/,
710       DeoptArgs, GCArgs, Name);
711 }
712 
713 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
714     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
715     BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
716     ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
717     ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
718   return CreateGCStatepointInvokeCommon<Use, Use, Use, Value *>(
719       this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest, Flags,
720       InvokeArgs, TransitionArgs, DeoptArgs, GCArgs, Name);
721 }
722 
723 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
724     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
725     BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
726     ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
727   return CreateGCStatepointInvokeCommon<Use, Value *, Value *, Value *>(
728       this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest,
729       uint32_t(StatepointFlags::None), InvokeArgs, None, DeoptArgs, GCArgs,
730       Name);
731 }
732 
733 CallInst *IRBuilderBase::CreateGCResult(Instruction *Statepoint,
734                                        Type *ResultType,
735                                        const Twine &Name) {
736  Intrinsic::ID ID = Intrinsic::experimental_gc_result;
737  Module *M = BB->getParent()->getParent();
738  Type *Types[] = {ResultType};
739  Function *FnGCResult = Intrinsic::getDeclaration(M, ID, Types);
740 
741  Value *Args[] = {Statepoint};
742  return createCallHelper(FnGCResult, Args, this, Name);
743 }
744 
745 CallInst *IRBuilderBase::CreateGCRelocate(Instruction *Statepoint,
746                                          int BaseOffset,
747                                          int DerivedOffset,
748                                          Type *ResultType,
749                                          const Twine &Name) {
750  Module *M = BB->getParent()->getParent();
751  Type *Types[] = {ResultType};
752  Function *FnGCRelocate =
753      Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
754 
755  Value *Args[] = {Statepoint,
756                   getInt32(BaseOffset),
757                   getInt32(DerivedOffset)};
758  return createCallHelper(FnGCRelocate, Args, this, Name);
759 }
760 
761 CallInst *IRBuilderBase::CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V,
762                                               Instruction *FMFSource,
763                                               const Twine &Name) {
764   Module *M = BB->getModule();
765   Function *Fn = Intrinsic::getDeclaration(M, ID, {V->getType()});
766   return createCallHelper(Fn, {V}, this, Name, FMFSource);
767 }
768 
769 CallInst *IRBuilderBase::CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS,
770                                                Value *RHS,
771                                                Instruction *FMFSource,
772                                                const Twine &Name) {
773   Module *M = BB->getModule();
774   Function *Fn = Intrinsic::getDeclaration(M, ID, { LHS->getType() });
775   return createCallHelper(Fn, {LHS, RHS}, this, Name, FMFSource);
776 }
777 
778 CallInst *IRBuilderBase::CreateIntrinsic(Intrinsic::ID ID,
779                                          ArrayRef<Type *> Types,
780                                          ArrayRef<Value *> Args,
781                                          Instruction *FMFSource,
782                                          const Twine &Name) {
783   Module *M = BB->getModule();
784   Function *Fn = Intrinsic::getDeclaration(M, ID, Types);
785   return createCallHelper(Fn, Args, this, Name, FMFSource);
786 }
787