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