]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/include/llvm/IR/IRBuilder.h
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / include / llvm / IR / IRBuilder.h
1 //===- llvm/IRBuilder.h - Builder for LLVM Instructions ---------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the IRBuilder class, which is used as a convenient way
10 // to create LLVM instructions with a consistent and simplified interface.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_IR_IRBUILDER_H
15 #define LLVM_IR_IRBUILDER_H
16
17 #include "llvm-c/Types.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/ConstantFolder.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/InstrTypes.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/Support/AtomicOrdering.h"
42 #include "llvm/Support/CBindingWrapping.h"
43 #include "llvm/Support/Casting.h"
44 #include <cassert>
45 #include <cstddef>
46 #include <cstdint>
47 #include <functional>
48 #include <utility>
49
50 namespace llvm {
51
52 class APInt;
53 class MDNode;
54 class Use;
55
56 /// This provides the default implementation of the IRBuilder
57 /// 'InsertHelper' method that is called whenever an instruction is created by
58 /// IRBuilder and needs to be inserted.
59 ///
60 /// By default, this inserts the instruction at the insertion point.
61 class IRBuilderDefaultInserter {
62 public:
63   virtual ~IRBuilderDefaultInserter();
64
65   virtual void InsertHelper(Instruction *I, const Twine &Name,
66                             BasicBlock *BB,
67                             BasicBlock::iterator InsertPt) const {
68     if (BB) BB->getInstList().insert(InsertPt, I);
69     I->setName(Name);
70   }
71 };
72
73 /// Provides an 'InsertHelper' that calls a user-provided callback after
74 /// performing the default insertion.
75 class IRBuilderCallbackInserter : public IRBuilderDefaultInserter {
76   std::function<void(Instruction *)> Callback;
77
78 public:
79   virtual ~IRBuilderCallbackInserter();
80
81   IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback)
82       : Callback(std::move(Callback)) {}
83
84   void InsertHelper(Instruction *I, const Twine &Name,
85                     BasicBlock *BB,
86                     BasicBlock::iterator InsertPt) const override {
87     IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
88     Callback(I);
89   }
90 };
91
92 /// Common base class shared among various IRBuilders.
93 class IRBuilderBase {
94   DebugLoc CurDbgLocation;
95
96 protected:
97   BasicBlock *BB;
98   BasicBlock::iterator InsertPt;
99   LLVMContext &Context;
100   const IRBuilderFolder &Folder;
101   const IRBuilderDefaultInserter &Inserter;
102
103   MDNode *DefaultFPMathTag;
104   FastMathFlags FMF;
105
106   bool IsFPConstrained;
107   fp::ExceptionBehavior DefaultConstrainedExcept;
108   RoundingMode DefaultConstrainedRounding;
109
110   ArrayRef<OperandBundleDef> DefaultOperandBundles;
111
112 public:
113   IRBuilderBase(LLVMContext &context, const IRBuilderFolder &Folder,
114                 const IRBuilderDefaultInserter &Inserter,
115                 MDNode *FPMathTag, ArrayRef<OperandBundleDef> OpBundles)
116       : Context(context), Folder(Folder), Inserter(Inserter),
117         DefaultFPMathTag(FPMathTag), IsFPConstrained(false),
118         DefaultConstrainedExcept(fp::ebStrict),
119         DefaultConstrainedRounding(RoundingMode::Dynamic),
120         DefaultOperandBundles(OpBundles) {
121     ClearInsertionPoint();
122   }
123
124   /// Insert and return the specified instruction.
125   template<typename InstTy>
126   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
127     Inserter.InsertHelper(I, Name, BB, InsertPt);
128     SetInstDebugLocation(I);
129     return I;
130   }
131
132   /// No-op overload to handle constants.
133   Constant *Insert(Constant *C, const Twine& = "") const {
134     return C;
135   }
136
137   Value *Insert(Value *V, const Twine &Name = "") const {
138     if (Instruction *I = dyn_cast<Instruction>(V))
139       return Insert(I, Name);
140     assert(isa<Constant>(V));
141     return V;
142   }
143
144   //===--------------------------------------------------------------------===//
145   // Builder configuration methods
146   //===--------------------------------------------------------------------===//
147
148   /// Clear the insertion point: created instructions will not be
149   /// inserted into a block.
150   void ClearInsertionPoint() {
151     BB = nullptr;
152     InsertPt = BasicBlock::iterator();
153   }
154
155   BasicBlock *GetInsertBlock() const { return BB; }
156   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
157   LLVMContext &getContext() const { return Context; }
158
159   /// This specifies that created instructions should be appended to the
160   /// end of the specified block.
161   void SetInsertPoint(BasicBlock *TheBB) {
162     BB = TheBB;
163     InsertPt = BB->end();
164   }
165
166   /// This specifies that created instructions should be inserted before
167   /// the specified instruction.
168   void SetInsertPoint(Instruction *I) {
169     BB = I->getParent();
170     InsertPt = I->getIterator();
171     assert(InsertPt != BB->end() && "Can't read debug loc from end()");
172     SetCurrentDebugLocation(I->getDebugLoc());
173   }
174
175   /// This specifies that created instructions should be inserted at the
176   /// specified point.
177   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
178     BB = TheBB;
179     InsertPt = IP;
180     if (IP != TheBB->end())
181       SetCurrentDebugLocation(IP->getDebugLoc());
182   }
183
184   /// Set location information used by debugging information.
185   void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
186
187   /// Get location information used by debugging information.
188   const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
189
190   /// If this builder has a current debug location, set it on the
191   /// specified instruction.
192   void SetInstDebugLocation(Instruction *I) const {
193     if (CurDbgLocation)
194       I->setDebugLoc(CurDbgLocation);
195   }
196
197   /// Get the return type of the current function that we're emitting
198   /// into.
199   Type *getCurrentFunctionReturnType() const;
200
201   /// InsertPoint - A saved insertion point.
202   class InsertPoint {
203     BasicBlock *Block = nullptr;
204     BasicBlock::iterator Point;
205
206   public:
207     /// Creates a new insertion point which doesn't point to anything.
208     InsertPoint() = default;
209
210     /// Creates a new insertion point at the given location.
211     InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
212         : Block(InsertBlock), Point(InsertPoint) {}
213
214     /// Returns true if this insert point is set.
215     bool isSet() const { return (Block != nullptr); }
216
217     BasicBlock *getBlock() const { return Block; }
218     BasicBlock::iterator getPoint() const { return Point; }
219   };
220
221   /// Returns the current insert point.
222   InsertPoint saveIP() const {
223     return InsertPoint(GetInsertBlock(), GetInsertPoint());
224   }
225
226   /// Returns the current insert point, clearing it in the process.
227   InsertPoint saveAndClearIP() {
228     InsertPoint IP(GetInsertBlock(), GetInsertPoint());
229     ClearInsertionPoint();
230     return IP;
231   }
232
233   /// Sets the current insert point to a previously-saved location.
234   void restoreIP(InsertPoint IP) {
235     if (IP.isSet())
236       SetInsertPoint(IP.getBlock(), IP.getPoint());
237     else
238       ClearInsertionPoint();
239   }
240
241   /// Get the floating point math metadata being used.
242   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
243
244   /// Get the flags to be applied to created floating point ops
245   FastMathFlags getFastMathFlags() const { return FMF; }
246
247   FastMathFlags &getFastMathFlags() { return FMF; }
248
249   /// Clear the fast-math flags.
250   void clearFastMathFlags() { FMF.clear(); }
251
252   /// Set the floating point math metadata to be used.
253   void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
254
255   /// Set the fast-math flags to be used with generated fp-math operators
256   void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
257
258   /// Enable/Disable use of constrained floating point math. When
259   /// enabled the CreateF<op>() calls instead create constrained
260   /// floating point intrinsic calls. Fast math flags are unaffected
261   /// by this setting.
262   void setIsFPConstrained(bool IsCon) { IsFPConstrained = IsCon; }
263
264   /// Query for the use of constrained floating point math
265   bool getIsFPConstrained() { return IsFPConstrained; }
266
267   /// Set the exception handling to be used with constrained floating point
268   void setDefaultConstrainedExcept(fp::ExceptionBehavior NewExcept) {
269     DefaultConstrainedExcept = NewExcept;
270   }
271
272   /// Set the rounding mode handling to be used with constrained floating point
273   void setDefaultConstrainedRounding(RoundingMode NewRounding) {
274     DefaultConstrainedRounding = NewRounding;
275   }
276
277   /// Get the exception handling used with constrained floating point
278   fp::ExceptionBehavior getDefaultConstrainedExcept() {
279     return DefaultConstrainedExcept;
280   }
281
282   /// Get the rounding mode handling used with constrained floating point
283   RoundingMode getDefaultConstrainedRounding() {
284     return DefaultConstrainedRounding;
285   }
286
287   void setConstrainedFPFunctionAttr() {
288     assert(BB && "Must have a basic block to set any function attributes!");
289
290     Function *F = BB->getParent();
291     if (!F->hasFnAttribute(Attribute::StrictFP)) {
292       F->addFnAttr(Attribute::StrictFP);
293     }
294   }
295
296   void setConstrainedFPCallAttr(CallInst *I) {
297     if (!I->hasFnAttr(Attribute::StrictFP))
298       I->addAttribute(AttributeList::FunctionIndex, Attribute::StrictFP);
299   }
300
301   void setDefaultOperandBundles(ArrayRef<OperandBundleDef> OpBundles) {
302     DefaultOperandBundles = OpBundles;
303   }
304
305   //===--------------------------------------------------------------------===//
306   // RAII helpers.
307   //===--------------------------------------------------------------------===//
308
309   // RAII object that stores the current insertion point and restores it
310   // when the object is destroyed. This includes the debug location.
311   class InsertPointGuard {
312     IRBuilderBase &Builder;
313     AssertingVH<BasicBlock> Block;
314     BasicBlock::iterator Point;
315     DebugLoc DbgLoc;
316
317   public:
318     InsertPointGuard(IRBuilderBase &B)
319         : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
320           DbgLoc(B.getCurrentDebugLocation()) {}
321
322     InsertPointGuard(const InsertPointGuard &) = delete;
323     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
324
325     ~InsertPointGuard() {
326       Builder.restoreIP(InsertPoint(Block, Point));
327       Builder.SetCurrentDebugLocation(DbgLoc);
328     }
329   };
330
331   // RAII object that stores the current fast math settings and restores
332   // them when the object is destroyed.
333   class FastMathFlagGuard {
334     IRBuilderBase &Builder;
335     FastMathFlags FMF;
336     MDNode *FPMathTag;
337     bool IsFPConstrained;
338     fp::ExceptionBehavior DefaultConstrainedExcept;
339     RoundingMode DefaultConstrainedRounding;
340
341   public:
342     FastMathFlagGuard(IRBuilderBase &B)
343         : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag),
344           IsFPConstrained(B.IsFPConstrained),
345           DefaultConstrainedExcept(B.DefaultConstrainedExcept),
346           DefaultConstrainedRounding(B.DefaultConstrainedRounding) {}
347
348     FastMathFlagGuard(const FastMathFlagGuard &) = delete;
349     FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
350
351     ~FastMathFlagGuard() {
352       Builder.FMF = FMF;
353       Builder.DefaultFPMathTag = FPMathTag;
354       Builder.IsFPConstrained = IsFPConstrained;
355       Builder.DefaultConstrainedExcept = DefaultConstrainedExcept;
356       Builder.DefaultConstrainedRounding = DefaultConstrainedRounding;
357     }
358   };
359
360   // RAII object that stores the current default operand bundles and restores
361   // them when the object is destroyed.
362   class OperandBundlesGuard {
363     IRBuilderBase &Builder;
364     ArrayRef<OperandBundleDef> DefaultOperandBundles;
365
366   public:
367     OperandBundlesGuard(IRBuilderBase &B)
368         : Builder(B), DefaultOperandBundles(B.DefaultOperandBundles) {}
369
370     OperandBundlesGuard(const OperandBundlesGuard &) = delete;
371     OperandBundlesGuard &operator=(const OperandBundlesGuard &) = delete;
372
373     ~OperandBundlesGuard() {
374       Builder.DefaultOperandBundles = DefaultOperandBundles;
375     }
376   };
377
378
379   //===--------------------------------------------------------------------===//
380   // Miscellaneous creation methods.
381   //===--------------------------------------------------------------------===//
382
383   /// Make a new global variable with initializer type i8*
384   ///
385   /// Make a new global variable with an initializer that has array of i8 type
386   /// filled in with the null terminated string value specified.  The new global
387   /// variable will be marked mergable with any others of the same contents.  If
388   /// Name is specified, it is the name of the global variable created.
389   GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
390                                      unsigned AddressSpace = 0);
391
392   /// Get a constant value representing either true or false.
393   ConstantInt *getInt1(bool V) {
394     return ConstantInt::get(getInt1Ty(), V);
395   }
396
397   /// Get the constant value for i1 true.
398   ConstantInt *getTrue() {
399     return ConstantInt::getTrue(Context);
400   }
401
402   /// Get the constant value for i1 false.
403   ConstantInt *getFalse() {
404     return ConstantInt::getFalse(Context);
405   }
406
407   /// Get a constant 8-bit value.
408   ConstantInt *getInt8(uint8_t C) {
409     return ConstantInt::get(getInt8Ty(), C);
410   }
411
412   /// Get a constant 16-bit value.
413   ConstantInt *getInt16(uint16_t C) {
414     return ConstantInt::get(getInt16Ty(), C);
415   }
416
417   /// Get a constant 32-bit value.
418   ConstantInt *getInt32(uint32_t C) {
419     return ConstantInt::get(getInt32Ty(), C);
420   }
421
422   /// Get a constant 64-bit value.
423   ConstantInt *getInt64(uint64_t C) {
424     return ConstantInt::get(getInt64Ty(), C);
425   }
426
427   /// Get a constant N-bit value, zero extended or truncated from
428   /// a 64-bit value.
429   ConstantInt *getIntN(unsigned N, uint64_t C) {
430     return ConstantInt::get(getIntNTy(N), C);
431   }
432
433   /// Get a constant integer value.
434   ConstantInt *getInt(const APInt &AI) {
435     return ConstantInt::get(Context, AI);
436   }
437
438   //===--------------------------------------------------------------------===//
439   // Type creation methods
440   //===--------------------------------------------------------------------===//
441
442   /// Fetch the type representing a single bit
443   IntegerType *getInt1Ty() {
444     return Type::getInt1Ty(Context);
445   }
446
447   /// Fetch the type representing an 8-bit integer.
448   IntegerType *getInt8Ty() {
449     return Type::getInt8Ty(Context);
450   }
451
452   /// Fetch the type representing a 16-bit integer.
453   IntegerType *getInt16Ty() {
454     return Type::getInt16Ty(Context);
455   }
456
457   /// Fetch the type representing a 32-bit integer.
458   IntegerType *getInt32Ty() {
459     return Type::getInt32Ty(Context);
460   }
461
462   /// Fetch the type representing a 64-bit integer.
463   IntegerType *getInt64Ty() {
464     return Type::getInt64Ty(Context);
465   }
466
467   /// Fetch the type representing a 128-bit integer.
468   IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
469
470   /// Fetch the type representing an N-bit integer.
471   IntegerType *getIntNTy(unsigned N) {
472     return Type::getIntNTy(Context, N);
473   }
474
475   /// Fetch the type representing a 16-bit floating point value.
476   Type *getHalfTy() {
477     return Type::getHalfTy(Context);
478   }
479
480   /// Fetch the type representing a 16-bit brain floating point value.
481   Type *getBFloatTy() {
482     return Type::getBFloatTy(Context);
483   }
484
485   /// Fetch the type representing a 32-bit floating point value.
486   Type *getFloatTy() {
487     return Type::getFloatTy(Context);
488   }
489
490   /// Fetch the type representing a 64-bit floating point value.
491   Type *getDoubleTy() {
492     return Type::getDoubleTy(Context);
493   }
494
495   /// Fetch the type representing void.
496   Type *getVoidTy() {
497     return Type::getVoidTy(Context);
498   }
499
500   /// Fetch the type representing a pointer to an 8-bit integer value.
501   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
502     return Type::getInt8PtrTy(Context, AddrSpace);
503   }
504
505   /// Fetch the type representing a pointer to an integer value.
506   IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
507     return DL.getIntPtrType(Context, AddrSpace);
508   }
509
510   //===--------------------------------------------------------------------===//
511   // Intrinsic creation methods
512   //===--------------------------------------------------------------------===//
513
514   /// Create and insert a memset to the specified pointer and the
515   /// specified value.
516   ///
517   /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
518   /// specified, it will be added to the instruction. Likewise with alias.scope
519   /// and noalias tags.
520   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size,
521                          MaybeAlign Align, bool isVolatile = false,
522                          MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr,
523                          MDNode *NoAliasTag = nullptr) {
524     return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
525                         TBAATag, ScopeTag, NoAliasTag);
526   }
527
528   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, MaybeAlign Align,
529                          bool isVolatile = false, MDNode *TBAATag = nullptr,
530                          MDNode *ScopeTag = nullptr,
531                          MDNode *NoAliasTag = nullptr);
532
533   /// Create and insert an element unordered-atomic memset of the region of
534   /// memory starting at the given pointer to the given value.
535   ///
536   /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
537   /// specified, it will be added to the instruction. Likewise with alias.scope
538   /// and noalias tags.
539   CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
540                                                uint64_t Size, Align Alignment,
541                                                uint32_t ElementSize,
542                                                MDNode *TBAATag = nullptr,
543                                                MDNode *ScopeTag = nullptr,
544                                                MDNode *NoAliasTag = nullptr) {
545     return CreateElementUnorderedAtomicMemSet(Ptr, Val, getInt64(Size),
546                                               Align(Alignment), ElementSize,
547                                               TBAATag, ScopeTag, NoAliasTag);
548   }
549
550   CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
551                                                Value *Size, Align Alignment,
552                                                uint32_t ElementSize,
553                                                MDNode *TBAATag = nullptr,
554                                                MDNode *ScopeTag = nullptr,
555                                                MDNode *NoAliasTag = nullptr);
556
557   /// Create and insert a memcpy between the specified pointers.
558   ///
559   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
560   /// specified, it will be added to the instruction. Likewise with alias.scope
561   /// and noalias tags.
562   CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
563                          MaybeAlign SrcAlign, uint64_t Size,
564                          bool isVolatile = false, MDNode *TBAATag = nullptr,
565                          MDNode *TBAAStructTag = nullptr,
566                          MDNode *ScopeTag = nullptr,
567                          MDNode *NoAliasTag = nullptr) {
568     return CreateMemCpy(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
569                         isVolatile, TBAATag, TBAAStructTag, ScopeTag,
570                         NoAliasTag);
571   }
572
573   CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
574                          MaybeAlign SrcAlign, Value *Size,
575                          bool isVolatile = false, MDNode *TBAATag = nullptr,
576                          MDNode *TBAAStructTag = nullptr,
577                          MDNode *ScopeTag = nullptr,
578                          MDNode *NoAliasTag = nullptr);
579
580   CallInst *CreateMemCpyInline(Value *Dst, MaybeAlign DstAlign, Value *Src,
581                                MaybeAlign SrcAlign, Value *Size);
582
583   /// Create and insert an element unordered-atomic memcpy between the
584   /// specified pointers.
585   ///
586   /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers, respectively.
587   ///
588   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
589   /// specified, it will be added to the instruction. Likewise with alias.scope
590   /// and noalias tags.
591   CallInst *CreateElementUnorderedAtomicMemCpy(
592       Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
593       uint32_t ElementSize, MDNode *TBAATag = nullptr,
594       MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
595       MDNode *NoAliasTag = nullptr);
596
597   LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateElementUnorderedAtomicMemCpy(
598                                 Value *Dst, unsigned DstAlign, Value *Src,
599                                 unsigned SrcAlign, uint64_t Size,
600                                 uint32_t ElementSize, MDNode *TBAATag = nullptr,
601                                 MDNode *TBAAStructTag = nullptr,
602                                 MDNode *ScopeTag = nullptr,
603                                 MDNode *NoAliasTag = nullptr),
604                             "Use the version that takes Align instead") {
605     return CreateElementUnorderedAtomicMemCpy(
606         Dst, Align(DstAlign), Src, Align(SrcAlign), getInt64(Size), ElementSize,
607         TBAATag, TBAAStructTag, ScopeTag, NoAliasTag);
608   }
609
610   LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateElementUnorderedAtomicMemCpy(
611                                 Value *Dst, unsigned DstAlign, Value *Src,
612                                 unsigned SrcAlign, Value *Size,
613                                 uint32_t ElementSize, MDNode *TBAATag = nullptr,
614                                 MDNode *TBAAStructTag = nullptr,
615                                 MDNode *ScopeTag = nullptr,
616                                 MDNode *NoAliasTag = nullptr),
617                             "Use the version that takes Align instead") {
618     return CreateElementUnorderedAtomicMemCpy(
619         Dst, Align(DstAlign), Src, Align(SrcAlign), Size, ElementSize, TBAATag,
620         TBAAStructTag, ScopeTag, NoAliasTag);
621   }
622
623   CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
624                           MaybeAlign SrcAlign, uint64_t Size,
625                           bool isVolatile = false, MDNode *TBAATag = nullptr,
626                           MDNode *ScopeTag = nullptr,
627                           MDNode *NoAliasTag = nullptr) {
628     return CreateMemMove(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
629                          isVolatile, TBAATag, ScopeTag, NoAliasTag);
630   }
631
632   CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
633                           MaybeAlign SrcAlign, Value *Size,
634                           bool isVolatile = false, MDNode *TBAATag = nullptr,
635                           MDNode *ScopeTag = nullptr,
636                           MDNode *NoAliasTag = nullptr);
637
638   /// \brief Create and insert an element unordered-atomic memmove between the
639   /// specified pointers.
640   ///
641   /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers,
642   /// respectively.
643   ///
644   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
645   /// specified, it will be added to the instruction. Likewise with alias.scope
646   /// and noalias tags.
647   CallInst *CreateElementUnorderedAtomicMemMove(
648       Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
649       uint32_t ElementSize, MDNode *TBAATag = nullptr,
650       MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
651       MDNode *NoAliasTag = nullptr);
652
653   LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateElementUnorderedAtomicMemMove(
654                                 Value *Dst, unsigned DstAlign, Value *Src,
655                                 unsigned SrcAlign, uint64_t Size,
656                                 uint32_t ElementSize, MDNode *TBAATag = nullptr,
657                                 MDNode *TBAAStructTag = nullptr,
658                                 MDNode *ScopeTag = nullptr,
659                                 MDNode *NoAliasTag = nullptr),
660                             "Use the version that takes Align instead") {
661     return CreateElementUnorderedAtomicMemMove(
662         Dst, Align(DstAlign), Src, Align(SrcAlign), getInt64(Size), ElementSize,
663         TBAATag, TBAAStructTag, ScopeTag, NoAliasTag);
664   }
665
666   LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateElementUnorderedAtomicMemMove(
667                                 Value *Dst, unsigned DstAlign, Value *Src,
668                                 unsigned SrcAlign, Value *Size,
669                                 uint32_t ElementSize, MDNode *TBAATag = nullptr,
670                                 MDNode *TBAAStructTag = nullptr,
671                                 MDNode *ScopeTag = nullptr,
672                                 MDNode *NoAliasTag = nullptr),
673                             "Use the version that takes Align instead") {
674     return CreateElementUnorderedAtomicMemMove(
675         Dst, Align(DstAlign), Src, Align(SrcAlign), Size, ElementSize, TBAATag,
676         TBAAStructTag, ScopeTag, NoAliasTag);
677   }
678
679   /// Create a vector fadd reduction intrinsic of the source vector.
680   /// The first parameter is a scalar accumulator value for ordered reductions.
681   CallInst *CreateFAddReduce(Value *Acc, Value *Src);
682
683   /// Create a vector fmul reduction intrinsic of the source vector.
684   /// The first parameter is a scalar accumulator value for ordered reductions.
685   CallInst *CreateFMulReduce(Value *Acc, Value *Src);
686
687   /// Create a vector int add reduction intrinsic of the source vector.
688   CallInst *CreateAddReduce(Value *Src);
689
690   /// Create a vector int mul reduction intrinsic of the source vector.
691   CallInst *CreateMulReduce(Value *Src);
692
693   /// Create a vector int AND reduction intrinsic of the source vector.
694   CallInst *CreateAndReduce(Value *Src);
695
696   /// Create a vector int OR reduction intrinsic of the source vector.
697   CallInst *CreateOrReduce(Value *Src);
698
699   /// Create a vector int XOR reduction intrinsic of the source vector.
700   CallInst *CreateXorReduce(Value *Src);
701
702   /// Create a vector integer max reduction intrinsic of the source
703   /// vector.
704   CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false);
705
706   /// Create a vector integer min reduction intrinsic of the source
707   /// vector.
708   CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false);
709
710   /// Create a vector float max reduction intrinsic of the source
711   /// vector.
712   CallInst *CreateFPMaxReduce(Value *Src, bool NoNaN = false);
713
714   /// Create a vector float min reduction intrinsic of the source
715   /// vector.
716   CallInst *CreateFPMinReduce(Value *Src, bool NoNaN = false);
717
718   /// Create a lifetime.start intrinsic.
719   ///
720   /// If the pointer isn't i8* it will be converted.
721   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
722
723   /// Create a lifetime.end intrinsic.
724   ///
725   /// If the pointer isn't i8* it will be converted.
726   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
727
728   /// Create a call to invariant.start intrinsic.
729   ///
730   /// If the pointer isn't i8* it will be converted.
731   CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr);
732
733   /// Create a call to Masked Load intrinsic
734   LLVM_ATTRIBUTE_DEPRECATED(
735       CallInst *CreateMaskedLoad(Value *Ptr, unsigned Alignment, Value *Mask,
736                                  Value *PassThru = nullptr,
737                                  const Twine &Name = ""),
738       "Use the version that takes Align instead") {
739     return CreateMaskedLoad(Ptr, assumeAligned(Alignment), Mask, PassThru,
740                             Name);
741   }
742   CallInst *CreateMaskedLoad(Value *Ptr, Align Alignment, Value *Mask,
743                              Value *PassThru = nullptr, const Twine &Name = "");
744
745   /// Create a call to Masked Store intrinsic
746   LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateMaskedStore(Value *Val, Value *Ptr,
747                                                         unsigned Alignment,
748                                                         Value *Mask),
749                             "Use the version that takes Align instead") {
750     return CreateMaskedStore(Val, Ptr, assumeAligned(Alignment), Mask);
751   }
752
753   CallInst *CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment,
754                               Value *Mask);
755
756   /// Create a call to Masked Gather intrinsic
757   LLVM_ATTRIBUTE_DEPRECATED(
758       CallInst *CreateMaskedGather(Value *Ptrs, unsigned Alignment,
759                                    Value *Mask = nullptr,
760                                    Value *PassThru = nullptr,
761                                    const Twine &Name = ""),
762       "Use the version that takes Align instead") {
763     return CreateMaskedGather(Ptrs, Align(Alignment), Mask, PassThru, Name);
764   }
765
766   /// Create a call to Masked Gather intrinsic
767   CallInst *CreateMaskedGather(Value *Ptrs, Align Alignment,
768                                Value *Mask = nullptr, Value *PassThru = nullptr,
769                                const Twine &Name = "");
770
771   /// Create a call to Masked Scatter intrinsic
772   LLVM_ATTRIBUTE_DEPRECATED(
773       CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned Alignment,
774                                     Value *Mask = nullptr),
775       "Use the version that takes Align instead") {
776     return CreateMaskedScatter(Val, Ptrs, Align(Alignment), Mask);
777   }
778
779   /// Create a call to Masked Scatter intrinsic
780   CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, Align Alignment,
781                                 Value *Mask = nullptr);
782
783   /// Create an assume intrinsic call that allows the optimizer to
784   /// assume that the provided condition will be true.
785   CallInst *CreateAssumption(Value *Cond);
786
787   /// Create a call to the experimental.gc.statepoint intrinsic to
788   /// start a new statepoint sequence.
789   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
790                                    Value *ActualCallee,
791                                    ArrayRef<Value *> CallArgs,
792                                    Optional<ArrayRef<Value *>> DeoptArgs,
793                                    ArrayRef<Value *> GCArgs,
794                                    const Twine &Name = "");
795
796   /// Create a call to the experimental.gc.statepoint intrinsic to
797   /// start a new statepoint sequence.
798   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
799                                    Value *ActualCallee, uint32_t Flags,
800                                    ArrayRef<Use> CallArgs,
801                                    Optional<ArrayRef<Use>> TransitionArgs,
802                                    Optional<ArrayRef<Use>> DeoptArgs,
803                                    ArrayRef<Value *> GCArgs,
804                                    const Twine &Name = "");
805
806   /// Conveninence function for the common case when CallArgs are filled
807   /// in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
808   /// .get()'ed to get the Value pointer.
809   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
810                                    Value *ActualCallee, ArrayRef<Use> CallArgs,
811                                    Optional<ArrayRef<Value *>> DeoptArgs,
812                                    ArrayRef<Value *> GCArgs,
813                                    const Twine &Name = "");
814
815   /// Create an invoke to the experimental.gc.statepoint intrinsic to
816   /// start a new statepoint sequence.
817   InvokeInst *
818   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
819                            Value *ActualInvokee, BasicBlock *NormalDest,
820                            BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
821                            Optional<ArrayRef<Value *>> DeoptArgs,
822                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
823
824   /// Create an invoke to the experimental.gc.statepoint intrinsic to
825   /// start a new statepoint sequence.
826   InvokeInst *CreateGCStatepointInvoke(
827       uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
828       BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
829       ArrayRef<Use> InvokeArgs, Optional<ArrayRef<Use>> TransitionArgs,
830       Optional<ArrayRef<Use>> DeoptArgs, ArrayRef<Value *> GCArgs,
831       const Twine &Name = "");
832
833   // Convenience function for the common case when CallArgs are filled in using
834   // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
835   // get the Value *.
836   InvokeInst *
837   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
838                            Value *ActualInvokee, BasicBlock *NormalDest,
839                            BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
840                            Optional<ArrayRef<Value *>> DeoptArgs,
841                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
842
843   /// Create a call to the experimental.gc.result intrinsic to extract
844   /// the result from a call wrapped in a statepoint.
845   CallInst *CreateGCResult(Instruction *Statepoint,
846                            Type *ResultType,
847                            const Twine &Name = "");
848
849   /// Create a call to the experimental.gc.relocate intrinsics to
850   /// project the relocated value of one pointer from the statepoint.
851   CallInst *CreateGCRelocate(Instruction *Statepoint,
852                              int BaseOffset,
853                              int DerivedOffset,
854                              Type *ResultType,
855                              const Twine &Name = "");
856
857   /// Create a call to intrinsic \p ID with 1 operand which is mangled on its
858   /// type.
859   CallInst *CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V,
860                                  Instruction *FMFSource = nullptr,
861                                  const Twine &Name = "");
862
863   /// Create a call to intrinsic \p ID with 2 operands which is mangled on the
864   /// first type.
865   CallInst *CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS,
866                                   Instruction *FMFSource = nullptr,
867                                   const Twine &Name = "");
868
869   /// Create a call to intrinsic \p ID with \p args, mangled using \p Types. If
870   /// \p FMFSource is provided, copy fast-math-flags from that instruction to
871   /// the intrinsic.
872   CallInst *CreateIntrinsic(Intrinsic::ID ID, ArrayRef<Type *> Types,
873                             ArrayRef<Value *> Args,
874                             Instruction *FMFSource = nullptr,
875                             const Twine &Name = "");
876
877   /// Create call to the minnum intrinsic.
878   CallInst *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") {
879     return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, nullptr, Name);
880   }
881
882   /// Create call to the maxnum intrinsic.
883   CallInst *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") {
884     return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, nullptr, Name);
885   }
886
887   /// Create call to the minimum intrinsic.
888   CallInst *CreateMinimum(Value *LHS, Value *RHS, const Twine &Name = "") {
889     return CreateBinaryIntrinsic(Intrinsic::minimum, LHS, RHS, nullptr, Name);
890   }
891
892   /// Create call to the maximum intrinsic.
893   CallInst *CreateMaximum(Value *LHS, Value *RHS, const Twine &Name = "") {
894     return CreateBinaryIntrinsic(Intrinsic::maximum, LHS, RHS, nullptr, Name);
895   }
896
897 private:
898   /// Create a call to a masked intrinsic with given Id.
899   CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
900                                   ArrayRef<Type *> OverloadedTypes,
901                                   const Twine &Name = "");
902
903   Value *getCastedInt8PtrValue(Value *Ptr);
904
905   //===--------------------------------------------------------------------===//
906   // Instruction creation methods: Terminators
907   //===--------------------------------------------------------------------===//
908
909 private:
910   /// Helper to add branch weight and unpredictable metadata onto an
911   /// instruction.
912   /// \returns The annotated instruction.
913   template <typename InstTy>
914   InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
915     if (Weights)
916       I->setMetadata(LLVMContext::MD_prof, Weights);
917     if (Unpredictable)
918       I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
919     return I;
920   }
921
922 public:
923   /// Create a 'ret void' instruction.
924   ReturnInst *CreateRetVoid() {
925     return Insert(ReturnInst::Create(Context));
926   }
927
928   /// Create a 'ret <val>' instruction.
929   ReturnInst *CreateRet(Value *V) {
930     return Insert(ReturnInst::Create(Context, V));
931   }
932
933   /// Create a sequence of N insertvalue instructions,
934   /// with one Value from the retVals array each, that build a aggregate
935   /// return value one value at a time, and a ret instruction to return
936   /// the resulting aggregate value.
937   ///
938   /// This is a convenience function for code that uses aggregate return values
939   /// as a vehicle for having multiple return values.
940   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
941     Value *V = UndefValue::get(getCurrentFunctionReturnType());
942     for (unsigned i = 0; i != N; ++i)
943       V = CreateInsertValue(V, retVals[i], i, "mrv");
944     return Insert(ReturnInst::Create(Context, V));
945   }
946
947   /// Create an unconditional 'br label X' instruction.
948   BranchInst *CreateBr(BasicBlock *Dest) {
949     return Insert(BranchInst::Create(Dest));
950   }
951
952   /// Create a conditional 'br Cond, TrueDest, FalseDest'
953   /// instruction.
954   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
955                            MDNode *BranchWeights = nullptr,
956                            MDNode *Unpredictable = nullptr) {
957     return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
958                                     BranchWeights, Unpredictable));
959   }
960
961   /// Create a conditional 'br Cond, TrueDest, FalseDest'
962   /// instruction. Copy branch meta data if available.
963   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
964                            Instruction *MDSrc) {
965     BranchInst *Br = BranchInst::Create(True, False, Cond);
966     if (MDSrc) {
967       unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
968                         LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
969       Br->copyMetadata(*MDSrc, makeArrayRef(&WL[0], 4));
970     }
971     return Insert(Br);
972   }
973
974   /// Create a switch instruction with the specified value, default dest,
975   /// and with a hint for the number of cases that will be added (for efficient
976   /// allocation).
977   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
978                            MDNode *BranchWeights = nullptr,
979                            MDNode *Unpredictable = nullptr) {
980     return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
981                                     BranchWeights, Unpredictable));
982   }
983
984   /// Create an indirect branch instruction with the specified address
985   /// operand, with an optional hint for the number of destinations that will be
986   /// added (for efficient allocation).
987   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
988     return Insert(IndirectBrInst::Create(Addr, NumDests));
989   }
990
991   /// Create an invoke instruction.
992   InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
993                            BasicBlock *NormalDest, BasicBlock *UnwindDest,
994                            ArrayRef<Value *> Args,
995                            ArrayRef<OperandBundleDef> OpBundles,
996                            const Twine &Name = "") {
997     return Insert(
998         InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args, OpBundles),
999         Name);
1000   }
1001   InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
1002                            BasicBlock *NormalDest, BasicBlock *UnwindDest,
1003                            ArrayRef<Value *> Args = None,
1004                            const Twine &Name = "") {
1005     return Insert(InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args),
1006                   Name);
1007   }
1008
1009   InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
1010                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
1011                            ArrayRef<OperandBundleDef> OpBundles,
1012                            const Twine &Name = "") {
1013     return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
1014                         NormalDest, UnwindDest, Args, OpBundles, Name);
1015   }
1016
1017   InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
1018                            BasicBlock *UnwindDest,
1019                            ArrayRef<Value *> Args = None,
1020                            const Twine &Name = "") {
1021     return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
1022                         NormalDest, UnwindDest, Args, Name);
1023   }
1024
1025   /// \brief Create a callbr instruction.
1026   CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
1027                            BasicBlock *DefaultDest,
1028                            ArrayRef<BasicBlock *> IndirectDests,
1029                            ArrayRef<Value *> Args = None,
1030                            const Twine &Name = "") {
1031     return Insert(CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests,
1032                                      Args), Name);
1033   }
1034   CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
1035                            BasicBlock *DefaultDest,
1036                            ArrayRef<BasicBlock *> IndirectDests,
1037                            ArrayRef<Value *> Args,
1038                            ArrayRef<OperandBundleDef> OpBundles,
1039                            const Twine &Name = "") {
1040     return Insert(
1041         CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
1042                            OpBundles), Name);
1043   }
1044
1045   CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
1046                            ArrayRef<BasicBlock *> IndirectDests,
1047                            ArrayRef<Value *> Args = None,
1048                            const Twine &Name = "") {
1049     return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
1050                         DefaultDest, IndirectDests, Args, Name);
1051   }
1052   CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
1053                            ArrayRef<BasicBlock *> IndirectDests,
1054                            ArrayRef<Value *> Args,
1055                            ArrayRef<OperandBundleDef> OpBundles,
1056                            const Twine &Name = "") {
1057     return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
1058                         DefaultDest, IndirectDests, Args, Name);
1059   }
1060
1061   ResumeInst *CreateResume(Value *Exn) {
1062     return Insert(ResumeInst::Create(Exn));
1063   }
1064
1065   CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
1066                                       BasicBlock *UnwindBB = nullptr) {
1067     return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
1068   }
1069
1070   CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
1071                                      unsigned NumHandlers,
1072                                      const Twine &Name = "") {
1073     return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
1074                   Name);
1075   }
1076
1077   CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
1078                                const Twine &Name = "") {
1079     return Insert(CatchPadInst::Create(ParentPad, Args), Name);
1080   }
1081
1082   CleanupPadInst *CreateCleanupPad(Value *ParentPad,
1083                                    ArrayRef<Value *> Args = None,
1084                                    const Twine &Name = "") {
1085     return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
1086   }
1087
1088   CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
1089     return Insert(CatchReturnInst::Create(CatchPad, BB));
1090   }
1091
1092   UnreachableInst *CreateUnreachable() {
1093     return Insert(new UnreachableInst(Context));
1094   }
1095
1096   //===--------------------------------------------------------------------===//
1097   // Instruction creation methods: Binary Operators
1098   //===--------------------------------------------------------------------===//
1099 private:
1100   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
1101                                           Value *LHS, Value *RHS,
1102                                           const Twine &Name,
1103                                           bool HasNUW, bool HasNSW) {
1104     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
1105     if (HasNUW) BO->setHasNoUnsignedWrap();
1106     if (HasNSW) BO->setHasNoSignedWrap();
1107     return BO;
1108   }
1109
1110   Instruction *setFPAttrs(Instruction *I, MDNode *FPMD,
1111                           FastMathFlags FMF) const {
1112     if (!FPMD)
1113       FPMD = DefaultFPMathTag;
1114     if (FPMD)
1115       I->setMetadata(LLVMContext::MD_fpmath, FPMD);
1116     I->setFastMathFlags(FMF);
1117     return I;
1118   }
1119
1120   Value *foldConstant(Instruction::BinaryOps Opc, Value *L,
1121                       Value *R, const Twine &Name) const {
1122     auto *LC = dyn_cast<Constant>(L);
1123     auto *RC = dyn_cast<Constant>(R);
1124     return (LC && RC) ? Insert(Folder.CreateBinOp(Opc, LC, RC), Name) : nullptr;
1125   }
1126
1127   Value *getConstrainedFPRounding(Optional<RoundingMode> Rounding) {
1128     RoundingMode UseRounding = DefaultConstrainedRounding;
1129
1130     if (Rounding.hasValue())
1131       UseRounding = Rounding.getValue();
1132
1133     Optional<StringRef> RoundingStr = RoundingModeToStr(UseRounding);
1134     assert(RoundingStr.hasValue() && "Garbage strict rounding mode!");
1135     auto *RoundingMDS = MDString::get(Context, RoundingStr.getValue());
1136
1137     return MetadataAsValue::get(Context, RoundingMDS);
1138   }
1139
1140   Value *getConstrainedFPExcept(Optional<fp::ExceptionBehavior> Except) {
1141     fp::ExceptionBehavior UseExcept = DefaultConstrainedExcept;
1142
1143     if (Except.hasValue())
1144       UseExcept = Except.getValue();
1145
1146     Optional<StringRef> ExceptStr = ExceptionBehaviorToStr(UseExcept);
1147     assert(ExceptStr.hasValue() && "Garbage strict exception behavior!");
1148     auto *ExceptMDS = MDString::get(Context, ExceptStr.getValue());
1149
1150     return MetadataAsValue::get(Context, ExceptMDS);
1151   }
1152
1153   Value *getConstrainedFPPredicate(CmpInst::Predicate Predicate) {
1154     assert(CmpInst::isFPPredicate(Predicate) &&
1155            Predicate != CmpInst::FCMP_FALSE &&
1156            Predicate != CmpInst::FCMP_TRUE &&
1157            "Invalid constrained FP comparison predicate!");
1158
1159     StringRef PredicateStr = CmpInst::getPredicateName(Predicate);
1160     auto *PredicateMDS = MDString::get(Context, PredicateStr);
1161
1162     return MetadataAsValue::get(Context, PredicateMDS);
1163   }
1164
1165 public:
1166   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
1167                    bool HasNUW = false, bool HasNSW = false) {
1168     if (auto *LC = dyn_cast<Constant>(LHS))
1169       if (auto *RC = dyn_cast<Constant>(RHS))
1170         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
1171     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
1172                                    HasNUW, HasNSW);
1173   }
1174
1175   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
1176     return CreateAdd(LHS, RHS, Name, false, true);
1177   }
1178
1179   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
1180     return CreateAdd(LHS, RHS, Name, true, false);
1181   }
1182
1183   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
1184                    bool HasNUW = false, bool HasNSW = false) {
1185     if (auto *LC = dyn_cast<Constant>(LHS))
1186       if (auto *RC = dyn_cast<Constant>(RHS))
1187         return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
1188     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
1189                                    HasNUW, HasNSW);
1190   }
1191
1192   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
1193     return CreateSub(LHS, RHS, Name, false, true);
1194   }
1195
1196   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
1197     return CreateSub(LHS, RHS, Name, true, false);
1198   }
1199
1200   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
1201                    bool HasNUW = false, bool HasNSW = false) {
1202     if (auto *LC = dyn_cast<Constant>(LHS))
1203       if (auto *RC = dyn_cast<Constant>(RHS))
1204         return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
1205     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
1206                                    HasNUW, HasNSW);
1207   }
1208
1209   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1210     return CreateMul(LHS, RHS, Name, false, true);
1211   }
1212
1213   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1214     return CreateMul(LHS, RHS, Name, true, false);
1215   }
1216
1217   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1218                     bool isExact = false) {
1219     if (auto *LC = dyn_cast<Constant>(LHS))
1220       if (auto *RC = dyn_cast<Constant>(RHS))
1221         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
1222     if (!isExact)
1223       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
1224     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
1225   }
1226
1227   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1228     return CreateUDiv(LHS, RHS, Name, true);
1229   }
1230
1231   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1232                     bool isExact = false) {
1233     if (auto *LC = dyn_cast<Constant>(LHS))
1234       if (auto *RC = dyn_cast<Constant>(RHS))
1235         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
1236     if (!isExact)
1237       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
1238     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
1239   }
1240
1241   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1242     return CreateSDiv(LHS, RHS, Name, true);
1243   }
1244
1245   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
1246     if (Value *V = foldConstant(Instruction::URem, LHS, RHS, Name)) return V;
1247     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
1248   }
1249
1250   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
1251     if (Value *V = foldConstant(Instruction::SRem, LHS, RHS, Name)) return V;
1252     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
1253   }
1254
1255   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
1256                    bool HasNUW = false, bool HasNSW = false) {
1257     if (auto *LC = dyn_cast<Constant>(LHS))
1258       if (auto *RC = dyn_cast<Constant>(RHS))
1259         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
1260     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
1261                                    HasNUW, HasNSW);
1262   }
1263
1264   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
1265                    bool HasNUW = false, bool HasNSW = false) {
1266     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1267                      HasNUW, HasNSW);
1268   }
1269
1270   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
1271                    bool HasNUW = false, bool HasNSW = false) {
1272     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1273                      HasNUW, HasNSW);
1274   }
1275
1276   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
1277                     bool isExact = false) {
1278     if (auto *LC = dyn_cast<Constant>(LHS))
1279       if (auto *RC = dyn_cast<Constant>(RHS))
1280         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
1281     if (!isExact)
1282       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
1283     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
1284   }
1285
1286   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1287                     bool isExact = false) {
1288     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1289   }
1290
1291   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1292                     bool isExact = false) {
1293     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1294   }
1295
1296   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
1297                     bool isExact = false) {
1298     if (auto *LC = dyn_cast<Constant>(LHS))
1299       if (auto *RC = dyn_cast<Constant>(RHS))
1300         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
1301     if (!isExact)
1302       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
1303     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
1304   }
1305
1306   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1307                     bool isExact = false) {
1308     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1309   }
1310
1311   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1312                     bool isExact = false) {
1313     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1314   }
1315
1316   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
1317     if (auto *RC = dyn_cast<Constant>(RHS)) {
1318       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isMinusOne())
1319         return LHS;  // LHS & -1 -> LHS
1320       if (auto *LC = dyn_cast<Constant>(LHS))
1321         return Insert(Folder.CreateAnd(LC, RC), Name);
1322     }
1323     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
1324   }
1325
1326   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1327     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1328   }
1329
1330   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1331     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1332   }
1333
1334   Value *CreateAnd(ArrayRef<Value*> Ops) {
1335     assert(!Ops.empty());
1336     Value *Accum = Ops[0];
1337     for (unsigned i = 1; i < Ops.size(); i++)
1338       Accum = CreateAnd(Accum, Ops[i]);
1339     return Accum;
1340   }
1341
1342   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
1343     if (auto *RC = dyn_cast<Constant>(RHS)) {
1344       if (RC->isNullValue())
1345         return LHS;  // LHS | 0 -> LHS
1346       if (auto *LC = dyn_cast<Constant>(LHS))
1347         return Insert(Folder.CreateOr(LC, RC), Name);
1348     }
1349     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
1350   }
1351
1352   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1353     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1354   }
1355
1356   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1357     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1358   }
1359
1360   Value *CreateOr(ArrayRef<Value*> Ops) {
1361     assert(!Ops.empty());
1362     Value *Accum = Ops[0];
1363     for (unsigned i = 1; i < Ops.size(); i++)
1364       Accum = CreateOr(Accum, Ops[i]);
1365     return Accum;
1366   }
1367
1368   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
1369     if (Value *V = foldConstant(Instruction::Xor, LHS, RHS, Name)) return V;
1370     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
1371   }
1372
1373   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1374     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1375   }
1376
1377   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1378     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1379   }
1380
1381   Value *CreateFAdd(Value *L, Value *R, const Twine &Name = "",
1382                     MDNode *FPMD = nullptr) {
1383     if (IsFPConstrained)
1384       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd,
1385                                       L, R, nullptr, Name, FPMD);
1386
1387     if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
1388     Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), FPMD, FMF);
1389     return Insert(I, Name);
1390   }
1391
1392   /// Copy fast-math-flags from an instruction rather than using the builder's
1393   /// default FMF.
1394   Value *CreateFAddFMF(Value *L, Value *R, Instruction *FMFSource,
1395                        const Twine &Name = "") {
1396     if (IsFPConstrained)
1397       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd,
1398                                       L, R, FMFSource, Name);
1399
1400     if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
1401     Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), nullptr,
1402                                 FMFSource->getFastMathFlags());
1403     return Insert(I, Name);
1404   }
1405
1406   Value *CreateFSub(Value *L, Value *R, const Twine &Name = "",
1407                     MDNode *FPMD = nullptr) {
1408     if (IsFPConstrained)
1409       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub,
1410                                       L, R, nullptr, Name, FPMD);
1411
1412     if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
1413     Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), FPMD, FMF);
1414     return Insert(I, Name);
1415   }
1416
1417   /// Copy fast-math-flags from an instruction rather than using the builder's
1418   /// default FMF.
1419   Value *CreateFSubFMF(Value *L, Value *R, Instruction *FMFSource,
1420                        const Twine &Name = "") {
1421     if (IsFPConstrained)
1422       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub,
1423                                       L, R, FMFSource, Name);
1424
1425     if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
1426     Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), nullptr,
1427                                 FMFSource->getFastMathFlags());
1428     return Insert(I, Name);
1429   }
1430
1431   Value *CreateFMul(Value *L, Value *R, const Twine &Name = "",
1432                     MDNode *FPMD = nullptr) {
1433     if (IsFPConstrained)
1434       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul,
1435                                       L, R, nullptr, Name, FPMD);
1436
1437     if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
1438     Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), FPMD, FMF);
1439     return Insert(I, Name);
1440   }
1441
1442   /// Copy fast-math-flags from an instruction rather than using the builder's
1443   /// default FMF.
1444   Value *CreateFMulFMF(Value *L, Value *R, Instruction *FMFSource,
1445                        const Twine &Name = "") {
1446     if (IsFPConstrained)
1447       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul,
1448                                       L, R, FMFSource, Name);
1449
1450     if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
1451     Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), nullptr,
1452                                 FMFSource->getFastMathFlags());
1453     return Insert(I, Name);
1454   }
1455
1456   Value *CreateFDiv(Value *L, Value *R, const Twine &Name = "",
1457                     MDNode *FPMD = nullptr) {
1458     if (IsFPConstrained)
1459       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv,
1460                                       L, R, nullptr, Name, FPMD);
1461
1462     if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
1463     Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), FPMD, FMF);
1464     return Insert(I, Name);
1465   }
1466
1467   /// Copy fast-math-flags from an instruction rather than using the builder's
1468   /// default FMF.
1469   Value *CreateFDivFMF(Value *L, Value *R, Instruction *FMFSource,
1470                        const Twine &Name = "") {
1471     if (IsFPConstrained)
1472       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv,
1473                                       L, R, FMFSource, Name);
1474
1475     if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
1476     Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), nullptr,
1477                                 FMFSource->getFastMathFlags());
1478     return Insert(I, Name);
1479   }
1480
1481   Value *CreateFRem(Value *L, Value *R, const Twine &Name = "",
1482                     MDNode *FPMD = nullptr) {
1483     if (IsFPConstrained)
1484       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem,
1485                                       L, R, nullptr, Name, FPMD);
1486
1487     if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
1488     Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), FPMD, FMF);
1489     return Insert(I, Name);
1490   }
1491
1492   /// Copy fast-math-flags from an instruction rather than using the builder's
1493   /// default FMF.
1494   Value *CreateFRemFMF(Value *L, Value *R, Instruction *FMFSource,
1495                        const Twine &Name = "") {
1496     if (IsFPConstrained)
1497       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem,
1498                                       L, R, FMFSource, Name);
1499
1500     if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
1501     Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), nullptr,
1502                                 FMFSource->getFastMathFlags());
1503     return Insert(I, Name);
1504   }
1505
1506   Value *CreateBinOp(Instruction::BinaryOps Opc,
1507                      Value *LHS, Value *RHS, const Twine &Name = "",
1508                      MDNode *FPMathTag = nullptr) {
1509     if (Value *V = foldConstant(Opc, LHS, RHS, Name)) return V;
1510     Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
1511     if (isa<FPMathOperator>(BinOp))
1512       setFPAttrs(BinOp, FPMathTag, FMF);
1513     return Insert(BinOp, Name);
1514   }
1515
1516   CallInst *CreateConstrainedFPBinOp(
1517       Intrinsic::ID ID, Value *L, Value *R, Instruction *FMFSource = nullptr,
1518       const Twine &Name = "", MDNode *FPMathTag = nullptr,
1519       Optional<RoundingMode> Rounding = None,
1520       Optional<fp::ExceptionBehavior> Except = None);
1521
1522   Value *CreateNeg(Value *V, const Twine &Name = "",
1523                    bool HasNUW = false, bool HasNSW = false) {
1524     if (auto *VC = dyn_cast<Constant>(V))
1525       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
1526     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
1527     if (HasNUW) BO->setHasNoUnsignedWrap();
1528     if (HasNSW) BO->setHasNoSignedWrap();
1529     return BO;
1530   }
1531
1532   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
1533     return CreateNeg(V, Name, false, true);
1534   }
1535
1536   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
1537     return CreateNeg(V, Name, true, false);
1538   }
1539
1540   Value *CreateFNeg(Value *V, const Twine &Name = "",
1541                     MDNode *FPMathTag = nullptr) {
1542     if (auto *VC = dyn_cast<Constant>(V))
1543       return Insert(Folder.CreateFNeg(VC), Name);
1544     return Insert(setFPAttrs(UnaryOperator::CreateFNeg(V), FPMathTag, FMF),
1545                   Name);
1546   }
1547
1548   /// Copy fast-math-flags from an instruction rather than using the builder's
1549   /// default FMF.
1550   Value *CreateFNegFMF(Value *V, Instruction *FMFSource,
1551                        const Twine &Name = "") {
1552    if (auto *VC = dyn_cast<Constant>(V))
1553      return Insert(Folder.CreateFNeg(VC), Name);
1554    return Insert(setFPAttrs(UnaryOperator::CreateFNeg(V), nullptr,
1555                             FMFSource->getFastMathFlags()),
1556                  Name);
1557   }
1558
1559   Value *CreateNot(Value *V, const Twine &Name = "") {
1560     if (auto *VC = dyn_cast<Constant>(V))
1561       return Insert(Folder.CreateNot(VC), Name);
1562     return Insert(BinaryOperator::CreateNot(V), Name);
1563   }
1564
1565   Value *CreateUnOp(Instruction::UnaryOps Opc,
1566                     Value *V, const Twine &Name = "",
1567                     MDNode *FPMathTag = nullptr) {
1568     if (auto *VC = dyn_cast<Constant>(V))
1569       return Insert(Folder.CreateUnOp(Opc, VC), Name);
1570     Instruction *UnOp = UnaryOperator::Create(Opc, V);
1571     if (isa<FPMathOperator>(UnOp))
1572       setFPAttrs(UnOp, FPMathTag, FMF);
1573     return Insert(UnOp, Name);
1574   }
1575
1576   /// Create either a UnaryOperator or BinaryOperator depending on \p Opc.
1577   /// Correct number of operands must be passed accordingly.
1578   Value *CreateNAryOp(unsigned Opc, ArrayRef<Value *> Ops,
1579                       const Twine &Name = "", MDNode *FPMathTag = nullptr);
1580
1581   //===--------------------------------------------------------------------===//
1582   // Instruction creation methods: Memory Instructions
1583   //===--------------------------------------------------------------------===//
1584
1585   AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace,
1586                            Value *ArraySize = nullptr, const Twine &Name = "") {
1587     const DataLayout &DL = BB->getModule()->getDataLayout();
1588     Align AllocaAlign = DL.getPrefTypeAlign(Ty);
1589     return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name);
1590   }
1591
1592   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1593                            const Twine &Name = "") {
1594     const DataLayout &DL = BB->getModule()->getDataLayout();
1595     Align AllocaAlign = DL.getPrefTypeAlign(Ty);
1596     unsigned AddrSpace = DL.getAllocaAddrSpace();
1597     return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name);
1598   }
1599
1600   /// Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of
1601   /// converting the string to 'bool' for the isVolatile parameter.
1602   LoadInst *CreateLoad(Type *Ty, Value *Ptr, const char *Name) {
1603     return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), Name);
1604   }
1605
1606   LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1607     return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), Name);
1608   }
1609
1610   LoadInst *CreateLoad(Type *Ty, Value *Ptr, bool isVolatile,
1611                        const Twine &Name = "") {
1612     return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), isVolatile, Name);
1613   }
1614
1615   // Deprecated [opaque pointer types]
1616   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1617     return CreateLoad(Ptr->getType()->getPointerElementType(), Ptr, Name);
1618   }
1619
1620   // Deprecated [opaque pointer types]
1621   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1622     return CreateLoad(Ptr->getType()->getPointerElementType(), Ptr, Name);
1623   }
1624
1625   // Deprecated [opaque pointer types]
1626   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1627     return CreateLoad(Ptr->getType()->getPointerElementType(), Ptr, isVolatile,
1628                       Name);
1629   }
1630
1631   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1632     return CreateAlignedStore(Val, Ptr, MaybeAlign(), isVolatile);
1633   }
1634
1635   LLVM_ATTRIBUTE_DEPRECATED(LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr,
1636                                                         unsigned Align,
1637                                                         const char *Name),
1638                             "Use the version that takes NaybeAlign instead") {
1639     return CreateAlignedLoad(Ty, Ptr, MaybeAlign(Align), Name);
1640   }
1641   LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
1642                               const char *Name) {
1643     return CreateAlignedLoad(Ty, Ptr, Align, /*isVolatile*/false, Name);
1644   }
1645
1646   LLVM_ATTRIBUTE_DEPRECATED(LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr,
1647                                                         unsigned Align,
1648                                                         const Twine &Name = ""),
1649                             "Use the version that takes MaybeAlign instead") {
1650     return CreateAlignedLoad(Ty, Ptr, MaybeAlign(Align), Name);
1651   }
1652   LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
1653                               const Twine &Name = "") {
1654     return CreateAlignedLoad(Ty, Ptr, Align, /*isVolatile*/false, Name);
1655   }
1656
1657   LLVM_ATTRIBUTE_DEPRECATED(LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr,
1658                                                         unsigned Align,
1659                                                         bool isVolatile,
1660                                                         const Twine &Name = ""),
1661                             "Use the version that takes MaybeAlign instead") {
1662     return CreateAlignedLoad(Ty, Ptr, MaybeAlign(Align), isVolatile, Name);
1663   }
1664   LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
1665                               bool isVolatile, const Twine &Name = "") {
1666     if (!Align) {
1667       const DataLayout &DL = BB->getModule()->getDataLayout();
1668       Align = DL.getABITypeAlign(Ty);
1669     }
1670     return Insert(new LoadInst(Ty, Ptr, Twine(), isVolatile, *Align), Name);
1671   }
1672
1673   // Deprecated [opaque pointer types]
1674   LLVM_ATTRIBUTE_DEPRECATED(LoadInst *CreateAlignedLoad(Value *Ptr,
1675                                                         unsigned Align,
1676                                                         const char *Name),
1677                             "Use the version that takes MaybeAlign instead") {
1678     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1679                              MaybeAlign(Align), Name);
1680   }
1681   // Deprecated [opaque pointer types]
1682   LLVM_ATTRIBUTE_DEPRECATED(LoadInst *CreateAlignedLoad(Value *Ptr,
1683                                                         unsigned Align,
1684                                                         const Twine &Name = ""),
1685                             "Use the version that takes MaybeAlign instead") {
1686     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1687                              MaybeAlign(Align), Name);
1688   }
1689   // Deprecated [opaque pointer types]
1690   LLVM_ATTRIBUTE_DEPRECATED(LoadInst *CreateAlignedLoad(Value *Ptr,
1691                                                         unsigned Align,
1692                                                         bool isVolatile,
1693                                                         const Twine &Name = ""),
1694                             "Use the version that takes MaybeAlign instead") {
1695     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1696                              MaybeAlign(Align), isVolatile, Name);
1697   }
1698   // Deprecated [opaque pointer types]
1699   LoadInst *CreateAlignedLoad(Value *Ptr, MaybeAlign Align, const char *Name) {
1700     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1701                              Align, Name);
1702   }
1703   // Deprecated [opaque pointer types]
1704   LoadInst *CreateAlignedLoad(Value *Ptr, MaybeAlign Align,
1705                               const Twine &Name = "") {
1706     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1707                              Align, Name);
1708   }
1709   // Deprecated [opaque pointer types]
1710   LoadInst *CreateAlignedLoad(Value *Ptr, MaybeAlign Align, bool isVolatile,
1711                               const Twine &Name = "") {
1712     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1713                              Align, isVolatile, Name);
1714   }
1715
1716   LLVM_ATTRIBUTE_DEPRECATED(
1717       StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1718                                     bool isVolatile = false),
1719       "Use the version that takes MaybeAlign instead") {
1720     return CreateAlignedStore(Val, Ptr, MaybeAlign(Align), isVolatile);
1721   }
1722   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align,
1723                                 bool isVolatile = false) {
1724     if (!Align) {
1725       const DataLayout &DL = BB->getModule()->getDataLayout();
1726       Align = DL.getABITypeAlign(Val->getType());
1727     }
1728     return Insert(new StoreInst(Val, Ptr, isVolatile, *Align));
1729   }
1730   FenceInst *CreateFence(AtomicOrdering Ordering,
1731                          SyncScope::ID SSID = SyncScope::System,
1732                          const Twine &Name = "") {
1733     return Insert(new FenceInst(Context, Ordering, SSID), Name);
1734   }
1735
1736   AtomicCmpXchgInst *CreateAtomicCmpXchg(
1737       Value *Ptr, Value *Cmp, Value *New, AtomicOrdering SuccessOrdering,
1738       AtomicOrdering FailureOrdering, SyncScope::ID SSID = SyncScope::System) {
1739     const DataLayout &DL = BB->getModule()->getDataLayout();
1740     Align Alignment(DL.getTypeStoreSize(New->getType()));
1741     return Insert(new AtomicCmpXchgInst(
1742         Ptr, Cmp, New, Alignment, SuccessOrdering, FailureOrdering, SSID));
1743   }
1744
1745   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1746                                  AtomicOrdering Ordering,
1747                                  SyncScope::ID SSID = SyncScope::System) {
1748     const DataLayout &DL = BB->getModule()->getDataLayout();
1749     Align Alignment(DL.getTypeStoreSize(Val->getType()));
1750     return Insert(new AtomicRMWInst(Op, Ptr, Val, Alignment, Ordering, SSID));
1751   }
1752
1753   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1754                    const Twine &Name = "") {
1755     return CreateGEP(nullptr, Ptr, IdxList, Name);
1756   }
1757
1758   Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1759                    const Twine &Name = "") {
1760     if (auto *PC = dyn_cast<Constant>(Ptr)) {
1761       // Every index must be constant.
1762       size_t i, e;
1763       for (i = 0, e = IdxList.size(); i != e; ++i)
1764         if (!isa<Constant>(IdxList[i]))
1765           break;
1766       if (i == e)
1767         return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1768     }
1769     return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1770   }
1771
1772   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1773                            const Twine &Name = "") {
1774     return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1775   }
1776
1777   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1778                            const Twine &Name = "") {
1779     if (auto *PC = dyn_cast<Constant>(Ptr)) {
1780       // Every index must be constant.
1781       size_t i, e;
1782       for (i = 0, e = IdxList.size(); i != e; ++i)
1783         if (!isa<Constant>(IdxList[i]))
1784           break;
1785       if (i == e)
1786         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1787                       Name);
1788     }
1789     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1790   }
1791
1792   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1793     return CreateGEP(nullptr, Ptr, Idx, Name);
1794   }
1795
1796   Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1797     if (auto *PC = dyn_cast<Constant>(Ptr))
1798       if (auto *IC = dyn_cast<Constant>(Idx))
1799         return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1800     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1801   }
1802
1803   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1804                            const Twine &Name = "") {
1805     if (auto *PC = dyn_cast<Constant>(Ptr))
1806       if (auto *IC = dyn_cast<Constant>(Idx))
1807         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1808     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1809   }
1810
1811   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1812     return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1813   }
1814
1815   Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1816                             const Twine &Name = "") {
1817     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1818
1819     if (auto *PC = dyn_cast<Constant>(Ptr))
1820       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1821
1822     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1823   }
1824
1825   Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1826                                     const Twine &Name = "") {
1827     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1828
1829     if (auto *PC = dyn_cast<Constant>(Ptr))
1830       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1831
1832     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1833   }
1834
1835   Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1836                             const Twine &Name = "") {
1837     Value *Idxs[] = {
1838       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1839       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1840     };
1841
1842     if (auto *PC = dyn_cast<Constant>(Ptr))
1843       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1844
1845     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1846   }
1847
1848   Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1849                                     unsigned Idx1, const Twine &Name = "") {
1850     Value *Idxs[] = {
1851       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1852       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1853     };
1854
1855     if (auto *PC = dyn_cast<Constant>(Ptr))
1856       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1857
1858     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1859   }
1860
1861   Value *CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0,
1862                             const Twine &Name = "") {
1863     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1864
1865     if (auto *PC = dyn_cast<Constant>(Ptr))
1866       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1867
1868     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1869   }
1870
1871   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1872     return CreateConstGEP1_64(nullptr, Ptr, Idx0, Name);
1873   }
1874
1875   Value *CreateConstInBoundsGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0,
1876                                     const Twine &Name = "") {
1877     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1878
1879     if (auto *PC = dyn_cast<Constant>(Ptr))
1880       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1881
1882     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1883   }
1884
1885   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1886                                     const Twine &Name = "") {
1887     return CreateConstInBoundsGEP1_64(nullptr, Ptr, Idx0, Name);
1888   }
1889
1890   Value *CreateConstGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1891                             const Twine &Name = "") {
1892     Value *Idxs[] = {
1893       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1894       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1895     };
1896
1897     if (auto *PC = dyn_cast<Constant>(Ptr))
1898       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1899
1900     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1901   }
1902
1903   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1904                             const Twine &Name = "") {
1905     return CreateConstGEP2_64(nullptr, Ptr, Idx0, Idx1, Name);
1906   }
1907
1908   Value *CreateConstInBoundsGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0,
1909                                     uint64_t Idx1, const Twine &Name = "") {
1910     Value *Idxs[] = {
1911       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1912       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1913     };
1914
1915     if (auto *PC = dyn_cast<Constant>(Ptr))
1916       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1917
1918     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1919   }
1920
1921   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1922                                     const Twine &Name = "") {
1923     return CreateConstInBoundsGEP2_64(nullptr, Ptr, Idx0, Idx1, Name);
1924   }
1925
1926   Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1927                          const Twine &Name = "") {
1928     return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1929   }
1930
1931   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
1932     return CreateConstInBoundsGEP2_32(nullptr, Ptr, 0, Idx, Name);
1933   }
1934
1935   /// Same as CreateGlobalString, but return a pointer with "i8*" type
1936   /// instead of a pointer to array of i8.
1937   Constant *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1938                                   unsigned AddressSpace = 0) {
1939     GlobalVariable *GV = CreateGlobalString(Str, Name, AddressSpace);
1940     Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1941     Constant *Indices[] = {Zero, Zero};
1942     return ConstantExpr::getInBoundsGetElementPtr(GV->getValueType(), GV,
1943                                                   Indices);
1944   }
1945
1946   //===--------------------------------------------------------------------===//
1947   // Instruction creation methods: Cast/Conversion Operators
1948   //===--------------------------------------------------------------------===//
1949
1950   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1951     return CreateCast(Instruction::Trunc, V, DestTy, Name);
1952   }
1953
1954   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1955     return CreateCast(Instruction::ZExt, V, DestTy, Name);
1956   }
1957
1958   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1959     return CreateCast(Instruction::SExt, V, DestTy, Name);
1960   }
1961
1962   /// Create a ZExt or Trunc from the integer value V to DestTy. Return
1963   /// the value untouched if the type of V is already DestTy.
1964   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1965                            const Twine &Name = "") {
1966     assert(V->getType()->isIntOrIntVectorTy() &&
1967            DestTy->isIntOrIntVectorTy() &&
1968            "Can only zero extend/truncate integers!");
1969     Type *VTy = V->getType();
1970     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1971       return CreateZExt(V, DestTy, Name);
1972     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1973       return CreateTrunc(V, DestTy, Name);
1974     return V;
1975   }
1976
1977   /// Create a SExt or Trunc from the integer value V to DestTy. Return
1978   /// the value untouched if the type of V is already DestTy.
1979   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1980                            const Twine &Name = "") {
1981     assert(V->getType()->isIntOrIntVectorTy() &&
1982            DestTy->isIntOrIntVectorTy() &&
1983            "Can only sign extend/truncate integers!");
1984     Type *VTy = V->getType();
1985     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1986       return CreateSExt(V, DestTy, Name);
1987     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1988       return CreateTrunc(V, DestTy, Name);
1989     return V;
1990   }
1991
1992   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = "") {
1993     if (IsFPConstrained)
1994       return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptoui,
1995                                      V, DestTy, nullptr, Name);
1996     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1997   }
1998
1999   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = "") {
2000     if (IsFPConstrained)
2001       return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptosi,
2002                                      V, DestTy, nullptr, Name);
2003     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
2004   }
2005
2006   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
2007     if (IsFPConstrained)
2008       return CreateConstrainedFPCast(Intrinsic::experimental_constrained_uitofp,
2009                                      V, DestTy, nullptr, Name);
2010     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
2011   }
2012
2013   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
2014     if (IsFPConstrained)
2015       return CreateConstrainedFPCast(Intrinsic::experimental_constrained_sitofp,
2016                                      V, DestTy, nullptr, Name);
2017     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
2018   }
2019
2020   Value *CreateFPTrunc(Value *V, Type *DestTy,
2021                        const Twine &Name = "") {
2022     if (IsFPConstrained)
2023       return CreateConstrainedFPCast(
2024           Intrinsic::experimental_constrained_fptrunc, V, DestTy, nullptr,
2025           Name);
2026     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
2027   }
2028
2029   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
2030     if (IsFPConstrained)
2031       return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fpext,
2032                                      V, DestTy, nullptr, Name);
2033     return CreateCast(Instruction::FPExt, V, DestTy, Name);
2034   }
2035
2036   Value *CreatePtrToInt(Value *V, Type *DestTy,
2037                         const Twine &Name = "") {
2038     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
2039   }
2040
2041   Value *CreateIntToPtr(Value *V, Type *DestTy,
2042                         const Twine &Name = "") {
2043     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
2044   }
2045
2046   Value *CreateBitCast(Value *V, Type *DestTy,
2047                        const Twine &Name = "") {
2048     return CreateCast(Instruction::BitCast, V, DestTy, Name);
2049   }
2050
2051   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
2052                              const Twine &Name = "") {
2053     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
2054   }
2055
2056   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
2057                              const Twine &Name = "") {
2058     if (V->getType() == DestTy)
2059       return V;
2060     if (auto *VC = dyn_cast<Constant>(V))
2061       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
2062     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
2063   }
2064
2065   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
2066                              const Twine &Name = "") {
2067     if (V->getType() == DestTy)
2068       return V;
2069     if (auto *VC = dyn_cast<Constant>(V))
2070       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
2071     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
2072   }
2073
2074   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
2075                               const Twine &Name = "") {
2076     if (V->getType() == DestTy)
2077       return V;
2078     if (auto *VC = dyn_cast<Constant>(V))
2079       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
2080     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
2081   }
2082
2083   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
2084                     const Twine &Name = "") {
2085     if (V->getType() == DestTy)
2086       return V;
2087     if (auto *VC = dyn_cast<Constant>(V))
2088       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
2089     return Insert(CastInst::Create(Op, V, DestTy), Name);
2090   }
2091
2092   Value *CreatePointerCast(Value *V, Type *DestTy,
2093                            const Twine &Name = "") {
2094     if (V->getType() == DestTy)
2095       return V;
2096     if (auto *VC = dyn_cast<Constant>(V))
2097       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
2098     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
2099   }
2100
2101   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
2102                                              const Twine &Name = "") {
2103     if (V->getType() == DestTy)
2104       return V;
2105
2106     if (auto *VC = dyn_cast<Constant>(V)) {
2107       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
2108                     Name);
2109     }
2110
2111     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
2112                   Name);
2113   }
2114
2115   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
2116                        const Twine &Name = "") {
2117     if (V->getType() == DestTy)
2118       return V;
2119     if (auto *VC = dyn_cast<Constant>(V))
2120       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
2121     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
2122   }
2123
2124   Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
2125                                 const Twine &Name = "") {
2126     if (V->getType() == DestTy)
2127       return V;
2128     if (V->getType()->isPtrOrPtrVectorTy() && DestTy->isIntOrIntVectorTy())
2129       return CreatePtrToInt(V, DestTy, Name);
2130     if (V->getType()->isIntOrIntVectorTy() && DestTy->isPtrOrPtrVectorTy())
2131       return CreateIntToPtr(V, DestTy, Name);
2132
2133     return CreateBitCast(V, DestTy, Name);
2134   }
2135
2136   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
2137     if (V->getType() == DestTy)
2138       return V;
2139     if (auto *VC = dyn_cast<Constant>(V))
2140       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
2141     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
2142   }
2143
2144   CallInst *CreateConstrainedFPCast(
2145       Intrinsic::ID ID, Value *V, Type *DestTy,
2146       Instruction *FMFSource = nullptr, const Twine &Name = "",
2147       MDNode *FPMathTag = nullptr,
2148       Optional<RoundingMode> Rounding = None,
2149       Optional<fp::ExceptionBehavior> Except = None);
2150
2151   // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
2152   // compile time error, instead of converting the string to bool for the
2153   // isSigned parameter.
2154   Value *CreateIntCast(Value *, Type *, const char *) = delete;
2155
2156   //===--------------------------------------------------------------------===//
2157   // Instruction creation methods: Compare Instructions
2158   //===--------------------------------------------------------------------===//
2159
2160   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
2161     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
2162   }
2163
2164   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
2165     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
2166   }
2167
2168   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
2169     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
2170   }
2171
2172   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
2173     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
2174   }
2175
2176   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
2177     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
2178   }
2179
2180   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
2181     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
2182   }
2183
2184   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
2185     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
2186   }
2187
2188   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
2189     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
2190   }
2191
2192   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
2193     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
2194   }
2195
2196   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
2197     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
2198   }
2199
2200   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
2201                        MDNode *FPMathTag = nullptr) {
2202     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
2203   }
2204
2205   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
2206                        MDNode *FPMathTag = nullptr) {
2207     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
2208   }
2209
2210   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
2211                        MDNode *FPMathTag = nullptr) {
2212     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
2213   }
2214
2215   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
2216                        MDNode *FPMathTag = nullptr) {
2217     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
2218   }
2219
2220   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
2221                        MDNode *FPMathTag = nullptr) {
2222     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
2223   }
2224
2225   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
2226                        MDNode *FPMathTag = nullptr) {
2227     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
2228   }
2229
2230   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
2231                        MDNode *FPMathTag = nullptr) {
2232     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
2233   }
2234
2235   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
2236                        MDNode *FPMathTag = nullptr) {
2237     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
2238   }
2239
2240   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
2241                        MDNode *FPMathTag = nullptr) {
2242     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
2243   }
2244
2245   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
2246                        MDNode *FPMathTag = nullptr) {
2247     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
2248   }
2249
2250   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
2251                        MDNode *FPMathTag = nullptr) {
2252     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
2253   }
2254
2255   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
2256                        MDNode *FPMathTag = nullptr) {
2257     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
2258   }
2259
2260   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
2261                        MDNode *FPMathTag = nullptr) {
2262     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
2263   }
2264
2265   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
2266                        MDNode *FPMathTag = nullptr) {
2267     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
2268   }
2269
2270   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
2271                     const Twine &Name = "") {
2272     if (auto *LC = dyn_cast<Constant>(LHS))
2273       if (auto *RC = dyn_cast<Constant>(RHS))
2274         return Insert(Folder.CreateICmp(P, LC, RC), Name);
2275     return Insert(new ICmpInst(P, LHS, RHS), Name);
2276   }
2277
2278   // Create a quiet floating-point comparison (i.e. one that raises an FP
2279   // exception only in the case where an input is a signaling NaN).
2280   // Note that this differs from CreateFCmpS only if IsFPConstrained is true.
2281   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
2282                     const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2283     return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, false);
2284   }
2285
2286   Value *CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
2287                    const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2288     return CmpInst::isFPPredicate(Pred)
2289                ? CreateFCmp(Pred, LHS, RHS, Name, FPMathTag)
2290                : CreateICmp(Pred, LHS, RHS, Name);
2291   }
2292
2293   // Create a signaling floating-point comparison (i.e. one that raises an FP
2294   // exception whenever an input is any NaN, signaling or quiet).
2295   // Note that this differs from CreateFCmp only if IsFPConstrained is true.
2296   Value *CreateFCmpS(CmpInst::Predicate P, Value *LHS, Value *RHS,
2297                      const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2298     return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, true);
2299   }
2300
2301 private:
2302   // Helper routine to create either a signaling or a quiet FP comparison.
2303   Value *CreateFCmpHelper(CmpInst::Predicate P, Value *LHS, Value *RHS,
2304                           const Twine &Name, MDNode *FPMathTag,
2305                           bool IsSignaling);
2306
2307 public:
2308   CallInst *CreateConstrainedFPCmp(
2309       Intrinsic::ID ID, CmpInst::Predicate P, Value *L, Value *R,
2310       const Twine &Name = "", Optional<fp::ExceptionBehavior> Except = None);
2311
2312   //===--------------------------------------------------------------------===//
2313   // Instruction creation methods: Other Instructions
2314   //===--------------------------------------------------------------------===//
2315
2316   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
2317                      const Twine &Name = "") {
2318     PHINode *Phi = PHINode::Create(Ty, NumReservedValues);
2319     if (isa<FPMathOperator>(Phi))
2320       setFPAttrs(Phi, nullptr /* MDNode* */, FMF);
2321     return Insert(Phi, Name);
2322   }
2323
2324   CallInst *CreateCall(FunctionType *FTy, Value *Callee,
2325                        ArrayRef<Value *> Args = None, const Twine &Name = "",
2326                        MDNode *FPMathTag = nullptr) {
2327     CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles);
2328     if (IsFPConstrained)
2329       setConstrainedFPCallAttr(CI);
2330     if (isa<FPMathOperator>(CI))
2331       setFPAttrs(CI, FPMathTag, FMF);
2332     return Insert(CI, Name);
2333   }
2334
2335   CallInst *CreateCall(FunctionType *FTy, Value *Callee, ArrayRef<Value *> Args,
2336                        ArrayRef<OperandBundleDef> OpBundles,
2337                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2338     CallInst *CI = CallInst::Create(FTy, Callee, Args, OpBundles);
2339     if (IsFPConstrained)
2340       setConstrainedFPCallAttr(CI);
2341     if (isa<FPMathOperator>(CI))
2342       setFPAttrs(CI, FPMathTag, FMF);
2343     return Insert(CI, Name);
2344   }
2345
2346   CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args = None,
2347                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2348     return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args, Name,
2349                       FPMathTag);
2350   }
2351
2352   CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args,
2353                        ArrayRef<OperandBundleDef> OpBundles,
2354                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2355     return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args,
2356                       OpBundles, Name, FPMathTag);
2357   }
2358
2359   CallInst *CreateConstrainedFPCall(
2360       Function *Callee, ArrayRef<Value *> Args, const Twine &Name = "",
2361       Optional<RoundingMode> Rounding = None,
2362       Optional<fp::ExceptionBehavior> Except = None);
2363
2364   Value *CreateSelect(Value *C, Value *True, Value *False,
2365                       const Twine &Name = "", Instruction *MDFrom = nullptr);
2366
2367   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
2368     return Insert(new VAArgInst(List, Ty), Name);
2369   }
2370
2371   Value *CreateExtractElement(Value *Vec, Value *Idx,
2372                               const Twine &Name = "") {
2373     if (auto *VC = dyn_cast<Constant>(Vec))
2374       if (auto *IC = dyn_cast<Constant>(Idx))
2375         return Insert(Folder.CreateExtractElement(VC, IC), Name);
2376     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
2377   }
2378
2379   Value *CreateExtractElement(Value *Vec, uint64_t Idx,
2380                               const Twine &Name = "") {
2381     return CreateExtractElement(Vec, getInt64(Idx), Name);
2382   }
2383
2384   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
2385                              const Twine &Name = "") {
2386     if (auto *VC = dyn_cast<Constant>(Vec))
2387       if (auto *NC = dyn_cast<Constant>(NewElt))
2388         if (auto *IC = dyn_cast<Constant>(Idx))
2389           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
2390     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
2391   }
2392
2393   Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
2394                              const Twine &Name = "") {
2395     return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
2396   }
2397
2398   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
2399                              const Twine &Name = "") {
2400     SmallVector<int, 16> IntMask;
2401     ShuffleVectorInst::getShuffleMask(cast<Constant>(Mask), IntMask);
2402     return CreateShuffleVector(V1, V2, IntMask, Name);
2403   }
2404
2405   LLVM_ATTRIBUTE_DEPRECATED(Value *CreateShuffleVector(Value *V1, Value *V2,
2406                                                        ArrayRef<uint32_t> Mask,
2407                                                        const Twine &Name = ""),
2408                             "Pass indices as 'int' instead") {
2409     SmallVector<int, 16> IntMask;
2410     IntMask.assign(Mask.begin(), Mask.end());
2411     return CreateShuffleVector(V1, V2, IntMask, Name);
2412   }
2413
2414   /// See class ShuffleVectorInst for a description of the mask representation.
2415   Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> Mask,
2416                              const Twine &Name = "") {
2417     if (auto *V1C = dyn_cast<Constant>(V1))
2418       if (auto *V2C = dyn_cast<Constant>(V2))
2419         return Insert(Folder.CreateShuffleVector(V1C, V2C, Mask), Name);
2420     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
2421   }
2422
2423   Value *CreateExtractValue(Value *Agg,
2424                             ArrayRef<unsigned> Idxs,
2425                             const Twine &Name = "") {
2426     if (auto *AggC = dyn_cast<Constant>(Agg))
2427       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
2428     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
2429   }
2430
2431   Value *CreateInsertValue(Value *Agg, Value *Val,
2432                            ArrayRef<unsigned> Idxs,
2433                            const Twine &Name = "") {
2434     if (auto *AggC = dyn_cast<Constant>(Agg))
2435       if (auto *ValC = dyn_cast<Constant>(Val))
2436         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
2437     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
2438   }
2439
2440   LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
2441                                    const Twine &Name = "") {
2442     return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
2443   }
2444
2445   Value *CreateFreeze(Value *V, const Twine &Name = "") {
2446     return Insert(new FreezeInst(V), Name);
2447   }
2448
2449   //===--------------------------------------------------------------------===//
2450   // Utility creation methods
2451   //===--------------------------------------------------------------------===//
2452
2453   /// Return an i1 value testing if \p Arg is null.
2454   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
2455     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
2456                         Name);
2457   }
2458
2459   /// Return an i1 value testing if \p Arg is not null.
2460   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
2461     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
2462                         Name);
2463   }
2464
2465   /// Return the i64 difference between two pointer values, dividing out
2466   /// the size of the pointed-to objects.
2467   ///
2468   /// This is intended to implement C-style pointer subtraction. As such, the
2469   /// pointers must be appropriately aligned for their element types and
2470   /// pointing into the same object.
2471   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "");
2472
2473   /// Create a launder.invariant.group intrinsic call. If Ptr type is
2474   /// different from pointer to i8, it's casted to pointer to i8 in the same
2475   /// address space before call and casted back to Ptr type after call.
2476   Value *CreateLaunderInvariantGroup(Value *Ptr);
2477
2478   /// \brief Create a strip.invariant.group intrinsic call. If Ptr type is
2479   /// different from pointer to i8, it's casted to pointer to i8 in the same
2480   /// address space before call and casted back to Ptr type after call.
2481   Value *CreateStripInvariantGroup(Value *Ptr);
2482
2483   /// Return a vector value that contains \arg V broadcasted to \p
2484   /// NumElts elements.
2485   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "");
2486
2487   /// Return a value that has been extracted from a larger integer type.
2488   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
2489                               IntegerType *ExtractedTy, uint64_t Offset,
2490                               const Twine &Name);
2491
2492   Value *CreatePreserveArrayAccessIndex(Type *ElTy, Value *Base,
2493                                         unsigned Dimension, unsigned LastIndex,
2494                                         MDNode *DbgInfo);
2495
2496   Value *CreatePreserveUnionAccessIndex(Value *Base, unsigned FieldIndex,
2497                                         MDNode *DbgInfo);
2498
2499   Value *CreatePreserveStructAccessIndex(Type *ElTy, Value *Base,
2500                                          unsigned Index, unsigned FieldIndex,
2501                                          MDNode *DbgInfo);
2502
2503 private:
2504   /// Helper function that creates an assume intrinsic call that
2505   /// represents an alignment assumption on the provided Ptr, Mask, Type
2506   /// and Offset. It may be sometimes useful to do some other logic
2507   /// based on this alignment check, thus it can be stored into 'TheCheck'.
2508   CallInst *CreateAlignmentAssumptionHelper(const DataLayout &DL,
2509                                             Value *PtrValue, Value *Mask,
2510                                             Type *IntPtrTy, Value *OffsetValue,
2511                                             Value **TheCheck);
2512
2513 public:
2514   /// Create an assume intrinsic call that represents an alignment
2515   /// assumption on the provided pointer.
2516   ///
2517   /// An optional offset can be provided, and if it is provided, the offset
2518   /// must be subtracted from the provided pointer to get the pointer with the
2519   /// specified alignment.
2520   ///
2521   /// It may be sometimes useful to do some other logic
2522   /// based on this alignment check, thus it can be stored into 'TheCheck'.
2523   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
2524                                       unsigned Alignment,
2525                                       Value *OffsetValue = nullptr,
2526                                       Value **TheCheck = nullptr);
2527
2528   /// Create an assume intrinsic call that represents an alignment
2529   /// assumption on the provided pointer.
2530   ///
2531   /// An optional offset can be provided, and if it is provided, the offset
2532   /// must be subtracted from the provided pointer to get the pointer with the
2533   /// specified alignment.
2534   ///
2535   /// It may be sometimes useful to do some other logic
2536   /// based on this alignment check, thus it can be stored into 'TheCheck'.
2537   ///
2538   /// This overload handles the condition where the Alignment is dependent
2539   /// on an existing value rather than a static value.
2540   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
2541                                       Value *Alignment,
2542                                       Value *OffsetValue = nullptr,
2543                                       Value **TheCheck = nullptr);
2544 };
2545
2546 /// This provides a uniform API for creating instructions and inserting
2547 /// them into a basic block: either at the end of a BasicBlock, or at a specific
2548 /// iterator location in a block.
2549 ///
2550 /// Note that the builder does not expose the full generality of LLVM
2551 /// instructions.  For access to extra instruction properties, use the mutators
2552 /// (e.g. setVolatile) on the instructions after they have been
2553 /// created. Convenience state exists to specify fast-math flags and fp-math
2554 /// tags.
2555 ///
2556 /// The first template argument specifies a class to use for creating constants.
2557 /// This defaults to creating minimally folded constants.  The second template
2558 /// argument allows clients to specify custom insertion hooks that are called on
2559 /// every newly created insertion.
2560 template <typename FolderTy = ConstantFolder,
2561           typename InserterTy = IRBuilderDefaultInserter>
2562 class IRBuilder : public IRBuilderBase {
2563 private:
2564   FolderTy Folder;
2565   InserterTy Inserter;
2566
2567 public:
2568   IRBuilder(LLVMContext &C, FolderTy Folder, InserterTy Inserter = InserterTy(),
2569             MDNode *FPMathTag = nullptr,
2570             ArrayRef<OperandBundleDef> OpBundles = None)
2571       : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles),
2572         Folder(Folder), Inserter(Inserter) {}
2573
2574   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr,
2575                      ArrayRef<OperandBundleDef> OpBundles = None)
2576       : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles) {}
2577
2578   explicit IRBuilder(BasicBlock *TheBB, FolderTy Folder,
2579                      MDNode *FPMathTag = nullptr,
2580                      ArrayRef<OperandBundleDef> OpBundles = None)
2581       : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
2582                       FPMathTag, OpBundles), Folder(Folder) {
2583     SetInsertPoint(TheBB);
2584   }
2585
2586   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr,
2587                      ArrayRef<OperandBundleDef> OpBundles = None)
2588       : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
2589                       FPMathTag, OpBundles) {
2590     SetInsertPoint(TheBB);
2591   }
2592
2593   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr,
2594                      ArrayRef<OperandBundleDef> OpBundles = None)
2595       : IRBuilderBase(IP->getContext(), this->Folder, this->Inserter,
2596                       FPMathTag, OpBundles) {
2597     SetInsertPoint(IP);
2598   }
2599
2600   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, FolderTy Folder,
2601             MDNode *FPMathTag = nullptr,
2602             ArrayRef<OperandBundleDef> OpBundles = None)
2603       : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
2604                       FPMathTag, OpBundles), Folder(Folder) {
2605     SetInsertPoint(TheBB, IP);
2606   }
2607
2608   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
2609             MDNode *FPMathTag = nullptr,
2610             ArrayRef<OperandBundleDef> OpBundles = None)
2611       : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter,
2612                       FPMathTag, OpBundles) {
2613     SetInsertPoint(TheBB, IP);
2614   }
2615
2616   /// Avoid copying the full IRBuilder. Prefer using InsertPointGuard
2617   /// or FastMathFlagGuard instead.
2618   IRBuilder(const IRBuilder &) = delete;
2619
2620   InserterTy &getInserter() { return Inserter; }
2621 };
2622
2623 // Create wrappers for C Binding types (see CBindingWrapping.h).
2624 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
2625
2626 } // end namespace llvm
2627
2628 #endif // LLVM_IR_IRBUILDER_H