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