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