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