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