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