b1f4354f484ce1378ad5b0b7fd1a3d3372d4bb8c
[oota-llvm.git] / include / llvm / Support / IRBuilder.h
1 //===---- llvm/Support/IRBuilder.h - Builder for LLVM Instrs ----*- C++ -*-===//
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 defines 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 #ifndef LLVM_SUPPORT_IRBUILDER_H
16 #define LLVM_SUPPORT_IRBUILDER_H
17
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/GlobalAlias.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Function.h"
23 #include "llvm/Metadata.h"
24 #include "llvm/LLVMContext.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/ConstantFolder.h"
27
28 namespace llvm {
29
30 /// IRBuilderDefaultInserter - This provides the default implementation of the
31 /// IRBuilder 'InsertHelper' method that is called whenever an instruction is
32 /// created by IRBuilder and needs to be inserted.  By default, this inserts the
33 /// instruction at the insertion point.
34 template <bool preserveNames = true>
35 class IRBuilderDefaultInserter {
36 protected:
37   void InsertHelper(Instruction *I, const Twine &Name,
38                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
39     if (BB) BB->getInstList().insert(InsertPt, I);
40     if (preserveNames)
41       I->setName(Name);
42   }
43 };
44   
45   
46 /// IRBuilder - This provides a uniform API for creating instructions and
47 /// inserting them into a basic block: either at the end of a BasicBlock, or
48 /// at a specific iterator location in a block.
49 ///
50 /// Note that the builder does not expose the full generality of LLVM
51 /// instructions.  For access to extra instruction properties, use the mutators
52 /// (e.g. setVolatile) on the instructions after they have been created.
53 /// The first template argument handles whether or not to preserve names in the
54 /// final instruction output. This defaults to on.  The second template argument
55 /// specifies a class to use for creating constants.  This defaults to creating
56 /// minimally folded constants.  The fourth template argument allows clients to
57 /// specify custom insertion hooks that are called on every newly created
58 /// insertion.
59 template<bool preserveNames = true, typename T = ConstantFolder,
60          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
61 class IRBuilder : public Inserter {
62   BasicBlock *BB;
63   BasicBlock::iterator InsertPt;
64   MDKindID MDKind;
65   MDNode *CurLocation;
66   LLVMContext &Context;
67   T Folder;
68 public:
69   IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter())
70     : Inserter(I), MDKind(0), CurLocation(0), Context(C), Folder(F) {
71     ClearInsertionPoint(); 
72   }
73   
74   explicit IRBuilder(LLVMContext &C) 
75     : MDKind(0), CurLocation(0), Context(C), Folder(C) {
76     ClearInsertionPoint();
77   }
78   
79   explicit IRBuilder(BasicBlock *TheBB, const T &F)
80     : MDKind(0), CurLocation(0), Context(TheBB->getContext()), Folder(F) {
81     SetInsertPoint(TheBB);
82   }
83   
84   explicit IRBuilder(BasicBlock *TheBB)
85     : MDKind(0), CurLocation(0), Context(TheBB->getContext()), Folder(Context) {
86     SetInsertPoint(TheBB);
87   }
88   
89   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F)
90     : MDKind(0), CurLocation(0), Context(TheBB->getContext()), Folder(F) {
91     SetInsertPoint(TheBB, IP);
92   }
93   
94   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP)
95     : MDKind(0), CurLocation(0), Context(TheBB->getContext()), Folder(Context) {
96     SetInsertPoint(TheBB, IP);
97   }
98
99   /// getFolder - Get the constant folder being used.
100   const T &getFolder() { return Folder; }
101
102   /// isNamePreserving - Return true if this builder is configured to actually
103   /// add the requested names to IR created through it.
104   bool isNamePreserving() const { return preserveNames; }
105   
106   //===--------------------------------------------------------------------===//
107   // Builder configuration methods
108   //===--------------------------------------------------------------------===//
109
110   /// ClearInsertionPoint - Clear the insertion point: created instructions will
111   /// not be inserted into a block.
112   void ClearInsertionPoint() {
113     BB = 0;
114   }
115
116   BasicBlock *GetInsertBlock() const { return BB; }
117
118   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
119
120   /// SetInsertPoint - This specifies that created instructions should be
121   /// appended to the end of the specified block.
122   void SetInsertPoint(BasicBlock *TheBB) {
123     BB = TheBB;
124     InsertPt = BB->end();
125   }
126
127   /// SetInsertPoint - This specifies that created instructions should be
128   /// inserted at the specified point.
129   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
130     BB = TheBB;
131     InsertPt = IP;
132   }
133
134   /// SetCurrentLocation - This specifies the location information used
135   /// by debugging information.
136   void SetCurrentLocation(MDNode *L) {
137     if (MDKind == 0) {
138       Context.getMetadata().RegisterMDKind("dbg");
139       MDKind = Context.getMetadata().getMDKind("dbg");
140     }
141     CurLocation = L;
142   }
143
144   MDNode *getCurrentLocation() const { return CurLocation; }
145   
146   /// Insert - Insert and return the specified instruction.
147   template<typename InstTy>
148   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
149     this->InsertHelper(I, Name, BB, InsertPt);
150     if (CurLocation)
151       Context.getMetadata().setMD(MDKind, CurLocation, I);
152     return I;
153   }
154
155   //===--------------------------------------------------------------------===//
156   // Type creation methods
157   //===--------------------------------------------------------------------===//
158
159   /// getInt1Ty - Fetch the type representing a single bit
160   const Type *getInt1Ty() {
161     return Type::getInt1Ty(Context);
162   }
163   
164   /// getInt8Ty - Fetch the type representing an 8-bit integer.
165   const Type *getInt8Ty() {
166     return Type::getInt8Ty(Context);
167   }
168   
169   /// getInt16Ty - Fetch the type representing a 16-bit integer.
170   const Type *getInt16Ty() {
171     return Type::getInt16Ty(Context);
172   }
173   
174   /// getInt32Ty - Fetch the type resepresenting a 32-bit integer.
175   const Type *getInt32Ty() {
176     return Type::getInt32Ty(Context);
177   }
178   
179   /// getInt64Ty - Fetch the type representing a 64-bit integer.
180   const Type *getInt64Ty() {
181     return Type::getInt64Ty(Context);
182   }
183
184   /// getFloatTy - Fetch the type representing a 32-bit floating point value.
185   const Type *getFloatTy() {
186     return Type::getFloatTy(Context);
187   }
188   
189   /// getDoubleTy - Fetch the type representing a 64-bit floating point value.
190   const Type *getDoubleTy() {
191     return Type::getDoubleTy(Context);
192   }
193   
194   /// getVoidTy - Fetch the type representing void.
195   const Type *getVoidTy() {
196     return Type::getVoidTy(Context);
197   }
198
199   //===--------------------------------------------------------------------===//
200   // Instruction creation methods: Terminators
201   //===--------------------------------------------------------------------===//
202
203   /// CreateRetVoid - Create a 'ret void' instruction.
204   ReturnInst *CreateRetVoid() {
205     return Insert(ReturnInst::Create(Context));
206   }
207
208   /// @verbatim
209   /// CreateRet - Create a 'ret <val>' instruction.
210   /// @endverbatim
211   ReturnInst *CreateRet(Value *V) {
212     return Insert(ReturnInst::Create(Context, V));
213   }
214
215   /// CreateAggregateRet - Create a sequence of N insertvalue instructions,
216   /// with one Value from the retVals array each, that build a aggregate
217   /// return value one value at a time, and a ret instruction to return
218   /// the resulting aggregate value. This is a convenience function for
219   /// code that uses aggregate return values as a vehicle for having
220   /// multiple return values.
221   ///
222   ReturnInst *CreateAggregateRet(Value * const* retVals, unsigned N) {
223     const Type *RetType = BB->getParent()->getReturnType();
224     Value *V = UndefValue::get(RetType);
225     for (unsigned i = 0; i != N; ++i)
226       V = CreateInsertValue(V, retVals[i], i, "mrv");
227     return Insert(ReturnInst::Create(Context, V));
228   }
229
230   /// CreateBr - Create an unconditional 'br label X' instruction.
231   BranchInst *CreateBr(BasicBlock *Dest) {
232     return Insert(BranchInst::Create(Dest));
233   }
234
235   /// CreateCondBr - Create a conditional 'br Cond, TrueDest, FalseDest'
236   /// instruction.
237   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False) {
238     return Insert(BranchInst::Create(True, False, Cond));
239   }
240
241   /// CreateSwitch - Create a switch instruction with the specified value,
242   /// default dest, and with a hint for the number of cases that will be added
243   /// (for efficient allocation).
244   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10) {
245     return Insert(SwitchInst::Create(V, Dest, NumCases));
246   }
247
248   /// CreateInvoke - Create an invoke instruction.
249   template<typename InputIterator>
250   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
251                            BasicBlock *UnwindDest, InputIterator ArgBegin,
252                            InputIterator ArgEnd, const Twine &Name = "") {
253     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest,
254                                      ArgBegin, ArgEnd), Name);
255   }
256
257   UnwindInst *CreateUnwind() {
258     return Insert(new UnwindInst(Context));
259   }
260
261   UnreachableInst *CreateUnreachable() {
262     return Insert(new UnreachableInst(Context));
263   }
264
265   //===--------------------------------------------------------------------===//
266   // Instruction creation methods: Binary Operators
267   //===--------------------------------------------------------------------===//
268
269   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
270     if (Constant *LC = dyn_cast<Constant>(LHS))
271       if (Constant *RC = dyn_cast<Constant>(RHS))
272         return Folder.CreateAdd(LC, RC);
273     return Insert(BinaryOperator::CreateAdd(LHS, RHS), Name);
274   }
275   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
276     if (Constant *LC = dyn_cast<Constant>(LHS))
277       if (Constant *RC = dyn_cast<Constant>(RHS))
278         return Folder.CreateNSWAdd(LC, RC);
279     return Insert(BinaryOperator::CreateNSWAdd(LHS, RHS), Name);
280   }
281   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
282     if (Constant *LC = dyn_cast<Constant>(LHS))
283       if (Constant *RC = dyn_cast<Constant>(RHS))
284         return Folder.CreateFAdd(LC, RC);
285     return Insert(BinaryOperator::CreateFAdd(LHS, RHS), Name);
286   }
287   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "") {
288     if (Constant *LC = dyn_cast<Constant>(LHS))
289       if (Constant *RC = dyn_cast<Constant>(RHS))
290         return Folder.CreateSub(LC, RC);
291     return Insert(BinaryOperator::CreateSub(LHS, RHS), Name);
292   }
293   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "") {
294     if (Constant *LC = dyn_cast<Constant>(LHS))
295       if (Constant *RC = dyn_cast<Constant>(RHS))
296         return Folder.CreateFSub(LC, RC);
297     return Insert(BinaryOperator::CreateFSub(LHS, RHS), Name);
298   }
299   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "") {
300     if (Constant *LC = dyn_cast<Constant>(LHS))
301       if (Constant *RC = dyn_cast<Constant>(RHS))
302         return Folder.CreateMul(LC, RC);
303     return Insert(BinaryOperator::CreateMul(LHS, RHS), Name);
304   }
305   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "") {
306     if (Constant *LC = dyn_cast<Constant>(LHS))
307       if (Constant *RC = dyn_cast<Constant>(RHS))
308         return Folder.CreateFMul(LC, RC);
309     return Insert(BinaryOperator::CreateFMul(LHS, RHS), Name);
310   }
311   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
312     if (Constant *LC = dyn_cast<Constant>(LHS))
313       if (Constant *RC = dyn_cast<Constant>(RHS))
314         return Folder.CreateUDiv(LC, RC);
315     return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
316   }
317   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
318     if (Constant *LC = dyn_cast<Constant>(LHS))
319       if (Constant *RC = dyn_cast<Constant>(RHS))
320         return Folder.CreateSDiv(LC, RC);
321     return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
322   }
323   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
324     if (Constant *LC = dyn_cast<Constant>(LHS))
325       if (Constant *RC = dyn_cast<Constant>(RHS))
326         return Folder.CreateExactSDiv(LC, RC);
327     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
328   }
329   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
330     if (Constant *LC = dyn_cast<Constant>(LHS))
331       if (Constant *RC = dyn_cast<Constant>(RHS))
332         return Folder.CreateFDiv(LC, RC);
333     return Insert(BinaryOperator::CreateFDiv(LHS, RHS), Name);
334   }
335   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
336     if (Constant *LC = dyn_cast<Constant>(LHS))
337       if (Constant *RC = dyn_cast<Constant>(RHS))
338         return Folder.CreateURem(LC, RC);
339     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
340   }
341   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
342     if (Constant *LC = dyn_cast<Constant>(LHS))
343       if (Constant *RC = dyn_cast<Constant>(RHS))
344         return Folder.CreateSRem(LC, RC);
345     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
346   }
347   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "") {
348     if (Constant *LC = dyn_cast<Constant>(LHS))
349       if (Constant *RC = dyn_cast<Constant>(RHS))
350         return Folder.CreateFRem(LC, RC);
351     return Insert(BinaryOperator::CreateFRem(LHS, RHS), Name);
352   }
353   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "") {
354     if (Constant *LC = dyn_cast<Constant>(LHS))
355       if (Constant *RC = dyn_cast<Constant>(RHS))
356         return Folder.CreateShl(LC, RC);
357     return Insert(BinaryOperator::CreateShl(LHS, RHS), Name);
358   }
359   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "") {
360     if (Constant *LC = dyn_cast<Constant>(LHS))
361       if (Constant *RC = dyn_cast<Constant>(RHS))
362         return Folder.CreateLShr(LC, RC);
363     return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
364   }
365   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "") {
366     if (Constant *LC = dyn_cast<Constant>(LHS))
367       if (Constant *RC = dyn_cast<Constant>(RHS))
368         return Folder.CreateAShr(LC, RC);
369     return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
370   }
371   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
372     if (Constant *LC = dyn_cast<Constant>(LHS))
373       if (Constant *RC = dyn_cast<Constant>(RHS))
374         return Folder.CreateAnd(LC, RC);
375     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
376   }
377   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
378     if (Constant *LC = dyn_cast<Constant>(LHS))
379       if (Constant *RC = dyn_cast<Constant>(RHS))
380         return Folder.CreateOr(LC, RC);
381     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
382   }
383   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
384     if (Constant *LC = dyn_cast<Constant>(LHS))
385       if (Constant *RC = dyn_cast<Constant>(RHS))
386         return Folder.CreateXor(LC, RC);
387     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
388   }
389
390   Value *CreateBinOp(Instruction::BinaryOps Opc,
391                      Value *LHS, Value *RHS, const Twine &Name = "") {
392     if (Constant *LC = dyn_cast<Constant>(LHS))
393       if (Constant *RC = dyn_cast<Constant>(RHS))
394         return Folder.CreateBinOp(Opc, LC, RC);
395     return Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
396   }
397
398   Value *CreateNeg(Value *V, const Twine &Name = "") {
399     if (Constant *VC = dyn_cast<Constant>(V))
400       return Folder.CreateNeg(VC);
401     return Insert(BinaryOperator::CreateNeg(V), Name);
402   }
403   Value *CreateFNeg(Value *V, const Twine &Name = "") {
404     if (Constant *VC = dyn_cast<Constant>(V))
405       return Folder.CreateFNeg(VC);
406     return Insert(BinaryOperator::CreateFNeg(V), Name);
407   }
408   Value *CreateNot(Value *V, const Twine &Name = "") {
409     if (Constant *VC = dyn_cast<Constant>(V))
410       return Folder.CreateNot(VC);
411     return Insert(BinaryOperator::CreateNot(V), Name);
412   }
413
414   //===--------------------------------------------------------------------===//
415   // Instruction creation methods: Memory Instructions
416   //===--------------------------------------------------------------------===//
417
418   MallocInst *CreateMalloc(const Type *Ty, Value *ArraySize = 0,
419                            const Twine &Name = "") {
420     return Insert(new MallocInst(Ty, ArraySize), Name);
421   }
422   AllocaInst *CreateAlloca(const Type *Ty, Value *ArraySize = 0,
423                            const Twine &Name = "") {
424     return Insert(new AllocaInst(Ty, ArraySize), Name);
425   }
426   FreeInst *CreateFree(Value *Ptr) {
427     return Insert(new FreeInst(Ptr));
428   }
429   // Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
430   // converting the string to 'bool' for the isVolatile parameter.
431   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
432     return Insert(new LoadInst(Ptr), Name);
433   }
434   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
435     return Insert(new LoadInst(Ptr), Name);
436   }
437   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
438     return Insert(new LoadInst(Ptr, 0, isVolatile), Name);
439   }
440   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
441     return Insert(new StoreInst(Val, Ptr, isVolatile));
442   }
443   template<typename InputIterator>
444   Value *CreateGEP(Value *Ptr, InputIterator IdxBegin, InputIterator IdxEnd,
445                    const Twine &Name = "") {
446     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
447       // Every index must be constant.
448       InputIterator i;
449       for (i = IdxBegin; i < IdxEnd; ++i)
450         if (!isa<Constant>(*i))
451           break;
452       if (i == IdxEnd)
453         return Folder.CreateGetElementPtr(PC, &IdxBegin[0], IdxEnd - IdxBegin);
454     }
455     return Insert(GetElementPtrInst::Create(Ptr, IdxBegin, IdxEnd), Name);
456   }
457   template<typename InputIterator>
458   Value *CreateInBoundsGEP(Value *Ptr, InputIterator IdxBegin, InputIterator IdxEnd,
459                            const Twine &Name = "") {
460     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
461       // Every index must be constant.
462       InputIterator i;
463       for (i = IdxBegin; i < IdxEnd; ++i)
464         if (!isa<Constant>(*i))
465           break;
466       if (i == IdxEnd)
467         return Folder.CreateInBoundsGetElementPtr(PC,
468                                                   &IdxBegin[0],
469                                                   IdxEnd - IdxBegin);
470     }
471     return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxBegin, IdxEnd),
472                   Name);
473   }
474   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
475     if (Constant *PC = dyn_cast<Constant>(Ptr))
476       if (Constant *IC = dyn_cast<Constant>(Idx))
477         return Folder.CreateGetElementPtr(PC, &IC, 1);
478     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
479   }
480   Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
481     if (Constant *PC = dyn_cast<Constant>(Ptr))
482       if (Constant *IC = dyn_cast<Constant>(Idx))
483         return Folder.CreateInBoundsGetElementPtr(PC, &IC, 1);
484     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
485   }
486   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
487     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
488
489     if (Constant *PC = dyn_cast<Constant>(Ptr))
490       return Folder.CreateGetElementPtr(PC, &Idx, 1);
491
492     return Insert(GetElementPtrInst::Create(Ptr, &Idx, &Idx+1), Name);    
493   }
494   Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
495                                     const Twine &Name = "") {
496     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
497
498     if (Constant *PC = dyn_cast<Constant>(Ptr))
499       return Folder.CreateInBoundsGetElementPtr(PC, &Idx, 1);
500
501     return Insert(GetElementPtrInst::CreateInBounds(Ptr, &Idx, &Idx+1), Name);
502   }
503   Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1, 
504                     const Twine &Name = "") {
505     Value *Idxs[] = {
506       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
507       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
508     };
509
510     if (Constant *PC = dyn_cast<Constant>(Ptr))
511       return Folder.CreateGetElementPtr(PC, Idxs, 2);
512
513     return Insert(GetElementPtrInst::Create(Ptr, Idxs, Idxs+2), Name);    
514   }
515   Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
516                                     const Twine &Name = "") {
517     Value *Idxs[] = {
518       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
519       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
520     };
521
522     if (Constant *PC = dyn_cast<Constant>(Ptr))
523       return Folder.CreateInBoundsGetElementPtr(PC, Idxs, 2);
524
525     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs, Idxs+2), Name);
526   }
527   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
528     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
529
530     if (Constant *PC = dyn_cast<Constant>(Ptr))
531       return Folder.CreateGetElementPtr(PC, &Idx, 1);
532
533     return Insert(GetElementPtrInst::Create(Ptr, &Idx, &Idx+1), Name);    
534   }
535   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
536                                     const Twine &Name = "") {
537     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
538
539     if (Constant *PC = dyn_cast<Constant>(Ptr))
540       return Folder.CreateInBoundsGetElementPtr(PC, &Idx, 1);
541
542     return Insert(GetElementPtrInst::CreateInBounds(Ptr, &Idx, &Idx+1), Name);
543   }
544   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
545                     const Twine &Name = "") {
546     Value *Idxs[] = {
547       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
548       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
549     };
550
551     if (Constant *PC = dyn_cast<Constant>(Ptr))
552       return Folder.CreateGetElementPtr(PC, Idxs, 2);
553
554     return Insert(GetElementPtrInst::Create(Ptr, Idxs, Idxs+2), Name);    
555   }
556   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
557                                     const Twine &Name = "") {
558     Value *Idxs[] = {
559       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
560       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
561     };
562
563     if (Constant *PC = dyn_cast<Constant>(Ptr))
564       return Folder.CreateInBoundsGetElementPtr(PC, Idxs, 2);
565
566     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs, Idxs+2), Name);
567   }
568   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
569     return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
570   }
571   Value *CreateGlobalString(const char *Str = "", const Twine &Name = "") {
572     Constant *StrConstant = ConstantArray::get(Context, Str, true);
573     Module &M = *BB->getParent()->getParent();
574     GlobalVariable *gv = new GlobalVariable(M,
575                                             StrConstant->getType(),
576                                             true,
577                                             GlobalValue::InternalLinkage,
578                                             StrConstant,
579                                             "",
580                                             0,
581                                             false);
582     gv->setName(Name);
583     return gv;
584   }
585   Value *CreateGlobalStringPtr(const char *Str = "", const Twine &Name = "") {
586     Value *gv = CreateGlobalString(Str, Name);
587     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
588     Value *Args[] = { zero, zero };
589     return CreateInBoundsGEP(gv, Args, Args+2, Name);
590   }
591   //===--------------------------------------------------------------------===//
592   // Instruction creation methods: Cast/Conversion Operators
593   //===--------------------------------------------------------------------===//
594
595   Value *CreateTrunc(Value *V, const Type *DestTy, const Twine &Name = "") {
596     return CreateCast(Instruction::Trunc, V, DestTy, Name);
597   }
598   Value *CreateZExt(Value *V, const Type *DestTy, const Twine &Name = "") {
599     return CreateCast(Instruction::ZExt, V, DestTy, Name);
600   }
601   Value *CreateSExt(Value *V, const Type *DestTy, const Twine &Name = "") {
602     return CreateCast(Instruction::SExt, V, DestTy, Name);
603   }
604   Value *CreateFPToUI(Value *V, const Type *DestTy, const Twine &Name = ""){
605     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
606   }
607   Value *CreateFPToSI(Value *V, const Type *DestTy, const Twine &Name = ""){
608     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
609   }
610   Value *CreateUIToFP(Value *V, const Type *DestTy, const Twine &Name = ""){
611     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
612   }
613   Value *CreateSIToFP(Value *V, const Type *DestTy, const Twine &Name = ""){
614     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
615   }
616   Value *CreateFPTrunc(Value *V, const Type *DestTy,
617                        const Twine &Name = "") {
618     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
619   }
620   Value *CreateFPExt(Value *V, const Type *DestTy, const Twine &Name = "") {
621     return CreateCast(Instruction::FPExt, V, DestTy, Name);
622   }
623   Value *CreatePtrToInt(Value *V, const Type *DestTy,
624                         const Twine &Name = "") {
625     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
626   }
627   Value *CreateIntToPtr(Value *V, const Type *DestTy,
628                         const Twine &Name = "") {
629     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
630   }
631   Value *CreateBitCast(Value *V, const Type *DestTy,
632                        const Twine &Name = "") {
633     return CreateCast(Instruction::BitCast, V, DestTy, Name);
634   }
635   Value *CreateZExtOrBitCast(Value *V, const Type *DestTy,
636                              const Twine &Name = "") {
637     if (V->getType() == DestTy)
638       return V;
639     if (Constant *VC = dyn_cast<Constant>(V))
640       return Folder.CreateZExtOrBitCast(VC, DestTy);
641     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
642   }
643   Value *CreateSExtOrBitCast(Value *V, const Type *DestTy,
644                              const Twine &Name = "") {
645     if (V->getType() == DestTy)
646       return V;
647     if (Constant *VC = dyn_cast<Constant>(V))
648       return Folder.CreateSExtOrBitCast(VC, DestTy);
649     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
650   }
651   Value *CreateTruncOrBitCast(Value *V, const Type *DestTy,
652                               const Twine &Name = "") {
653     if (V->getType() == DestTy)
654       return V;
655     if (Constant *VC = dyn_cast<Constant>(V))
656       return Folder.CreateTruncOrBitCast(VC, DestTy);
657     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
658   }
659   Value *CreateCast(Instruction::CastOps Op, Value *V, const Type *DestTy,
660                     const Twine &Name = "") {
661     if (V->getType() == DestTy)
662       return V;
663     if (Constant *VC = dyn_cast<Constant>(V))
664       return Folder.CreateCast(Op, VC, DestTy);
665     return Insert(CastInst::Create(Op, V, DestTy), Name);
666   }
667   Value *CreatePointerCast(Value *V, const Type *DestTy,
668                            const Twine &Name = "") {
669     if (V->getType() == DestTy)
670       return V;
671     if (Constant *VC = dyn_cast<Constant>(V))
672       return Folder.CreatePointerCast(VC, DestTy);
673     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
674   }
675   Value *CreateIntCast(Value *V, const Type *DestTy, bool isSigned,
676                        const Twine &Name = "") {
677     if (V->getType() == DestTy)
678       return V;
679     if (Constant *VC = dyn_cast<Constant>(V))
680       return Folder.CreateIntCast(VC, DestTy, isSigned);
681     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
682   }
683   Value *CreateFPCast(Value *V, const Type *DestTy, const Twine &Name = "") {
684     if (V->getType() == DestTy)
685       return V;
686     if (Constant *VC = dyn_cast<Constant>(V))
687       return Folder.CreateFPCast(VC, DestTy);
688     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
689   }
690
691   //===--------------------------------------------------------------------===//
692   // Instruction creation methods: Compare Instructions
693   //===--------------------------------------------------------------------===//
694
695   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
696     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
697   }
698   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
699     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
700   }
701   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
702     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
703   }
704   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
705     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
706   }
707   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
708     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
709   }
710   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
711     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
712   }
713   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
714     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
715   }
716   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
717     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
718   }
719   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
720     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
721   }
722   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
723     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
724   }
725
726   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
727     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
728   }
729   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
730     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
731   }
732   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
733     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
734   }
735   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
736     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
737   }
738   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
739     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
740   }
741   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
742     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
743   }
744   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
745     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
746   }
747   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
748     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
749   }
750   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
751     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
752   }
753   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
754     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
755   }
756   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
757     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
758   }
759   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
760     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
761   }
762   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
763     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
764   }
765   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
766     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
767   }
768
769   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
770                     const Twine &Name = "") {
771     if (Constant *LC = dyn_cast<Constant>(LHS))
772       if (Constant *RC = dyn_cast<Constant>(RHS))
773         return Folder.CreateICmp(P, LC, RC);
774     return Insert(new ICmpInst(P, LHS, RHS), Name);
775   }
776   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
777                     const Twine &Name = "") {
778     if (Constant *LC = dyn_cast<Constant>(LHS))
779       if (Constant *RC = dyn_cast<Constant>(RHS))
780         return Folder.CreateFCmp(P, LC, RC);
781     return Insert(new FCmpInst(P, LHS, RHS), Name);
782   }
783
784   //===--------------------------------------------------------------------===//
785   // Instruction creation methods: Other Instructions
786   //===--------------------------------------------------------------------===//
787
788   PHINode *CreatePHI(const Type *Ty, const Twine &Name = "") {
789     return Insert(PHINode::Create(Ty), Name);
790   }
791
792   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
793     return Insert(CallInst::Create(Callee), Name);
794   }
795   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
796     return Insert(CallInst::Create(Callee, Arg), Name);
797   }
798   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
799                         const Twine &Name = "") {
800     Value *Args[] = { Arg1, Arg2 };
801     return Insert(CallInst::Create(Callee, Args, Args+2), Name);
802   }
803   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
804                         const Twine &Name = "") {
805     Value *Args[] = { Arg1, Arg2, Arg3 };
806     return Insert(CallInst::Create(Callee, Args, Args+3), Name);
807   }
808   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
809                         Value *Arg4, const Twine &Name = "") {
810     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
811     return Insert(CallInst::Create(Callee, Args, Args+4), Name);
812   }
813
814   template<typename InputIterator>
815   CallInst *CreateCall(Value *Callee, InputIterator ArgBegin,
816                        InputIterator ArgEnd, const Twine &Name = "") {
817     return Insert(CallInst::Create(Callee, ArgBegin, ArgEnd), Name);
818   }
819
820   Value *CreateSelect(Value *C, Value *True, Value *False,
821                       const Twine &Name = "") {
822     if (Constant *CC = dyn_cast<Constant>(C))
823       if (Constant *TC = dyn_cast<Constant>(True))
824         if (Constant *FC = dyn_cast<Constant>(False))
825           return Folder.CreateSelect(CC, TC, FC);
826     return Insert(SelectInst::Create(C, True, False), Name);
827   }
828
829   VAArgInst *CreateVAArg(Value *List, const Type *Ty, const Twine &Name = "") {
830     return Insert(new VAArgInst(List, Ty), Name);
831   }
832
833   Value *CreateExtractElement(Value *Vec, Value *Idx,
834                               const Twine &Name = "") {
835     if (Constant *VC = dyn_cast<Constant>(Vec))
836       if (Constant *IC = dyn_cast<Constant>(Idx))
837         return Folder.CreateExtractElement(VC, IC);
838     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
839   }
840
841   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
842                              const Twine &Name = "") {
843     if (Constant *VC = dyn_cast<Constant>(Vec))
844       if (Constant *NC = dyn_cast<Constant>(NewElt))
845         if (Constant *IC = dyn_cast<Constant>(Idx))
846           return Folder.CreateInsertElement(VC, NC, IC);
847     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
848   }
849
850   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
851                              const Twine &Name = "") {
852     if (Constant *V1C = dyn_cast<Constant>(V1))
853       if (Constant *V2C = dyn_cast<Constant>(V2))
854         if (Constant *MC = dyn_cast<Constant>(Mask))
855           return Folder.CreateShuffleVector(V1C, V2C, MC);
856     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
857   }
858
859   Value *CreateExtractValue(Value *Agg, unsigned Idx,
860                             const Twine &Name = "") {
861     if (Constant *AggC = dyn_cast<Constant>(Agg))
862       return Folder.CreateExtractValue(AggC, &Idx, 1);
863     return Insert(ExtractValueInst::Create(Agg, Idx), Name);
864   }
865
866   template<typename InputIterator>
867   Value *CreateExtractValue(Value *Agg,
868                             InputIterator IdxBegin,
869                             InputIterator IdxEnd,
870                             const Twine &Name = "") {
871     if (Constant *AggC = dyn_cast<Constant>(Agg))
872       return Folder.CreateExtractValue(AggC, IdxBegin, IdxEnd - IdxBegin);
873     return Insert(ExtractValueInst::Create(Agg, IdxBegin, IdxEnd), Name);
874   }
875
876   Value *CreateInsertValue(Value *Agg, Value *Val, unsigned Idx,
877                            const Twine &Name = "") {
878     if (Constant *AggC = dyn_cast<Constant>(Agg))
879       if (Constant *ValC = dyn_cast<Constant>(Val))
880         return Folder.CreateInsertValue(AggC, ValC, &Idx, 1);
881     return Insert(InsertValueInst::Create(Agg, Val, Idx), Name);
882   }
883
884   template<typename InputIterator>
885   Value *CreateInsertValue(Value *Agg, Value *Val,
886                            InputIterator IdxBegin,
887                            InputIterator IdxEnd,
888                            const Twine &Name = "") {
889     if (Constant *AggC = dyn_cast<Constant>(Agg))
890       if (Constant *ValC = dyn_cast<Constant>(Val))
891         return Folder.CreateInsertValue(AggC, ValC, IdxBegin, IdxEnd-IdxBegin);
892     return Insert(InsertValueInst::Create(Agg, Val, IdxBegin, IdxEnd), Name);
893   }
894
895   //===--------------------------------------------------------------------===//
896   // Utility creation methods
897   //===--------------------------------------------------------------------===//
898
899   /// CreateIsNull - Return an i1 value testing if \arg Arg is null.
900   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
901     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
902                         Name);
903   }
904
905   /// CreateIsNotNull - Return an i1 value testing if \arg Arg is not null.
906   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
907     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
908                         Name);
909   }
910
911   /// CreatePtrDiff - Return the i64 difference between two pointer values,
912   /// dividing out the size of the pointed-to objects.  This is intended to
913   /// implement C-style pointer subtraction. As such, the pointers must be
914   /// appropriately aligned for their element types and pointing into the
915   /// same object.
916   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
917     assert(LHS->getType() == RHS->getType() &&
918            "Pointer subtraction operand types must match!");
919     const PointerType *ArgType = cast<PointerType>(LHS->getType());
920     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
921     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
922     Value *Difference = CreateSub(LHS_int, RHS_int);
923     return CreateExactSDiv(Difference,
924                            ConstantExpr::getSizeOf(ArgType->getElementType()),
925                            Name);
926   }
927 };
928
929 }
930
931 #endif