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