458f87a88f4b0086abaa61b77b92c4b48cd66cae
[oota-llvm.git] / include / llvm / IR / IRBuilder.h
1 //===---- llvm/IRBuilder.h - Builder for LLVM Instructions ------*- 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_IR_IRBUILDER_H
16 #define LLVM_IR_IRBUILDER_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/Support/CBindingWrapping.h"
27 #include "llvm/Support/ConstantFolder.h"
28
29 namespace llvm {
30   class MDNode;
31
32 /// \brief This provides the default implementation of the IRBuilder
33 /// 'InsertHelper' method that is called whenever an instruction is created by
34 /// IRBuilder and needs to be inserted.
35 ///
36 /// By default, this inserts the instruction at the insertion point.
37 template <bool preserveNames = true>
38 class IRBuilderDefaultInserter {
39 protected:
40   void InsertHelper(Instruction *I, const Twine &Name,
41                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
42     if (BB) BB->getInstList().insert(InsertPt, I);
43     if (preserveNames)
44       I->setName(Name);
45   }
46 };
47
48 /// \brief Common base class shared among various IRBuilders.
49 class IRBuilderBase {
50   DebugLoc CurDbgLocation;
51 protected:
52   BasicBlock *BB;
53   BasicBlock::iterator InsertPt;
54   LLVMContext &Context;
55
56   MDNode *DefaultFPMathTag;
57   FastMathFlags FMF;
58 public:
59
60   IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = 0)
61     : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
62     ClearInsertionPoint();
63   }
64
65   //===--------------------------------------------------------------------===//
66   // Builder configuration methods
67   //===--------------------------------------------------------------------===//
68
69   /// \brief Clear the insertion point: created instructions will not be
70   /// inserted into a block.
71   void ClearInsertionPoint() {
72     BB = 0;
73     InsertPt = 0;
74   }
75
76   BasicBlock *GetInsertBlock() const { return BB; }
77   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
78   LLVMContext &getContext() const { return Context; }
79
80   /// \brief This specifies that created instructions should be appended to the
81   /// end of the specified block.
82   void SetInsertPoint(BasicBlock *TheBB) {
83     BB = TheBB;
84     InsertPt = BB->end();
85   }
86
87   /// \brief This specifies that created instructions should be inserted before
88   /// the specified instruction.
89   void SetInsertPoint(Instruction *I) {
90     BB = I->getParent();
91     InsertPt = I;
92     assert(I != BB->end() && "Can't read debug loc from end()");
93     SetCurrentDebugLocation(I->getDebugLoc());
94   }
95
96   /// \brief This specifies that created instructions should be inserted at the
97   /// specified point.
98   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
99     BB = TheBB;
100     InsertPt = IP;
101   }
102
103   /// \brief Find the nearest point that dominates this use, and specify that
104   /// created instructions should be inserted at this point.
105   void SetInsertPoint(Use &U) {
106     Instruction *UseInst = cast<Instruction>(U.getUser());
107     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
108       BasicBlock *PredBB = Phi->getIncomingBlock(U);
109       assert(U != PredBB->getTerminator() && "critical edge not split");
110       SetInsertPoint(PredBB, PredBB->getTerminator());
111       return;
112     }
113     SetInsertPoint(UseInst);
114   }
115
116   /// \brief Set location information used by debugging information.
117   void SetCurrentDebugLocation(const DebugLoc &L) {
118     CurDbgLocation = L;
119   }
120
121   /// \brief Get location information used by debugging information.
122   DebugLoc getCurrentDebugLocation() const { return CurDbgLocation; }
123
124   /// \brief If this builder has a current debug location, set it on the
125   /// specified instruction.
126   void SetInstDebugLocation(Instruction *I) const {
127     if (!CurDbgLocation.isUnknown())
128       I->setDebugLoc(CurDbgLocation);
129   }
130
131   /// \brief Get the return type of the current function that we're emitting
132   /// into.
133   Type *getCurrentFunctionReturnType() const;
134
135   /// InsertPoint - A saved insertion point.
136   class InsertPoint {
137     BasicBlock *Block;
138     BasicBlock::iterator Point;
139
140   public:
141     /// \brief Creates a new insertion point which doesn't point to anything.
142     InsertPoint() : Block(0) {}
143
144     /// \brief Creates a new insertion point at the given location.
145     InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
146       : Block(InsertBlock), Point(InsertPoint) {}
147
148     /// \brief Returns true if this insert point is set.
149     bool isSet() const { return (Block != 0); }
150
151     llvm::BasicBlock *getBlock() const { return Block; }
152     llvm::BasicBlock::iterator getPoint() const { return Point; }
153   };
154
155   /// \brief Returns the current insert point.
156   InsertPoint saveIP() const {
157     return InsertPoint(GetInsertBlock(), GetInsertPoint());
158   }
159
160   /// \brief Returns the current insert point, clearing it in the process.
161   InsertPoint saveAndClearIP() {
162     InsertPoint IP(GetInsertBlock(), GetInsertPoint());
163     ClearInsertionPoint();
164     return IP;
165   }
166
167   /// \brief Sets the current insert point to a previously-saved location.
168   void restoreIP(InsertPoint IP) {
169     if (IP.isSet())
170       SetInsertPoint(IP.getBlock(), IP.getPoint());
171     else
172       ClearInsertionPoint();
173   }
174
175   /// \brief Get the floating point math metadata being used.
176   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
177
178   /// \brief Get the flags to be applied to created floating point ops
179   FastMathFlags getFastMathFlags() const { return FMF; }
180
181   /// \brief Clear the fast-math flags.
182   void clearFastMathFlags() { FMF.clear(); }
183
184   /// \brief Set the floating point math metadata to be used.
185   void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
186
187   /// \brief Set the fast-math flags to be used with generated fp-math operators
188   void SetFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
189
190   //===--------------------------------------------------------------------===//
191   // Miscellaneous creation methods.
192   //===--------------------------------------------------------------------===//
193
194   /// \brief Make a new global variable with initializer type i8*
195   ///
196   /// Make a new global variable with an initializer that has array of i8 type
197   /// filled in with the null terminated string value specified.  The new global
198   /// variable will be marked mergable with any others of the same contents.  If
199   /// Name is specified, it is the name of the global variable created.
200   Value *CreateGlobalString(StringRef Str, const Twine &Name = "");
201
202   /// \brief Get a constant value representing either true or false.
203   ConstantInt *getInt1(bool V) {
204     return ConstantInt::get(getInt1Ty(), V);
205   }
206
207   /// \brief Get the constant value for i1 true.
208   ConstantInt *getTrue() {
209     return ConstantInt::getTrue(Context);
210   }
211
212   /// \brief Get the constant value for i1 false.
213   ConstantInt *getFalse() {
214     return ConstantInt::getFalse(Context);
215   }
216
217   /// \brief Get a constant 8-bit value.
218   ConstantInt *getInt8(uint8_t C) {
219     return ConstantInt::get(getInt8Ty(), C);
220   }
221
222   /// \brief Get a constant 16-bit value.
223   ConstantInt *getInt16(uint16_t C) {
224     return ConstantInt::get(getInt16Ty(), C);
225   }
226
227   /// \brief Get a constant 32-bit value.
228   ConstantInt *getInt32(uint32_t C) {
229     return ConstantInt::get(getInt32Ty(), C);
230   }
231
232   /// \brief Get a constant 64-bit value.
233   ConstantInt *getInt64(uint64_t C) {
234     return ConstantInt::get(getInt64Ty(), C);
235   }
236
237   /// \brief Get a constant integer value.
238   ConstantInt *getInt(const APInt &AI) {
239     return ConstantInt::get(Context, AI);
240   }
241
242   //===--------------------------------------------------------------------===//
243   // Type creation methods
244   //===--------------------------------------------------------------------===//
245
246   /// \brief Fetch the type representing a single bit
247   IntegerType *getInt1Ty() {
248     return Type::getInt1Ty(Context);
249   }
250
251   /// \brief Fetch the type representing an 8-bit integer.
252   IntegerType *getInt8Ty() {
253     return Type::getInt8Ty(Context);
254   }
255
256   /// \brief Fetch the type representing a 16-bit integer.
257   IntegerType *getInt16Ty() {
258     return Type::getInt16Ty(Context);
259   }
260
261   /// \brief Fetch the type representing a 32-bit integer.
262   IntegerType *getInt32Ty() {
263     return Type::getInt32Ty(Context);
264   }
265
266   /// \brief Fetch the type representing a 64-bit integer.
267   IntegerType *getInt64Ty() {
268     return Type::getInt64Ty(Context);
269   }
270
271   /// \brief Fetch the type representing a 32-bit floating point value.
272   Type *getFloatTy() {
273     return Type::getFloatTy(Context);
274   }
275
276   /// \brief Fetch the type representing a 64-bit floating point value.
277   Type *getDoubleTy() {
278     return Type::getDoubleTy(Context);
279   }
280
281   /// \brief Fetch the type representing void.
282   Type *getVoidTy() {
283     return Type::getVoidTy(Context);
284   }
285
286   /// \brief Fetch the type representing a pointer to an 8-bit integer value.
287   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
288     return Type::getInt8PtrTy(Context, AddrSpace);
289   }
290
291   /// \brief Fetch the type representing a pointer to an integer value.
292   IntegerType* getIntPtrTy(const DataLayout *DL, unsigned AddrSpace = 0) {
293     return DL->getIntPtrType(Context, AddrSpace);
294   }
295
296   //===--------------------------------------------------------------------===//
297   // Intrinsic creation methods
298   //===--------------------------------------------------------------------===//
299
300   /// \brief Create and insert a memset to the specified pointer and the
301   /// specified value.
302   ///
303   /// If the pointer isn't an i8*, it will be converted.  If a TBAA tag is
304   /// specified, it will be added to the instruction.
305   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
306                          bool isVolatile = false, MDNode *TBAATag = 0) {
307     return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile, TBAATag);
308   }
309
310   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
311                          bool isVolatile = false, MDNode *TBAATag = 0);
312
313   /// \brief Create and insert a memcpy between the specified pointers.
314   ///
315   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
316   /// specified, it will be added to the instruction.
317   CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
318                          bool isVolatile = false, MDNode *TBAATag = 0,
319                          MDNode *TBAAStructTag = 0) {
320     return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
321                         TBAAStructTag);
322   }
323
324   CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
325                          bool isVolatile = false, MDNode *TBAATag = 0,
326                          MDNode *TBAAStructTag = 0);
327
328   /// \brief Create and insert a memmove between the specified
329   /// pointers.
330   ///
331   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
332   /// specified, it will be added to the instruction.
333   CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
334                           bool isVolatile = false, MDNode *TBAATag = 0) {
335     return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag);
336   }
337
338   CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
339                           bool isVolatile = false, MDNode *TBAATag = 0);
340
341   /// \brief Create a lifetime.start intrinsic.
342   ///
343   /// If the pointer isn't i8* it will be converted.
344   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = 0);
345
346   /// \brief Create a lifetime.end intrinsic.
347   ///
348   /// If the pointer isn't i8* it will be converted.
349   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = 0);
350
351 private:
352   Value *getCastedInt8PtrValue(Value *Ptr);
353 };
354
355 /// \brief This provides a uniform API for creating instructions and inserting
356 /// them into a basic block: either at the end of a BasicBlock, or at a specific
357 /// iterator location in a block.
358 ///
359 /// Note that the builder does not expose the full generality of LLVM
360 /// instructions.  For access to extra instruction properties, use the mutators
361 /// (e.g. setVolatile) on the instructions after they have been
362 /// created. Convenience state exists to specify fast-math flags and fp-math
363 /// tags.
364 ///
365 /// The first template argument handles whether or not to preserve names in the
366 /// final instruction output. This defaults to on.  The second template argument
367 /// specifies a class to use for creating constants.  This defaults to creating
368 /// minimally folded constants.  The fourth template argument allows clients to
369 /// specify custom insertion hooks that are called on every newly created
370 /// insertion.
371 template<bool preserveNames = true, typename T = ConstantFolder,
372          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
373 class IRBuilder : public IRBuilderBase, public Inserter {
374   T Folder;
375 public:
376   IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
377             MDNode *FPMathTag = 0)
378     : IRBuilderBase(C, FPMathTag), Inserter(I), Folder(F) {
379   }
380
381   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = 0)
382     : IRBuilderBase(C, FPMathTag), Folder() {
383   }
384
385   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = 0)
386     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
387     SetInsertPoint(TheBB);
388   }
389
390   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = 0)
391     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
392     SetInsertPoint(TheBB);
393   }
394
395   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = 0)
396     : IRBuilderBase(IP->getContext(), FPMathTag), Folder() {
397     SetInsertPoint(IP);
398     SetCurrentDebugLocation(IP->getDebugLoc());
399   }
400
401   explicit IRBuilder(Use &U, MDNode *FPMathTag = 0)
402     : IRBuilderBase(U->getContext(), FPMathTag), Folder() {
403     SetInsertPoint(U);
404     SetCurrentDebugLocation(cast<Instruction>(U.getUser())->getDebugLoc());
405   }
406
407   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
408             MDNode *FPMathTag = 0)
409     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
410     SetInsertPoint(TheBB, IP);
411   }
412
413   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, MDNode *FPMathTag = 0)
414     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
415     SetInsertPoint(TheBB, IP);
416   }
417
418   /// \brief Get the constant folder being used.
419   const T &getFolder() { return Folder; }
420
421   /// \brief Return true if this builder is configured to actually add the
422   /// requested names to IR created through it.
423   bool isNamePreserving() const { return preserveNames; }
424
425   /// \brief Insert and return the specified instruction.
426   template<typename InstTy>
427   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
428     this->InsertHelper(I, Name, BB, InsertPt);
429     this->SetInstDebugLocation(I);
430     return I;
431   }
432
433   /// \brief No-op overload to handle constants.
434   Constant *Insert(Constant *C, const Twine& = "") const {
435     return C;
436   }
437
438   //===--------------------------------------------------------------------===//
439   // Instruction creation methods: Terminators
440   //===--------------------------------------------------------------------===//
441
442 private:
443   /// \brief Helper to add branch weight metadata onto an instruction.
444   /// \returns The annotated instruction.
445   template <typename InstTy>
446   InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
447     if (Weights)
448       I->setMetadata(LLVMContext::MD_prof, Weights);
449     return I;
450   }
451
452 public:
453   /// \brief Create a 'ret void' instruction.
454   ReturnInst *CreateRetVoid() {
455     return Insert(ReturnInst::Create(Context));
456   }
457
458   /// \brief Create a 'ret <val>' instruction.
459   ReturnInst *CreateRet(Value *V) {
460     return Insert(ReturnInst::Create(Context, V));
461   }
462
463   /// \brief Create a sequence of N insertvalue instructions,
464   /// with one Value from the retVals array each, that build a aggregate
465   /// return value one value at a time, and a ret instruction to return
466   /// the resulting aggregate value.
467   ///
468   /// This is a convenience function for code that uses aggregate return values
469   /// as a vehicle for having multiple return values.
470   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
471     Value *V = UndefValue::get(getCurrentFunctionReturnType());
472     for (unsigned i = 0; i != N; ++i)
473       V = CreateInsertValue(V, retVals[i], i, "mrv");
474     return Insert(ReturnInst::Create(Context, V));
475   }
476
477   /// \brief Create an unconditional 'br label X' instruction.
478   BranchInst *CreateBr(BasicBlock *Dest) {
479     return Insert(BranchInst::Create(Dest));
480   }
481
482   /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
483   /// instruction.
484   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
485                            MDNode *BranchWeights = 0) {
486     return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
487                                    BranchWeights));
488   }
489
490   /// \brief Create a switch instruction with the specified value, default dest,
491   /// and with a hint for the number of cases that will be added (for efficient
492   /// allocation).
493   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
494                            MDNode *BranchWeights = 0) {
495     return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
496                                    BranchWeights));
497   }
498
499   /// \brief Create an indirect branch instruction with the specified address
500   /// operand, with an optional hint for the number of destinations that will be
501   /// added (for efficient allocation).
502   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
503     return Insert(IndirectBrInst::Create(Addr, NumDests));
504   }
505
506   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
507                            BasicBlock *UnwindDest, const Twine &Name = "") {
508     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest,
509                                      ArrayRef<Value *>()),
510                   Name);
511   }
512   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
513                            BasicBlock *UnwindDest, Value *Arg1,
514                            const Twine &Name = "") {
515     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
516                   Name);
517   }
518   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
519                             BasicBlock *UnwindDest, Value *Arg1,
520                             Value *Arg2, Value *Arg3,
521                             const Twine &Name = "") {
522     Value *Args[] = { Arg1, Arg2, Arg3 };
523     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
524                   Name);
525   }
526   /// \brief Create an invoke instruction.
527   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
528                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
529                            const Twine &Name = "") {
530     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
531                   Name);
532   }
533
534   ResumeInst *CreateResume(Value *Exn) {
535     return Insert(ResumeInst::Create(Exn));
536   }
537
538   UnreachableInst *CreateUnreachable() {
539     return Insert(new UnreachableInst(Context));
540   }
541
542   //===--------------------------------------------------------------------===//
543   // Instruction creation methods: Binary Operators
544   //===--------------------------------------------------------------------===//
545 private:
546   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
547                                           Value *LHS, Value *RHS,
548                                           const Twine &Name,
549                                           bool HasNUW, bool HasNSW) {
550     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
551     if (HasNUW) BO->setHasNoUnsignedWrap();
552     if (HasNSW) BO->setHasNoSignedWrap();
553     return BO;
554   }
555
556   Instruction *AddFPMathAttributes(Instruction *I,
557                                    MDNode *FPMathTag,
558                                    FastMathFlags FMF) const {
559     if (!FPMathTag)
560       FPMathTag = DefaultFPMathTag;
561     if (FPMathTag)
562       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
563     I->setFastMathFlags(FMF);
564     return I;
565   }
566 public:
567   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
568                    bool HasNUW = false, bool HasNSW = false) {
569     if (Constant *LC = dyn_cast<Constant>(LHS))
570       if (Constant *RC = dyn_cast<Constant>(RHS))
571         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
572     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
573                                    HasNUW, HasNSW);
574   }
575   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
576     return CreateAdd(LHS, RHS, Name, false, true);
577   }
578   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
579     return CreateAdd(LHS, RHS, Name, true, false);
580   }
581   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
582                     MDNode *FPMathTag = 0) {
583     if (Constant *LC = dyn_cast<Constant>(LHS))
584       if (Constant *RC = dyn_cast<Constant>(RHS))
585         return Insert(Folder.CreateFAdd(LC, RC), Name);
586     return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
587                                       FPMathTag, FMF), Name);
588   }
589   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
590                    bool HasNUW = false, bool HasNSW = false) {
591     if (Constant *LC = dyn_cast<Constant>(LHS))
592       if (Constant *RC = dyn_cast<Constant>(RHS))
593         return Insert(Folder.CreateSub(LC, RC), Name);
594     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
595                                    HasNUW, HasNSW);
596   }
597   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
598     return CreateSub(LHS, RHS, Name, false, true);
599   }
600   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
601     return CreateSub(LHS, RHS, Name, true, false);
602   }
603   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
604                     MDNode *FPMathTag = 0) {
605     if (Constant *LC = dyn_cast<Constant>(LHS))
606       if (Constant *RC = dyn_cast<Constant>(RHS))
607         return Insert(Folder.CreateFSub(LC, RC), Name);
608     return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
609                                       FPMathTag, FMF), Name);
610   }
611   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
612                    bool HasNUW = false, bool HasNSW = false) {
613     if (Constant *LC = dyn_cast<Constant>(LHS))
614       if (Constant *RC = dyn_cast<Constant>(RHS))
615         return Insert(Folder.CreateMul(LC, RC), Name);
616     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
617                                    HasNUW, HasNSW);
618   }
619   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
620     return CreateMul(LHS, RHS, Name, false, true);
621   }
622   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
623     return CreateMul(LHS, RHS, Name, true, false);
624   }
625   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
626                     MDNode *FPMathTag = 0) {
627     if (Constant *LC = dyn_cast<Constant>(LHS))
628       if (Constant *RC = dyn_cast<Constant>(RHS))
629         return Insert(Folder.CreateFMul(LC, RC), Name);
630     return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
631                                       FPMathTag, FMF), Name);
632   }
633   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
634                     bool isExact = false) {
635     if (Constant *LC = dyn_cast<Constant>(LHS))
636       if (Constant *RC = dyn_cast<Constant>(RHS))
637         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
638     if (!isExact)
639       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
640     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
641   }
642   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
643     return CreateUDiv(LHS, RHS, Name, true);
644   }
645   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
646                     bool isExact = false) {
647     if (Constant *LC = dyn_cast<Constant>(LHS))
648       if (Constant *RC = dyn_cast<Constant>(RHS))
649         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
650     if (!isExact)
651       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
652     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
653   }
654   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
655     return CreateSDiv(LHS, RHS, Name, true);
656   }
657   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
658                     MDNode *FPMathTag = 0) {
659     if (Constant *LC = dyn_cast<Constant>(LHS))
660       if (Constant *RC = dyn_cast<Constant>(RHS))
661         return Insert(Folder.CreateFDiv(LC, RC), Name);
662     return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
663                                       FPMathTag, FMF), Name);
664   }
665   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
666     if (Constant *LC = dyn_cast<Constant>(LHS))
667       if (Constant *RC = dyn_cast<Constant>(RHS))
668         return Insert(Folder.CreateURem(LC, RC), Name);
669     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
670   }
671   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
672     if (Constant *LC = dyn_cast<Constant>(LHS))
673       if (Constant *RC = dyn_cast<Constant>(RHS))
674         return Insert(Folder.CreateSRem(LC, RC), Name);
675     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
676   }
677   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
678                     MDNode *FPMathTag = 0) {
679     if (Constant *LC = dyn_cast<Constant>(LHS))
680       if (Constant *RC = dyn_cast<Constant>(RHS))
681         return Insert(Folder.CreateFRem(LC, RC), Name);
682     return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
683                                       FPMathTag, FMF), Name);
684   }
685
686   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
687                    bool HasNUW = false, bool HasNSW = false) {
688     if (Constant *LC = dyn_cast<Constant>(LHS))
689       if (Constant *RC = dyn_cast<Constant>(RHS))
690         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
691     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
692                                    HasNUW, HasNSW);
693   }
694   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
695                    bool HasNUW = false, bool HasNSW = false) {
696     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
697                      HasNUW, HasNSW);
698   }
699   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
700                    bool HasNUW = false, bool HasNSW = false) {
701     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
702                      HasNUW, HasNSW);
703   }
704
705   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
706                     bool isExact = false) {
707     if (Constant *LC = dyn_cast<Constant>(LHS))
708       if (Constant *RC = dyn_cast<Constant>(RHS))
709         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
710     if (!isExact)
711       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
712     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
713   }
714   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
715                     bool isExact = false) {
716     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
717   }
718   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
719                     bool isExact = false) {
720     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
721   }
722
723   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
724                     bool isExact = false) {
725     if (Constant *LC = dyn_cast<Constant>(LHS))
726       if (Constant *RC = dyn_cast<Constant>(RHS))
727         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
728     if (!isExact)
729       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
730     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
731   }
732   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
733                     bool isExact = false) {
734     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
735   }
736   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
737                     bool isExact = false) {
738     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
739   }
740
741   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
742     if (Constant *RC = dyn_cast<Constant>(RHS)) {
743       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
744         return LHS;  // LHS & -1 -> LHS
745       if (Constant *LC = dyn_cast<Constant>(LHS))
746         return Insert(Folder.CreateAnd(LC, RC), Name);
747     }
748     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
749   }
750   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
751     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
752   }
753   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
754     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
755   }
756
757   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
758     if (Constant *RC = dyn_cast<Constant>(RHS)) {
759       if (RC->isNullValue())
760         return LHS;  // LHS | 0 -> LHS
761       if (Constant *LC = dyn_cast<Constant>(LHS))
762         return Insert(Folder.CreateOr(LC, RC), Name);
763     }
764     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
765   }
766   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
767     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
768   }
769   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
770     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
771   }
772
773   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
774     if (Constant *LC = dyn_cast<Constant>(LHS))
775       if (Constant *RC = dyn_cast<Constant>(RHS))
776         return Insert(Folder.CreateXor(LC, RC), Name);
777     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
778   }
779   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
780     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
781   }
782   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
783     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
784   }
785
786   Value *CreateBinOp(Instruction::BinaryOps Opc,
787                      Value *LHS, Value *RHS, const Twine &Name = "") {
788     if (Constant *LC = dyn_cast<Constant>(LHS))
789       if (Constant *RC = dyn_cast<Constant>(RHS))
790         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
791     return Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
792   }
793
794   Value *CreateNeg(Value *V, const Twine &Name = "",
795                    bool HasNUW = false, bool HasNSW = false) {
796     if (Constant *VC = dyn_cast<Constant>(V))
797       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
798     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
799     if (HasNUW) BO->setHasNoUnsignedWrap();
800     if (HasNSW) BO->setHasNoSignedWrap();
801     return BO;
802   }
803   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
804     return CreateNeg(V, Name, false, true);
805   }
806   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
807     return CreateNeg(V, Name, true, false);
808   }
809   Value *CreateFNeg(Value *V, const Twine &Name = "", MDNode *FPMathTag = 0) {
810     if (Constant *VC = dyn_cast<Constant>(V))
811       return Insert(Folder.CreateFNeg(VC), Name);
812     return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
813                                       FPMathTag, FMF), Name);
814   }
815   Value *CreateNot(Value *V, const Twine &Name = "") {
816     if (Constant *VC = dyn_cast<Constant>(V))
817       return Insert(Folder.CreateNot(VC), Name);
818     return Insert(BinaryOperator::CreateNot(V), Name);
819   }
820
821   //===--------------------------------------------------------------------===//
822   // Instruction creation methods: Memory Instructions
823   //===--------------------------------------------------------------------===//
824
825   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = 0,
826                            const Twine &Name = "") {
827     return Insert(new AllocaInst(Ty, ArraySize), Name);
828   }
829   // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
830   // converting the string to 'bool' for the isVolatile parameter.
831   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
832     return Insert(new LoadInst(Ptr), Name);
833   }
834   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
835     return Insert(new LoadInst(Ptr), Name);
836   }
837   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
838     return Insert(new LoadInst(Ptr, 0, isVolatile), Name);
839   }
840   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
841     return Insert(new StoreInst(Val, Ptr, isVolatile));
842   }
843   // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
844   // correctly, instead of converting the string to 'bool' for the isVolatile
845   // parameter.
846   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
847     LoadInst *LI = CreateLoad(Ptr, Name);
848     LI->setAlignment(Align);
849     return LI;
850   }
851   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
852                               const Twine &Name = "") {
853     LoadInst *LI = CreateLoad(Ptr, Name);
854     LI->setAlignment(Align);
855     return LI;
856   }
857   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
858                               const Twine &Name = "") {
859     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
860     LI->setAlignment(Align);
861     return LI;
862   }
863   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
864                                 bool isVolatile = false) {
865     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
866     SI->setAlignment(Align);
867     return SI;
868   }
869   FenceInst *CreateFence(AtomicOrdering Ordering,
870                          SynchronizationScope SynchScope = CrossThread) {
871     return Insert(new FenceInst(Context, Ordering, SynchScope));
872   }
873   AtomicCmpXchgInst *CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
874                                          AtomicOrdering Ordering,
875                                SynchronizationScope SynchScope = CrossThread) {
876     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope));
877   }
878   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
879                                  AtomicOrdering Ordering,
880                                SynchronizationScope SynchScope = CrossThread) {
881     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
882   }
883   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
884                    const Twine &Name = "") {
885     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
886       // Every index must be constant.
887       size_t i, e;
888       for (i = 0, e = IdxList.size(); i != e; ++i)
889         if (!isa<Constant>(IdxList[i]))
890           break;
891       if (i == e)
892         return Insert(Folder.CreateGetElementPtr(PC, IdxList), Name);
893     }
894     return Insert(GetElementPtrInst::Create(Ptr, IdxList), Name);
895   }
896   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
897                            const Twine &Name = "") {
898     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
899       // Every index must be constant.
900       size_t i, e;
901       for (i = 0, e = IdxList.size(); i != e; ++i)
902         if (!isa<Constant>(IdxList[i]))
903           break;
904       if (i == e)
905         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IdxList), Name);
906     }
907     return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxList), Name);
908   }
909   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
910     if (Constant *PC = dyn_cast<Constant>(Ptr))
911       if (Constant *IC = dyn_cast<Constant>(Idx))
912         return Insert(Folder.CreateGetElementPtr(PC, IC), Name);
913     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
914   }
915   Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
916     if (Constant *PC = dyn_cast<Constant>(Ptr))
917       if (Constant *IC = dyn_cast<Constant>(Idx))
918         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IC), Name);
919     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
920   }
921   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
922     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
923
924     if (Constant *PC = dyn_cast<Constant>(Ptr))
925       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
926
927     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
928   }
929   Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
930                                     const Twine &Name = "") {
931     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
932
933     if (Constant *PC = dyn_cast<Constant>(Ptr))
934       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
935
936     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
937   }
938   Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
939                     const Twine &Name = "") {
940     Value *Idxs[] = {
941       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
942       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
943     };
944
945     if (Constant *PC = dyn_cast<Constant>(Ptr))
946       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
947
948     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
949   }
950   Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
951                                     const Twine &Name = "") {
952     Value *Idxs[] = {
953       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
954       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
955     };
956
957     if (Constant *PC = dyn_cast<Constant>(Ptr))
958       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
959
960     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
961   }
962   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
963     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
964
965     if (Constant *PC = dyn_cast<Constant>(Ptr))
966       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
967
968     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
969   }
970   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
971                                     const Twine &Name = "") {
972     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
973
974     if (Constant *PC = dyn_cast<Constant>(Ptr))
975       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
976
977     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
978   }
979   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
980                     const Twine &Name = "") {
981     Value *Idxs[] = {
982       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
983       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
984     };
985
986     if (Constant *PC = dyn_cast<Constant>(Ptr))
987       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
988
989     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
990   }
991   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
992                                     const Twine &Name = "") {
993     Value *Idxs[] = {
994       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
995       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
996     };
997
998     if (Constant *PC = dyn_cast<Constant>(Ptr))
999       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
1000
1001     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
1002   }
1003   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
1004     return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
1005   }
1006
1007   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1008   /// instead of a pointer to array of i8.
1009   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
1010     Value *gv = CreateGlobalString(Str, Name);
1011     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1012     Value *Args[] = { zero, zero };
1013     return CreateInBoundsGEP(gv, Args, Name);
1014   }
1015
1016   //===--------------------------------------------------------------------===//
1017   // Instruction creation methods: Cast/Conversion Operators
1018   //===--------------------------------------------------------------------===//
1019
1020   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1021     return CreateCast(Instruction::Trunc, V, DestTy, Name);
1022   }
1023   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1024     return CreateCast(Instruction::ZExt, V, DestTy, Name);
1025   }
1026   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1027     return CreateCast(Instruction::SExt, V, DestTy, Name);
1028   }
1029   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1030   /// the value untouched if the type of V is already DestTy.
1031   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1032                            const Twine &Name = "") {
1033     assert(V->getType()->isIntOrIntVectorTy() &&
1034            DestTy->isIntOrIntVectorTy() &&
1035            "Can only zero extend/truncate integers!");
1036     Type *VTy = V->getType();
1037     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1038       return CreateZExt(V, DestTy, Name);
1039     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1040       return CreateTrunc(V, DestTy, Name);
1041     return V;
1042   }
1043   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1044   /// the value untouched if the type of V is already DestTy.
1045   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1046                            const Twine &Name = "") {
1047     assert(V->getType()->isIntOrIntVectorTy() &&
1048            DestTy->isIntOrIntVectorTy() &&
1049            "Can only sign extend/truncate integers!");
1050     Type *VTy = V->getType();
1051     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1052       return CreateSExt(V, DestTy, Name);
1053     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1054       return CreateTrunc(V, DestTy, Name);
1055     return V;
1056   }
1057   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1058     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1059   }
1060   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1061     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1062   }
1063   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1064     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1065   }
1066   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1067     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1068   }
1069   Value *CreateFPTrunc(Value *V, Type *DestTy,
1070                        const Twine &Name = "") {
1071     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1072   }
1073   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1074     return CreateCast(Instruction::FPExt, V, DestTy, Name);
1075   }
1076   Value *CreatePtrToInt(Value *V, Type *DestTy,
1077                         const Twine &Name = "") {
1078     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1079   }
1080   Value *CreateIntToPtr(Value *V, Type *DestTy,
1081                         const Twine &Name = "") {
1082     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1083   }
1084   Value *CreateBitCast(Value *V, Type *DestTy,
1085                        const Twine &Name = "") {
1086     return CreateCast(Instruction::BitCast, V, DestTy, Name);
1087   }
1088   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1089                              const Twine &Name = "") {
1090     if (V->getType() == DestTy)
1091       return V;
1092     if (Constant *VC = dyn_cast<Constant>(V))
1093       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1094     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1095   }
1096   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1097                              const Twine &Name = "") {
1098     if (V->getType() == DestTy)
1099       return V;
1100     if (Constant *VC = dyn_cast<Constant>(V))
1101       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1102     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1103   }
1104   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1105                               const Twine &Name = "") {
1106     if (V->getType() == DestTy)
1107       return V;
1108     if (Constant *VC = dyn_cast<Constant>(V))
1109       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1110     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1111   }
1112   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1113                     const Twine &Name = "") {
1114     if (V->getType() == DestTy)
1115       return V;
1116     if (Constant *VC = dyn_cast<Constant>(V))
1117       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1118     return Insert(CastInst::Create(Op, V, DestTy), Name);
1119   }
1120   Value *CreatePointerCast(Value *V, Type *DestTy,
1121                            const Twine &Name = "") {
1122     if (V->getType() == DestTy)
1123       return V;
1124     if (Constant *VC = dyn_cast<Constant>(V))
1125       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1126     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1127   }
1128   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1129                        const Twine &Name = "") {
1130     if (V->getType() == DestTy)
1131       return V;
1132     if (Constant *VC = dyn_cast<Constant>(V))
1133       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1134     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1135   }
1136 private:
1137   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1138   // compile time error, instead of converting the string to bool for the
1139   // isSigned parameter.
1140   Value *CreateIntCast(Value *, Type *, const char *) LLVM_DELETED_FUNCTION;
1141 public:
1142   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1143     if (V->getType() == DestTy)
1144       return V;
1145     if (Constant *VC = dyn_cast<Constant>(V))
1146       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1147     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1148   }
1149
1150   //===--------------------------------------------------------------------===//
1151   // Instruction creation methods: Compare Instructions
1152   //===--------------------------------------------------------------------===//
1153
1154   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1155     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1156   }
1157   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1158     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1159   }
1160   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1161     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1162   }
1163   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1164     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1165   }
1166   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1167     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1168   }
1169   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1170     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1171   }
1172   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1173     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1174   }
1175   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1176     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1177   }
1178   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1179     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1180   }
1181   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1182     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1183   }
1184
1185   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1186     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
1187   }
1188   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1189     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
1190   }
1191   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1192     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
1193   }
1194   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1195     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
1196   }
1197   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1198     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
1199   }
1200   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
1201     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
1202   }
1203   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
1204     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
1205   }
1206   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
1207     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
1208   }
1209   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1210     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
1211   }
1212   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1213     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
1214   }
1215   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1216     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
1217   }
1218   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1219     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
1220   }
1221   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1222     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
1223   }
1224   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1225     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
1226   }
1227
1228   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1229                     const Twine &Name = "") {
1230     if (Constant *LC = dyn_cast<Constant>(LHS))
1231       if (Constant *RC = dyn_cast<Constant>(RHS))
1232         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1233     return Insert(new ICmpInst(P, LHS, RHS), Name);
1234   }
1235   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1236                     const Twine &Name = "") {
1237     if (Constant *LC = dyn_cast<Constant>(LHS))
1238       if (Constant *RC = dyn_cast<Constant>(RHS))
1239         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1240     return Insert(new FCmpInst(P, LHS, RHS), Name);
1241   }
1242
1243   //===--------------------------------------------------------------------===//
1244   // Instruction creation methods: Other Instructions
1245   //===--------------------------------------------------------------------===//
1246
1247   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1248                      const Twine &Name = "") {
1249     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1250   }
1251
1252   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
1253     return Insert(CallInst::Create(Callee), Name);
1254   }
1255   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
1256     return Insert(CallInst::Create(Callee, Arg), Name);
1257   }
1258   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
1259                         const Twine &Name = "") {
1260     Value *Args[] = { Arg1, Arg2 };
1261     return Insert(CallInst::Create(Callee, Args), Name);
1262   }
1263   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1264                         const Twine &Name = "") {
1265     Value *Args[] = { Arg1, Arg2, Arg3 };
1266     return Insert(CallInst::Create(Callee, Args), Name);
1267   }
1268   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1269                         Value *Arg4, const Twine &Name = "") {
1270     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
1271     return Insert(CallInst::Create(Callee, Args), Name);
1272   }
1273   CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1274                         Value *Arg4, Value *Arg5, const Twine &Name = "") {
1275     Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
1276     return Insert(CallInst::Create(Callee, Args), Name);
1277   }
1278
1279   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1280                        const Twine &Name = "") {
1281     return Insert(CallInst::Create(Callee, Args), Name);
1282   }
1283
1284   Value *CreateSelect(Value *C, Value *True, Value *False,
1285                       const Twine &Name = "") {
1286     if (Constant *CC = dyn_cast<Constant>(C))
1287       if (Constant *TC = dyn_cast<Constant>(True))
1288         if (Constant *FC = dyn_cast<Constant>(False))
1289           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1290     return Insert(SelectInst::Create(C, True, False), Name);
1291   }
1292
1293   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1294     return Insert(new VAArgInst(List, Ty), Name);
1295   }
1296
1297   Value *CreateExtractElement(Value *Vec, Value *Idx,
1298                               const Twine &Name = "") {
1299     if (Constant *VC = dyn_cast<Constant>(Vec))
1300       if (Constant *IC = dyn_cast<Constant>(Idx))
1301         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1302     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1303   }
1304
1305   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1306                              const Twine &Name = "") {
1307     if (Constant *VC = dyn_cast<Constant>(Vec))
1308       if (Constant *NC = dyn_cast<Constant>(NewElt))
1309         if (Constant *IC = dyn_cast<Constant>(Idx))
1310           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1311     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1312   }
1313
1314   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1315                              const Twine &Name = "") {
1316     if (Constant *V1C = dyn_cast<Constant>(V1))
1317       if (Constant *V2C = dyn_cast<Constant>(V2))
1318         if (Constant *MC = dyn_cast<Constant>(Mask))
1319           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1320     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1321   }
1322
1323   Value *CreateExtractValue(Value *Agg,
1324                             ArrayRef<unsigned> Idxs,
1325                             const Twine &Name = "") {
1326     if (Constant *AggC = dyn_cast<Constant>(Agg))
1327       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1328     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1329   }
1330
1331   Value *CreateInsertValue(Value *Agg, Value *Val,
1332                            ArrayRef<unsigned> Idxs,
1333                            const Twine &Name = "") {
1334     if (Constant *AggC = dyn_cast<Constant>(Agg))
1335       if (Constant *ValC = dyn_cast<Constant>(Val))
1336         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1337     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1338   }
1339
1340   LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
1341                                    const Twine &Name = "") {
1342     return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses), Name);
1343   }
1344
1345   //===--------------------------------------------------------------------===//
1346   // Utility creation methods
1347   //===--------------------------------------------------------------------===//
1348
1349   /// \brief Return an i1 value testing if \p Arg is null.
1350   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1351     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1352                         Name);
1353   }
1354
1355   /// \brief Return an i1 value testing if \p Arg is not null.
1356   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1357     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1358                         Name);
1359   }
1360
1361   /// \brief Return the i64 difference between two pointer values, dividing out
1362   /// the size of the pointed-to objects.
1363   ///
1364   /// This is intended to implement C-style pointer subtraction. As such, the
1365   /// pointers must be appropriately aligned for their element types and
1366   /// pointing into the same object.
1367   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1368     assert(LHS->getType() == RHS->getType() &&
1369            "Pointer subtraction operand types must match!");
1370     PointerType *ArgType = cast<PointerType>(LHS->getType());
1371     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1372     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1373     Value *Difference = CreateSub(LHS_int, RHS_int);
1374     return CreateExactSDiv(Difference,
1375                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1376                            Name);
1377   }
1378
1379   /// \brief Return a vector value that contains \arg V broadcasted to \p
1380   /// NumElts elements.
1381   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1382     assert(NumElts > 0 && "Cannot splat to an empty vector!");
1383
1384     // First insert it into an undef vector so we can shuffle it.
1385     Type *I32Ty = getInt32Ty();
1386     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1387     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1388                             Name + ".splatinsert");
1389
1390     // Shuffle the value across the desired number of elements.
1391     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1392     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1393   }
1394 };
1395
1396 // Create wrappers for C Binding types (see CBindingWrapping.h).
1397 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
1398
1399 }
1400
1401 #endif