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