Change memcpy/memset/memmove to have dest and source alignments.
[oota-llvm.git] / lib / IR / IRBuilder.cpp
1 //===---- IRBuilder.cpp - Builder for LLVM Instrs -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/Function.h"
16 #include "llvm/IR/GlobalVariable.h"
17 #include "llvm/IR/IRBuilder.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/Intrinsics.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Statepoint.h"
22 using namespace llvm;
23
24 /// CreateGlobalString - Make a new global variable with an initializer that
25 /// has array of i8 type filled in with the nul terminated string value
26 /// specified.  If Name is specified, it is the name of the global variable
27 /// created.
28 GlobalVariable *IRBuilderBase::CreateGlobalString(StringRef Str,
29                                                   const Twine &Name,
30                                                   unsigned AddressSpace) {
31   Constant *StrConstant = ConstantDataArray::getString(Context, Str);
32   Module &M = *BB->getParent()->getParent();
33   GlobalVariable *GV = new GlobalVariable(M, StrConstant->getType(),
34                                           true, GlobalValue::PrivateLinkage,
35                                           StrConstant, Name, nullptr,
36                                           GlobalVariable::NotThreadLocal,
37                                           AddressSpace);
38   GV->setUnnamedAddr(true);
39   return GV;
40 }
41
42 Type *IRBuilderBase::getCurrentFunctionReturnType() const {
43   assert(BB && BB->getParent() && "No current function!");
44   return BB->getParent()->getReturnType();
45 }
46
47 Value *IRBuilderBase::getCastedInt8PtrValue(Value *Ptr) {
48   PointerType *PT = cast<PointerType>(Ptr->getType());
49   if (PT->getElementType()->isIntegerTy(8))
50     return Ptr;
51   
52   // Otherwise, we need to insert a bitcast.
53   PT = getInt8PtrTy(PT->getAddressSpace());
54   BitCastInst *BCI = new BitCastInst(Ptr, PT, "");
55   BB->getInstList().insert(InsertPt, BCI);
56   SetInstDebugLocation(BCI);
57   return BCI;
58 }
59
60 static CallInst *createCallHelper(Value *Callee, ArrayRef<Value *> Ops,
61                                   IRBuilderBase *Builder,
62                                   const Twine& Name="") {
63   CallInst *CI = CallInst::Create(Callee, Ops, Name);
64   Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),CI);
65   Builder->SetInstDebugLocation(CI);
66   return CI;  
67 }
68
69 static InvokeInst *createInvokeHelper(Value *Invokee, BasicBlock *NormalDest,
70                                       BasicBlock *UnwindDest,
71                                       ArrayRef<Value *> Ops,
72                                       IRBuilderBase *Builder,
73                                       const Twine &Name = "") {
74   InvokeInst *II =
75       InvokeInst::Create(Invokee, NormalDest, UnwindDest, Ops, Name);
76   Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),
77                                                   II);
78   Builder->SetInstDebugLocation(II);
79   return II;
80 }
81
82 CallInst *IRBuilderBase::
83 CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned DstAlign,
84              bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag,
85              MDNode *NoAliasTag) {
86   Ptr = getCastedInt8PtrValue(Ptr);
87   Value *Ops[] = { Ptr, Val, Size, getInt1(isVolatile) };
88   Type *Tys[] = { Ptr->getType(), Size->getType() };
89   Module *M = BB->getParent()->getParent();
90   Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys);
91   
92   CallInst *CI = createCallHelper(TheFn, Ops, this);
93   
94   // Set the TBAA info if present.
95   if (TBAATag)
96     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
97
98   if (ScopeTag)
99     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
100  
101   if (NoAliasTag)
102     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
103
104   cast<MemSetInst>(CI)->setDestAlignment(DstAlign);
105  
106   return CI;
107 }
108
109 CallInst *IRBuilderBase::
110 CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned DstAlign,
111              IntegerAlignment SrcAlign,
112              bool isVolatile, MDNode *TBAATag, MDNode *TBAAStructTag,
113              MDNode *ScopeTag, MDNode *NoAliasTag) {
114   Dst = getCastedInt8PtrValue(Dst);
115   Src = getCastedInt8PtrValue(Src);
116
117   Value *Ops[] = { Dst, Src, Size, getInt1(isVolatile) };
118   Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
119   Module *M = BB->getParent()->getParent();
120   Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
121   
122   CallInst *CI = createCallHelper(TheFn, Ops, this);
123   
124   // Set the TBAA info if present.
125   if (TBAATag)
126     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
127
128   // Set the TBAA Struct info if present.
129   if (TBAAStructTag)
130     CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag);
131  
132   if (ScopeTag)
133     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
134  
135   if (NoAliasTag)
136     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
137
138   auto *MCI = cast<MemCpyInst>(CI);
139   MCI->setDestAlignment(DstAlign);
140   MCI->setSrcAlignment(SrcAlign);
141  
142   return CI;  
143 }
144
145 CallInst *IRBuilderBase::
146 CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned DstAlign,
147               IntegerAlignment SrcAlign,
148               bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag,
149               MDNode *NoAliasTag) {
150   Dst = getCastedInt8PtrValue(Dst);
151   Src = getCastedInt8PtrValue(Src);
152   
153   Value *Ops[] = { Dst, Src, Size, getInt1(isVolatile) };
154   Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
155   Module *M = BB->getParent()->getParent();
156   Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memmove, Tys);
157   
158   CallInst *CI = createCallHelper(TheFn, Ops, this);
159   
160   // Set the TBAA info if present.
161   if (TBAATag)
162     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
163  
164   if (ScopeTag)
165     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
166  
167   if (NoAliasTag)
168     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
169
170   auto *MMI = cast<MemMoveInst>(CI);
171   MMI->setDestAlignment(DstAlign);
172   MMI->setSrcAlignment(SrcAlign);
173  
174   return CI;  
175 }
176
177 CallInst *IRBuilderBase::CreateLifetimeStart(Value *Ptr, ConstantInt *Size) {
178   assert(isa<PointerType>(Ptr->getType()) &&
179          "lifetime.start only applies to pointers.");
180   Ptr = getCastedInt8PtrValue(Ptr);
181   if (!Size)
182     Size = getInt64(-1);
183   else
184     assert(Size->getType() == getInt64Ty() &&
185            "lifetime.start requires the size to be an i64");
186   Value *Ops[] = { Size, Ptr };
187   Module *M = BB->getParent()->getParent();
188   Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_start);
189   return createCallHelper(TheFn, Ops, this);
190 }
191
192 CallInst *IRBuilderBase::CreateLifetimeEnd(Value *Ptr, ConstantInt *Size) {
193   assert(isa<PointerType>(Ptr->getType()) &&
194          "lifetime.end only applies to pointers.");
195   Ptr = getCastedInt8PtrValue(Ptr);
196   if (!Size)
197     Size = getInt64(-1);
198   else
199     assert(Size->getType() == getInt64Ty() &&
200            "lifetime.end requires the size to be an i64");
201   Value *Ops[] = { Size, Ptr };
202   Module *M = BB->getParent()->getParent();
203   Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_end);
204   return createCallHelper(TheFn, Ops, this);
205 }
206
207 CallInst *IRBuilderBase::CreateAssumption(Value *Cond) {
208   assert(Cond->getType() == getInt1Ty() &&
209          "an assumption condition must be of type i1");
210
211   Value *Ops[] = { Cond };
212   Module *M = BB->getParent()->getParent();
213   Value *FnAssume = Intrinsic::getDeclaration(M, Intrinsic::assume);
214   return createCallHelper(FnAssume, Ops, this);
215 }
216
217 /// Create a call to a Masked Load intrinsic.
218 /// Ptr      - the base pointer for the load
219 /// Align    - alignment of the source location
220 /// Mask     - an vector of booleans which indicates what vector lanes should
221 ///            be accessed in memory
222 /// PassThru - a pass-through value that is used to fill the masked-off lanes
223 ///            of the result
224 /// Name     - name of the result variable
225 CallInst *IRBuilderBase::CreateMaskedLoad(Value *Ptr, unsigned Align,
226                                           Value *Mask, Value *PassThru,
227                                           const Twine &Name) {
228   assert(Ptr->getType()->isPointerTy() && "Ptr must be of pointer type");
229   // DataTy is the overloaded type
230   Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
231   assert(DataTy->isVectorTy() && "Ptr should point to a vector");
232   if (!PassThru)
233     PassThru = UndefValue::get(DataTy);
234   Value *Ops[] = { Ptr, getInt32(Align), Mask,  PassThru};
235   return CreateMaskedIntrinsic(Intrinsic::masked_load, Ops, DataTy, Name);
236 }
237
238 /// Create a call to a Masked Store intrinsic.
239 /// Val   - the data to be stored,
240 /// Ptr   - the base pointer for the store
241 /// Align - alignment of the destination location
242 /// Mask  - an vector of booleans which indicates what vector lanes should
243 ///         be accessed in memory
244 CallInst *IRBuilderBase::CreateMaskedStore(Value *Val, Value *Ptr,
245                                            unsigned Align, Value *Mask) {
246   Value *Ops[] = { Val, Ptr, getInt32(Align), Mask };
247   // Type of the data to be stored - the only one overloaded type
248   return CreateMaskedIntrinsic(Intrinsic::masked_store, Ops, Val->getType());
249 }
250
251 /// Create a call to a Masked intrinsic, with given intrinsic Id,
252 /// an array of operands - Ops, and one overloaded type - DataTy
253 CallInst *IRBuilderBase::CreateMaskedIntrinsic(Intrinsic::ID Id,
254                                                ArrayRef<Value *> Ops,
255                                                Type *DataTy,
256                                                const Twine &Name) {
257   Module *M = BB->getParent()->getParent();
258   Type *OverloadedTypes[] = { DataTy };
259   Value *TheFn = Intrinsic::getDeclaration(M, Id, OverloadedTypes);
260   return createCallHelper(TheFn, Ops, this, Name);
261 }
262
263 template <typename T0, typename T1, typename T2, typename T3>
264 static std::vector<Value *>
265 getStatepointArgs(IRBuilderBase &B, uint64_t ID, uint32_t NumPatchBytes,
266                   Value *ActualCallee, uint32_t Flags, ArrayRef<T0> CallArgs,
267                   ArrayRef<T1> TransitionArgs, ArrayRef<T2> DeoptArgs,
268                   ArrayRef<T3> GCArgs) {
269   std::vector<Value *> Args;
270   Args.push_back(B.getInt64(ID));
271   Args.push_back(B.getInt32(NumPatchBytes));
272   Args.push_back(ActualCallee);
273   Args.push_back(B.getInt32(CallArgs.size()));
274   Args.push_back(B.getInt32(Flags));
275   Args.insert(Args.end(), CallArgs.begin(), CallArgs.end());
276   Args.push_back(B.getInt32(TransitionArgs.size()));
277   Args.insert(Args.end(), TransitionArgs.begin(), TransitionArgs.end());
278   Args.push_back(B.getInt32(DeoptArgs.size()));
279   Args.insert(Args.end(), DeoptArgs.begin(), DeoptArgs.end());
280   Args.insert(Args.end(), GCArgs.begin(), GCArgs.end());
281
282   return Args;
283 }
284
285 template <typename T0, typename T1, typename T2, typename T3>
286 static CallInst *CreateGCStatepointCallCommon(
287     IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes,
288     Value *ActualCallee, uint32_t Flags, ArrayRef<T0> CallArgs,
289     ArrayRef<T1> TransitionArgs, ArrayRef<T2> DeoptArgs, ArrayRef<T3> GCArgs,
290     const Twine &Name) {
291   // Extract out the type of the callee.
292   PointerType *FuncPtrType = cast<PointerType>(ActualCallee->getType());
293   assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
294          "actual callee must be a callable value");
295
296   Module *M = Builder->GetInsertBlock()->getParent()->getParent();
297   // Fill in the one generic type'd argument (the function is also vararg)
298   Type *ArgTypes[] = { FuncPtrType };
299   Function *FnStatepoint =
300     Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_statepoint,
301                               ArgTypes);
302
303   std::vector<llvm::Value *> Args =
304       getStatepointArgs(*Builder, ID, NumPatchBytes, ActualCallee, Flags,
305                         CallArgs, TransitionArgs, DeoptArgs, GCArgs);
306   return createCallHelper(FnStatepoint, Args, Builder, Name);
307 }
308
309 CallInst *IRBuilderBase::CreateGCStatepointCall(
310     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
311     ArrayRef<Value *> CallArgs, ArrayRef<Value *> DeoptArgs,
312     ArrayRef<Value *> GCArgs, const Twine &Name) {
313   return CreateGCStatepointCallCommon<Value *, Value *, Value *, Value *>(
314       this, ID, NumPatchBytes, ActualCallee, uint32_t(StatepointFlags::None),
315       CallArgs, None /* No Transition Args */, DeoptArgs, GCArgs, Name);
316 }
317
318 CallInst *IRBuilderBase::CreateGCStatepointCall(
319     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, uint32_t Flags,
320     ArrayRef<Use> CallArgs, ArrayRef<Use> TransitionArgs,
321     ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
322   return CreateGCStatepointCallCommon<Use, Use, Use, Value *>(
323       this, ID, NumPatchBytes, ActualCallee, Flags, CallArgs, TransitionArgs,
324       DeoptArgs, GCArgs, Name);
325 }
326
327 CallInst *IRBuilderBase::CreateGCStatepointCall(
328     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
329     ArrayRef<Use> CallArgs, ArrayRef<Value *> DeoptArgs,
330     ArrayRef<Value *> GCArgs, const Twine &Name) {
331   return CreateGCStatepointCallCommon<Use, Value *, Value *, Value *>(
332       this, ID, NumPatchBytes, ActualCallee, uint32_t(StatepointFlags::None),
333       CallArgs, None, DeoptArgs, GCArgs, Name);
334 }
335
336 template <typename T0, typename T1, typename T2, typename T3>
337 static InvokeInst *CreateGCStatepointInvokeCommon(
338     IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes,
339     Value *ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest,
340     uint32_t Flags, ArrayRef<T0> InvokeArgs, ArrayRef<T1> TransitionArgs,
341     ArrayRef<T2> DeoptArgs, ArrayRef<T3> GCArgs, const Twine &Name) {
342   // Extract out the type of the callee.
343   PointerType *FuncPtrType = cast<PointerType>(ActualInvokee->getType());
344   assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
345          "actual callee must be a callable value");
346
347   Module *M = Builder->GetInsertBlock()->getParent()->getParent();
348   // Fill in the one generic type'd argument (the function is also vararg)
349   Function *FnStatepoint = Intrinsic::getDeclaration(
350       M, Intrinsic::experimental_gc_statepoint, {FuncPtrType});
351
352   std::vector<llvm::Value *> Args =
353       getStatepointArgs(*Builder, ID, NumPatchBytes, ActualInvokee, Flags,
354                         InvokeArgs, TransitionArgs, DeoptArgs, GCArgs);
355   return createInvokeHelper(FnStatepoint, NormalDest, UnwindDest, Args, Builder,
356                             Name);
357 }
358
359 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
360     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
361     BasicBlock *NormalDest, BasicBlock *UnwindDest,
362     ArrayRef<Value *> InvokeArgs, ArrayRef<Value *> DeoptArgs,
363     ArrayRef<Value *> GCArgs, const Twine &Name) {
364   return CreateGCStatepointInvokeCommon<Value *, Value *, Value *, Value *>(
365       this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest,
366       uint32_t(StatepointFlags::None), InvokeArgs, None /* No Transition Args*/,
367       DeoptArgs, GCArgs, Name);
368 }
369
370 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
371     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
372     BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
373     ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
374     ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
375   return CreateGCStatepointInvokeCommon<Use, Use, Use, Value *>(
376       this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest, Flags,
377       InvokeArgs, TransitionArgs, DeoptArgs, GCArgs, Name);
378 }
379
380 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
381     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
382     BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
383     ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
384   return CreateGCStatepointInvokeCommon<Use, Value *, Value *, Value *>(
385       this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest,
386       uint32_t(StatepointFlags::None), InvokeArgs, None, DeoptArgs, GCArgs,
387       Name);
388 }
389
390 CallInst *IRBuilderBase::CreateGCResult(Instruction *Statepoint,
391                                        Type *ResultType,
392                                        const Twine &Name) {
393  Intrinsic::ID ID = Intrinsic::experimental_gc_result;
394  Module *M = BB->getParent()->getParent();
395  Type *Types[] = {ResultType};
396  Value *FnGCResult = Intrinsic::getDeclaration(M, ID, Types);
397
398  Value *Args[] = {Statepoint};
399  return createCallHelper(FnGCResult, Args, this, Name);
400 }
401
402 CallInst *IRBuilderBase::CreateGCRelocate(Instruction *Statepoint,
403                                          int BaseOffset,
404                                          int DerivedOffset,
405                                          Type *ResultType,
406                                          const Twine &Name) {
407  Module *M = BB->getParent()->getParent();
408  Type *Types[] = {ResultType};
409  Value *FnGCRelocate =
410    Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
411
412  Value *Args[] = {Statepoint,
413                   getInt32(BaseOffset),
414                   getInt32(DerivedOffset)};
415  return createCallHelper(FnGCRelocate, Args, this, Name);
416 }