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