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