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