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