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