LLVM  mainline
IRBuilder.h
Go to the documentation of this file.
00001 //===---- llvm/IRBuilder.h - Builder for LLVM Instructions ------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the IRBuilder class, which is used as a convenient way
00011 // to create LLVM instructions with a consistent and simplified interface.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_IR_IRBUILDER_H
00016 #define LLVM_IR_IRBUILDER_H
00017 
00018 #include "llvm/ADT/ArrayRef.h"
00019 #include "llvm/ADT/StringRef.h"
00020 #include "llvm/ADT/Twine.h"
00021 #include "llvm/IR/BasicBlock.h"
00022 #include "llvm/IR/ConstantFolder.h"
00023 #include "llvm/IR/DataLayout.h"
00024 #include "llvm/IR/Function.h"
00025 #include "llvm/IR/GlobalVariable.h"
00026 #include "llvm/IR/Instructions.h"
00027 #include "llvm/IR/Intrinsics.h"
00028 #include "llvm/IR/LLVMContext.h"
00029 #include "llvm/IR/Operator.h"
00030 #include "llvm/IR/ValueHandle.h"
00031 #include "llvm/Support/CBindingWrapping.h"
00032 
00033 namespace llvm {
00034 class MDNode;
00035 
00036 /// \brief This provides the default implementation of the IRBuilder
00037 /// 'InsertHelper' method that is called whenever an instruction is created by
00038 /// IRBuilder and needs to be inserted.
00039 ///
00040 /// By default, this inserts the instruction at the insertion point.
00041 template <bool preserveNames = true>
00042 class IRBuilderDefaultInserter {
00043 protected:
00044   void InsertHelper(Instruction *I, const Twine &Name,
00045                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
00046     if (BB) BB->getInstList().insert(InsertPt, I);
00047     if (preserveNames)
00048       I->setName(Name);
00049   }
00050 };
00051 
00052 /// \brief Common base class shared among various IRBuilders.
00053 class IRBuilderBase {
00054   DebugLoc CurDbgLocation;
00055 
00056 protected:
00057   BasicBlock *BB;
00058   BasicBlock::iterator InsertPt;
00059   LLVMContext &Context;
00060 
00061   MDNode *DefaultFPMathTag;
00062   FastMathFlags FMF;
00063 
00064   ArrayRef<OperandBundleDef> DefaultOperandBundles;
00065 
00066 public:
00067   IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr,
00068                 ArrayRef<OperandBundleDef> OpBundles = None)
00069       : Context(context), DefaultFPMathTag(FPMathTag), FMF(),
00070         DefaultOperandBundles(OpBundles) {
00071     ClearInsertionPoint();
00072   }
00073 
00074   //===--------------------------------------------------------------------===//
00075   // Builder configuration methods
00076   //===--------------------------------------------------------------------===//
00077 
00078   /// \brief Clear the insertion point: created instructions will not be
00079   /// inserted into a block.
00080   void ClearInsertionPoint() {
00081     BB = nullptr;
00082     InsertPt.reset(nullptr);
00083   }
00084 
00085   BasicBlock *GetInsertBlock() const { return BB; }
00086   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
00087   LLVMContext &getContext() const { return Context; }
00088 
00089   /// \brief This specifies that created instructions should be appended to the
00090   /// end of the specified block.
00091   void SetInsertPoint(BasicBlock *TheBB) {
00092     BB = TheBB;
00093     InsertPt = BB->end();
00094   }
00095 
00096   /// \brief This specifies that created instructions should be inserted before
00097   /// the specified instruction.
00098   void SetInsertPoint(Instruction *I) {
00099     BB = I->getParent();
00100     InsertPt = I->getIterator();
00101     assert(InsertPt != BB->end() && "Can't read debug loc from end()");
00102     SetCurrentDebugLocation(I->getDebugLoc());
00103   }
00104 
00105   /// \brief This specifies that created instructions should be inserted at the
00106   /// specified point.
00107   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
00108     BB = TheBB;
00109     InsertPt = IP;
00110     if (IP != TheBB->end())
00111       SetCurrentDebugLocation(IP->getDebugLoc());
00112   }
00113 
00114   /// \brief Set location information used by debugging information.
00115   void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
00116 
00117   /// \brief Get location information used by debugging information.
00118   const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
00119 
00120   /// \brief If this builder has a current debug location, set it on the
00121   /// specified instruction.
00122   void SetInstDebugLocation(Instruction *I) const {
00123     if (CurDbgLocation)
00124       I->setDebugLoc(CurDbgLocation);
00125   }
00126 
00127   /// \brief Get the return type of the current function that we're emitting
00128   /// into.
00129   Type *getCurrentFunctionReturnType() const;
00130 
00131   /// InsertPoint - A saved insertion point.
00132   class InsertPoint {
00133     BasicBlock *Block;
00134     BasicBlock::iterator Point;
00135 
00136   public:
00137     /// \brief Creates a new insertion point which doesn't point to anything.
00138     InsertPoint() : Block(nullptr) {}
00139 
00140     /// \brief Creates a new insertion point at the given location.
00141     InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
00142       : Block(InsertBlock), Point(InsertPoint) {}
00143 
00144     /// \brief Returns true if this insert point is set.
00145     bool isSet() const { return (Block != nullptr); }
00146 
00147     llvm::BasicBlock *getBlock() const { return Block; }
00148     llvm::BasicBlock::iterator getPoint() const { return Point; }
00149   };
00150 
00151   /// \brief Returns the current insert point.
00152   InsertPoint saveIP() const {
00153     return InsertPoint(GetInsertBlock(), GetInsertPoint());
00154   }
00155 
00156   /// \brief Returns the current insert point, clearing it in the process.
00157   InsertPoint saveAndClearIP() {
00158     InsertPoint IP(GetInsertBlock(), GetInsertPoint());
00159     ClearInsertionPoint();
00160     return IP;
00161   }
00162 
00163   /// \brief Sets the current insert point to a previously-saved location.
00164   void restoreIP(InsertPoint IP) {
00165     if (IP.isSet())
00166       SetInsertPoint(IP.getBlock(), IP.getPoint());
00167     else
00168       ClearInsertionPoint();
00169   }
00170 
00171   /// \brief Get the floating point math metadata being used.
00172   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
00173 
00174   /// \brief Get the flags to be applied to created floating point ops
00175   FastMathFlags getFastMathFlags() const { return FMF; }
00176 
00177   /// \brief Clear the fast-math flags.
00178   void clearFastMathFlags() { FMF.clear(); }
00179 
00180   /// \brief Set the floating point math metadata to be used.
00181   void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
00182 
00183   /// \brief Set the fast-math flags to be used with generated fp-math operators
00184   void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
00185 
00186   //===--------------------------------------------------------------------===//
00187   // RAII helpers.
00188   //===--------------------------------------------------------------------===//
00189 
00190   // \brief RAII object that stores the current insertion point and restores it
00191   // when the object is destroyed. This includes the debug location.
00192   class InsertPointGuard {
00193     IRBuilderBase &Builder;
00194     AssertingVH<BasicBlock> Block;
00195     BasicBlock::iterator Point;
00196     DebugLoc DbgLoc;
00197 
00198     InsertPointGuard(const InsertPointGuard &) = delete;
00199     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
00200 
00201   public:
00202     InsertPointGuard(IRBuilderBase &B)
00203         : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
00204           DbgLoc(B.getCurrentDebugLocation()) {}
00205 
00206     ~InsertPointGuard() {
00207       Builder.restoreIP(InsertPoint(Block, Point));
00208       Builder.SetCurrentDebugLocation(DbgLoc);
00209     }
00210   };
00211 
00212   // \brief RAII object that stores the current fast math settings and restores
00213   // them when the object is destroyed.
00214   class FastMathFlagGuard {
00215     IRBuilderBase &Builder;
00216     FastMathFlags FMF;
00217     MDNode *FPMathTag;
00218 
00219     FastMathFlagGuard(const FastMathFlagGuard &) = delete;
00220     FastMathFlagGuard &operator=(
00221         const FastMathFlagGuard &) = delete;
00222 
00223   public:
00224     FastMathFlagGuard(IRBuilderBase &B)
00225         : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
00226 
00227     ~FastMathFlagGuard() {
00228       Builder.FMF = FMF;
00229       Builder.DefaultFPMathTag = FPMathTag;
00230     }
00231   };
00232 
00233   //===--------------------------------------------------------------------===//
00234   // Miscellaneous creation methods.
00235   //===--------------------------------------------------------------------===//
00236 
00237   /// \brief Make a new global variable with initializer type i8*
00238   ///
00239   /// Make a new global variable with an initializer that has array of i8 type
00240   /// filled in with the null terminated string value specified.  The new global
00241   /// variable will be marked mergable with any others of the same contents.  If
00242   /// Name is specified, it is the name of the global variable created.
00243   GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
00244                                      unsigned AddressSpace = 0);
00245 
00246   /// \brief Get a constant value representing either true or false.
00247   ConstantInt *getInt1(bool V) {
00248     return ConstantInt::get(getInt1Ty(), V);
00249   }
00250 
00251   /// \brief Get the constant value for i1 true.
00252   ConstantInt *getTrue() {
00253     return ConstantInt::getTrue(Context);
00254   }
00255 
00256   /// \brief Get the constant value for i1 false.
00257   ConstantInt *getFalse() {
00258     return ConstantInt::getFalse(Context);
00259   }
00260 
00261   /// \brief Get a constant 8-bit value.
00262   ConstantInt *getInt8(uint8_t C) {
00263     return ConstantInt::get(getInt8Ty(), C);
00264   }
00265 
00266   /// \brief Get a constant 16-bit value.
00267   ConstantInt *getInt16(uint16_t C) {
00268     return ConstantInt::get(getInt16Ty(), C);
00269   }
00270 
00271   /// \brief Get a constant 32-bit value.
00272   ConstantInt *getInt32(uint32_t C) {
00273     return ConstantInt::get(getInt32Ty(), C);
00274   }
00275 
00276   /// \brief Get a constant 64-bit value.
00277   ConstantInt *getInt64(uint64_t C) {
00278     return ConstantInt::get(getInt64Ty(), C);
00279   }
00280 
00281   /// \brief Get a constant N-bit value, zero extended or truncated from
00282   /// a 64-bit value.
00283   ConstantInt *getIntN(unsigned N, uint64_t C) {
00284     return ConstantInt::get(getIntNTy(N), C);
00285   }
00286 
00287   /// \brief Get a constant integer value.
00288   ConstantInt *getInt(const APInt &AI) {
00289     return ConstantInt::get(Context, AI);
00290   }
00291 
00292   //===--------------------------------------------------------------------===//
00293   // Type creation methods
00294   //===--------------------------------------------------------------------===//
00295 
00296   /// \brief Fetch the type representing a single bit
00297   IntegerType *getInt1Ty() {
00298     return Type::getInt1Ty(Context);
00299   }
00300 
00301   /// \brief Fetch the type representing an 8-bit integer.
00302   IntegerType *getInt8Ty() {
00303     return Type::getInt8Ty(Context);
00304   }
00305 
00306   /// \brief Fetch the type representing a 16-bit integer.
00307   IntegerType *getInt16Ty() {
00308     return Type::getInt16Ty(Context);
00309   }
00310 
00311   /// \brief Fetch the type representing a 32-bit integer.
00312   IntegerType *getInt32Ty() {
00313     return Type::getInt32Ty(Context);
00314   }
00315 
00316   /// \brief Fetch the type representing a 64-bit integer.
00317   IntegerType *getInt64Ty() {
00318     return Type::getInt64Ty(Context);
00319   }
00320 
00321   /// \brief Fetch the type representing a 128-bit integer.
00322   IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
00323 
00324   /// \brief Fetch the type representing an N-bit integer.
00325   IntegerType *getIntNTy(unsigned N) {
00326     return Type::getIntNTy(Context, N);
00327   }
00328 
00329   /// \brief Fetch the type representing a 16-bit floating point value.
00330   Type *getHalfTy() {
00331     return Type::getHalfTy(Context);
00332   }
00333 
00334   /// \brief Fetch the type representing a 32-bit floating point value.
00335   Type *getFloatTy() {
00336     return Type::getFloatTy(Context);
00337   }
00338 
00339   /// \brief Fetch the type representing a 64-bit floating point value.
00340   Type *getDoubleTy() {
00341     return Type::getDoubleTy(Context);
00342   }
00343 
00344   /// \brief Fetch the type representing void.
00345   Type *getVoidTy() {
00346     return Type::getVoidTy(Context);
00347   }
00348 
00349   /// \brief Fetch the type representing a pointer to an 8-bit integer value.
00350   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
00351     return Type::getInt8PtrTy(Context, AddrSpace);
00352   }
00353 
00354   /// \brief Fetch the type representing a pointer to an integer value.
00355   IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
00356     return DL.getIntPtrType(Context, AddrSpace);
00357   }
00358 
00359   //===--------------------------------------------------------------------===//
00360   // Intrinsic creation methods
00361   //===--------------------------------------------------------------------===//
00362 
00363   /// \brief Create and insert a memset to the specified pointer and the
00364   /// specified value.
00365   ///
00366   /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
00367   /// specified, it will be added to the instruction. Likewise with alias.scope
00368   /// and noalias tags.
00369   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
00370                          bool isVolatile = false, MDNode *TBAATag = nullptr,
00371                          MDNode *ScopeTag = nullptr,
00372                          MDNode *NoAliasTag = nullptr) {
00373     return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
00374                         TBAATag, ScopeTag, NoAliasTag);
00375   }
00376 
00377   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
00378                          bool isVolatile = false, MDNode *TBAATag = nullptr,
00379                          MDNode *ScopeTag = nullptr,
00380                          MDNode *NoAliasTag = nullptr);
00381 
00382   /// \brief Create and insert a memcpy between the specified pointers.
00383   ///
00384   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
00385   /// specified, it will be added to the instruction. Likewise with alias.scope
00386   /// and noalias tags.
00387   CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
00388                          bool isVolatile = false, MDNode *TBAATag = nullptr,
00389                          MDNode *TBAAStructTag = nullptr,
00390                          MDNode *ScopeTag = nullptr,
00391                          MDNode *NoAliasTag = nullptr) {
00392     return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
00393                         TBAAStructTag, ScopeTag, NoAliasTag);
00394   }
00395 
00396   CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
00397                          bool isVolatile = false, MDNode *TBAATag = nullptr,
00398                          MDNode *TBAAStructTag = nullptr,
00399                          MDNode *ScopeTag = nullptr,
00400                          MDNode *NoAliasTag = nullptr);
00401 
00402   /// \brief Create and insert a memmove between the specified
00403   /// pointers.
00404   ///
00405   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
00406   /// specified, it will be added to the instruction. Likewise with alias.scope
00407   /// and noalias tags.
00408   CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
00409                           bool isVolatile = false, MDNode *TBAATag = nullptr,
00410                           MDNode *ScopeTag = nullptr,
00411                           MDNode *NoAliasTag = nullptr) {
00412     return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
00413                          TBAATag, ScopeTag, NoAliasTag);
00414   }
00415 
00416   CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
00417                           bool isVolatile = false, MDNode *TBAATag = nullptr,
00418                           MDNode *ScopeTag = nullptr,
00419                           MDNode *NoAliasTag = nullptr);
00420 
00421   /// \brief Create a lifetime.start intrinsic.
00422   ///
00423   /// If the pointer isn't i8* it will be converted.
00424   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
00425 
00426   /// \brief Create a lifetime.end intrinsic.
00427   ///
00428   /// If the pointer isn't i8* it will be converted.
00429   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
00430 
00431   /// \brief Create a call to Masked Load intrinsic
00432   CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
00433                              Value *PassThru = nullptr, const Twine &Name = "");
00434 
00435   /// \brief Create a call to Masked Store intrinsic
00436   CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
00437                               Value *Mask);
00438 
00439   /// \brief Create an assume intrinsic call that allows the optimizer to
00440   /// assume that the provided condition will be true.
00441   CallInst *CreateAssumption(Value *Cond);
00442 
00443   /// \brief Create a call to the experimental.gc.statepoint intrinsic to
00444   /// start a new statepoint sequence.
00445   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
00446                                    Value *ActualCallee,
00447                                    ArrayRef<Value *> CallArgs,
00448                                    ArrayRef<Value *> DeoptArgs,
00449                                    ArrayRef<Value *> GCArgs,
00450                                    const Twine &Name = "");
00451 
00452   /// \brief Create a call to the experimental.gc.statepoint intrinsic to
00453   /// start a new statepoint sequence.
00454   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
00455                                    Value *ActualCallee, uint32_t Flags,
00456                                    ArrayRef<Use> CallArgs,
00457                                    ArrayRef<Use> TransitionArgs,
00458                                    ArrayRef<Use> DeoptArgs,
00459                                    ArrayRef<Value *> GCArgs,
00460                                    const Twine &Name = "");
00461 
00462   // \brief Conveninence function for the common case when CallArgs are filled
00463   // in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
00464   // .get()'ed to get the Value pointer.
00465   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
00466                                    Value *ActualCallee, ArrayRef<Use> CallArgs,
00467                                    ArrayRef<Value *> DeoptArgs,
00468                                    ArrayRef<Value *> GCArgs,
00469                                    const Twine &Name = "");
00470 
00471   /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
00472   /// start a new statepoint sequence.
00473   InvokeInst *
00474   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
00475                            Value *ActualInvokee, BasicBlock *NormalDest,
00476                            BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
00477                            ArrayRef<Value *> DeoptArgs,
00478                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
00479 
00480   /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
00481   /// start a new statepoint sequence.
00482   InvokeInst *CreateGCStatepointInvoke(
00483       uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
00484       BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
00485       ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
00486       ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs,
00487       const Twine &Name = "");
00488 
00489   // Conveninence function for the common case when CallArgs are filled in using
00490   // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
00491   // get the Value *.
00492   InvokeInst *
00493   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
00494                            Value *ActualInvokee, BasicBlock *NormalDest,
00495                            BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
00496                            ArrayRef<Value *> DeoptArgs,
00497                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
00498 
00499   /// \brief Create a call to the experimental.gc.result intrinsic to extract
00500   /// the result from a call wrapped in a statepoint.
00501   CallInst *CreateGCResult(Instruction *Statepoint,
00502                            Type *ResultType,
00503                            const Twine &Name = "");
00504 
00505   /// \brief Create a call to the experimental.gc.relocate intrinsics to
00506   /// project the relocated value of one pointer from the statepoint.
00507   CallInst *CreateGCRelocate(Instruction *Statepoint,
00508                              int BaseOffset,
00509                              int DerivedOffset,
00510                              Type *ResultType,
00511                              const Twine &Name = "");
00512 
00513 private:
00514   /// \brief Create a call to a masked intrinsic with given Id.
00515   /// Masked intrinsic has only one overloaded type - data type.
00516   CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
00517                                   Type *DataTy, const Twine &Name = "");
00518 
00519   Value *getCastedInt8PtrValue(Value *Ptr);
00520 };
00521 
00522 /// \brief This provides a uniform API for creating instructions and inserting
00523 /// them into a basic block: either at the end of a BasicBlock, or at a specific
00524 /// iterator location in a block.
00525 ///
00526 /// Note that the builder does not expose the full generality of LLVM
00527 /// instructions.  For access to extra instruction properties, use the mutators
00528 /// (e.g. setVolatile) on the instructions after they have been
00529 /// created. Convenience state exists to specify fast-math flags and fp-math
00530 /// tags.
00531 ///
00532 /// The first template argument handles whether or not to preserve names in the
00533 /// final instruction output. This defaults to on.  The second template argument
00534 /// specifies a class to use for creating constants.  This defaults to creating
00535 /// minimally folded constants.  The third template argument allows clients to
00536 /// specify custom insertion hooks that are called on every newly created
00537 /// insertion.
00538 template<bool preserveNames = true, typename T = ConstantFolder,
00539          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
00540 class IRBuilder : public IRBuilderBase, public Inserter {
00541   T Folder;
00542 
00543 public:
00544   IRBuilder(LLVMContext &C, const T &F, Inserter I = Inserter(),
00545             MDNode *FPMathTag = nullptr,
00546             ArrayRef<OperandBundleDef> OpBundles = None)
00547       : IRBuilderBase(C, FPMathTag, OpBundles), Inserter(std::move(I)),
00548         Folder(F) {}
00549 
00550   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr,
00551                      ArrayRef<OperandBundleDef> OpBundles = None)
00552       : IRBuilderBase(C, FPMathTag, OpBundles), Folder() {}
00553 
00554   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr,
00555                      ArrayRef<OperandBundleDef> OpBundles = None)
00556       : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
00557     SetInsertPoint(TheBB);
00558   }
00559 
00560   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr,
00561                      ArrayRef<OperandBundleDef> OpBundles = None)
00562       : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder() {
00563     SetInsertPoint(TheBB);
00564   }
00565 
00566   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr,
00567                      ArrayRef<OperandBundleDef> OpBundles = None)
00568       : IRBuilderBase(IP->getContext(), FPMathTag, OpBundles), Folder() {
00569     SetInsertPoint(IP);
00570   }
00571 
00572   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T &F,
00573             MDNode *FPMathTag = nullptr,
00574             ArrayRef<OperandBundleDef> OpBundles = None)
00575       : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
00576     SetInsertPoint(TheBB, IP);
00577   }
00578 
00579   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
00580             MDNode *FPMathTag = nullptr,
00581             ArrayRef<OperandBundleDef> OpBundles = None)
00582       : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder() {
00583     SetInsertPoint(TheBB, IP);
00584   }
00585 
00586   /// \brief Get the constant folder being used.
00587   const T &getFolder() { return Folder; }
00588 
00589   /// \brief Return true if this builder is configured to actually add the
00590   /// requested names to IR created through it.
00591   bool isNamePreserving() const { return preserveNames; }
00592 
00593   /// \brief Insert and return the specified instruction.
00594   template<typename InstTy>
00595   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
00596     this->InsertHelper(I, Name, BB, InsertPt);
00597     this->SetInstDebugLocation(I);
00598     return I;
00599   }
00600 
00601   /// \brief No-op overload to handle constants.
00602   Constant *Insert(Constant *C, const Twine& = "") const {
00603     return C;
00604   }
00605 
00606   //===--------------------------------------------------------------------===//
00607   // Instruction creation methods: Terminators
00608   //===--------------------------------------------------------------------===//
00609 
00610 private:
00611   /// \brief Helper to add branch weight and unpredictable metadata onto an
00612   /// instruction.
00613   /// \returns The annotated instruction.
00614   template <typename InstTy>
00615   InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
00616     if (Weights)
00617       I->setMetadata(LLVMContext::MD_prof, Weights);
00618     if (Unpredictable)
00619       I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
00620     return I;
00621   }
00622 
00623 public:
00624   /// \brief Create a 'ret void' instruction.
00625   ReturnInst *CreateRetVoid() {
00626     return Insert(ReturnInst::Create(Context));
00627   }
00628 
00629   /// \brief Create a 'ret <val>' instruction.
00630   ReturnInst *CreateRet(Value *V) {
00631     return Insert(ReturnInst::Create(Context, V));
00632   }
00633 
00634   /// \brief Create a sequence of N insertvalue instructions,
00635   /// with one Value from the retVals array each, that build a aggregate
00636   /// return value one value at a time, and a ret instruction to return
00637   /// the resulting aggregate value.
00638   ///
00639   /// This is a convenience function for code that uses aggregate return values
00640   /// as a vehicle for having multiple return values.
00641   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
00642     Value *V = UndefValue::get(getCurrentFunctionReturnType());
00643     for (unsigned i = 0; i != N; ++i)
00644       V = CreateInsertValue(V, retVals[i], i, "mrv");
00645     return Insert(ReturnInst::Create(Context, V));
00646   }
00647 
00648   /// \brief Create an unconditional 'br label X' instruction.
00649   BranchInst *CreateBr(BasicBlock *Dest) {
00650     return Insert(BranchInst::Create(Dest));
00651   }
00652 
00653   /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
00654   /// instruction.
00655   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
00656                            MDNode *BranchWeights = nullptr,
00657                            MDNode *Unpredictable = nullptr) {
00658     return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
00659                                     BranchWeights, Unpredictable));
00660   }
00661 
00662   /// \brief Create a switch instruction with the specified value, default dest,
00663   /// and with a hint for the number of cases that will be added (for efficient
00664   /// allocation).
00665   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
00666                            MDNode *BranchWeights = nullptr,
00667                            MDNode *Unpredictable = nullptr) {
00668     return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
00669                                     BranchWeights, Unpredictable));
00670   }
00671 
00672   /// \brief Create an indirect branch instruction with the specified address
00673   /// operand, with an optional hint for the number of destinations that will be
00674   /// added (for efficient allocation).
00675   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
00676     return Insert(IndirectBrInst::Create(Addr, NumDests));
00677   }
00678 
00679   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
00680                            BasicBlock *UnwindDest, const Twine &Name = "") {
00681     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, None),
00682                   Name);
00683   }
00684   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
00685                            BasicBlock *UnwindDest, Value *Arg1,
00686                            const Twine &Name = "") {
00687     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
00688                   Name);
00689   }
00690   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
00691                             BasicBlock *UnwindDest, Value *Arg1,
00692                             Value *Arg2, Value *Arg3,
00693                             const Twine &Name = "") {
00694     Value *Args[] = { Arg1, Arg2, Arg3 };
00695     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
00696                   Name);
00697   }
00698   /// \brief Create an invoke instruction.
00699   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
00700                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
00701                            const Twine &Name = "") {
00702     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
00703                   Name);
00704   }
00705   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
00706                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
00707                            ArrayRef<OperandBundleDef> OpBundles,
00708                            const Twine &Name = "") {
00709     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args,
00710                                      OpBundles), Name);
00711   }
00712 
00713   ResumeInst *CreateResume(Value *Exn) {
00714     return Insert(ResumeInst::Create(Exn));
00715   }
00716 
00717   CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
00718                                       BasicBlock *UnwindBB = nullptr) {
00719     return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
00720   }
00721 
00722   CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
00723                                      unsigned NumHandlers,
00724                                      const Twine &Name = "") {
00725     return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
00726                   Name);
00727   }
00728 
00729   CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
00730                                const Twine &Name = "") {
00731     return Insert(CatchPadInst::Create(ParentPad, Args), Name);
00732   }
00733 
00734   CleanupPadInst *CreateCleanupPad(Value *ParentPad,
00735                                    ArrayRef<Value *> Args = None,
00736                                    const Twine &Name = "") {
00737     return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
00738   }
00739 
00740   CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
00741     return Insert(CatchReturnInst::Create(CatchPad, BB));
00742   }
00743 
00744   UnreachableInst *CreateUnreachable() {
00745     return Insert(new UnreachableInst(Context));
00746   }
00747 
00748   //===--------------------------------------------------------------------===//
00749   // Instruction creation methods: Binary Operators
00750   //===--------------------------------------------------------------------===//
00751 private:
00752   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
00753                                           Value *LHS, Value *RHS,
00754                                           const Twine &Name,
00755                                           bool HasNUW, bool HasNSW) {
00756     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
00757     if (HasNUW) BO->setHasNoUnsignedWrap();
00758     if (HasNSW) BO->setHasNoSignedWrap();
00759     return BO;
00760   }
00761 
00762   Instruction *AddFPMathAttributes(Instruction *I,
00763                                    MDNode *FPMathTag,
00764                                    FastMathFlags FMF) const {
00765     if (!FPMathTag)
00766       FPMathTag = DefaultFPMathTag;
00767     if (FPMathTag)
00768       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
00769     I->setFastMathFlags(FMF);
00770     return I;
00771   }
00772 
00773 public:
00774   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
00775                    bool HasNUW = false, bool HasNSW = false) {
00776     if (Constant *LC = dyn_cast<Constant>(LHS))
00777       if (Constant *RC = dyn_cast<Constant>(RHS))
00778         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
00779     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
00780                                    HasNUW, HasNSW);
00781   }
00782   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
00783     return CreateAdd(LHS, RHS, Name, false, true);
00784   }
00785   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
00786     return CreateAdd(LHS, RHS, Name, true, false);
00787   }
00788   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
00789                     MDNode *FPMathTag = nullptr) {
00790     if (Constant *LC = dyn_cast<Constant>(LHS))
00791       if (Constant *RC = dyn_cast<Constant>(RHS))
00792         return Insert(Folder.CreateFAdd(LC, RC), Name);
00793     return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
00794                                       FPMathTag, FMF), Name);
00795   }
00796   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
00797                    bool HasNUW = false, bool HasNSW = false) {
00798     if (Constant *LC = dyn_cast<Constant>(LHS))
00799       if (Constant *RC = dyn_cast<Constant>(RHS))
00800         return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
00801     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
00802                                    HasNUW, HasNSW);
00803   }
00804   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
00805     return CreateSub(LHS, RHS, Name, false, true);
00806   }
00807   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
00808     return CreateSub(LHS, RHS, Name, true, false);
00809   }
00810   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
00811                     MDNode *FPMathTag = nullptr) {
00812     if (Constant *LC = dyn_cast<Constant>(LHS))
00813       if (Constant *RC = dyn_cast<Constant>(RHS))
00814         return Insert(Folder.CreateFSub(LC, RC), Name);
00815     return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
00816                                       FPMathTag, FMF), Name);
00817   }
00818   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
00819                    bool HasNUW = false, bool HasNSW = false) {
00820     if (Constant *LC = dyn_cast<Constant>(LHS))
00821       if (Constant *RC = dyn_cast<Constant>(RHS))
00822         return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
00823     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
00824                                    HasNUW, HasNSW);
00825   }
00826   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
00827     return CreateMul(LHS, RHS, Name, false, true);
00828   }
00829   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
00830     return CreateMul(LHS, RHS, Name, true, false);
00831   }
00832   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
00833                     MDNode *FPMathTag = nullptr) {
00834     if (Constant *LC = dyn_cast<Constant>(LHS))
00835       if (Constant *RC = dyn_cast<Constant>(RHS))
00836         return Insert(Folder.CreateFMul(LC, RC), Name);
00837     return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
00838                                       FPMathTag, FMF), Name);
00839   }
00840   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
00841                     bool isExact = false) {
00842     if (Constant *LC = dyn_cast<Constant>(LHS))
00843       if (Constant *RC = dyn_cast<Constant>(RHS))
00844         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
00845     if (!isExact)
00846       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
00847     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
00848   }
00849   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
00850     return CreateUDiv(LHS, RHS, Name, true);
00851   }
00852   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
00853                     bool isExact = false) {
00854     if (Constant *LC = dyn_cast<Constant>(LHS))
00855       if (Constant *RC = dyn_cast<Constant>(RHS))
00856         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
00857     if (!isExact)
00858       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
00859     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
00860   }
00861   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
00862     return CreateSDiv(LHS, RHS, Name, true);
00863   }
00864   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
00865                     MDNode *FPMathTag = nullptr) {
00866     if (Constant *LC = dyn_cast<Constant>(LHS))
00867       if (Constant *RC = dyn_cast<Constant>(RHS))
00868         return Insert(Folder.CreateFDiv(LC, RC), Name);
00869     return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
00870                                       FPMathTag, FMF), Name);
00871   }
00872   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
00873     if (Constant *LC = dyn_cast<Constant>(LHS))
00874       if (Constant *RC = dyn_cast<Constant>(RHS))
00875         return Insert(Folder.CreateURem(LC, RC), Name);
00876     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
00877   }
00878   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
00879     if (Constant *LC = dyn_cast<Constant>(LHS))
00880       if (Constant *RC = dyn_cast<Constant>(RHS))
00881         return Insert(Folder.CreateSRem(LC, RC), Name);
00882     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
00883   }
00884   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
00885                     MDNode *FPMathTag = nullptr) {
00886     if (Constant *LC = dyn_cast<Constant>(LHS))
00887       if (Constant *RC = dyn_cast<Constant>(RHS))
00888         return Insert(Folder.CreateFRem(LC, RC), Name);
00889     return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
00890                                       FPMathTag, FMF), Name);
00891   }
00892 
00893   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
00894                    bool HasNUW = false, bool HasNSW = false) {
00895     if (Constant *LC = dyn_cast<Constant>(LHS))
00896       if (Constant *RC = dyn_cast<Constant>(RHS))
00897         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
00898     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
00899                                    HasNUW, HasNSW);
00900   }
00901   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
00902                    bool HasNUW = false, bool HasNSW = false) {
00903     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
00904                      HasNUW, HasNSW);
00905   }
00906   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
00907                    bool HasNUW = false, bool HasNSW = false) {
00908     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
00909                      HasNUW, HasNSW);
00910   }
00911 
00912   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
00913                     bool isExact = false) {
00914     if (Constant *LC = dyn_cast<Constant>(LHS))
00915       if (Constant *RC = dyn_cast<Constant>(RHS))
00916         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
00917     if (!isExact)
00918       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
00919     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
00920   }
00921   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
00922                     bool isExact = false) {
00923     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
00924   }
00925   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
00926                     bool isExact = false) {
00927     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
00928   }
00929 
00930   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
00931                     bool isExact = false) {
00932     if (Constant *LC = dyn_cast<Constant>(LHS))
00933       if (Constant *RC = dyn_cast<Constant>(RHS))
00934         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
00935     if (!isExact)
00936       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
00937     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
00938   }
00939   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
00940                     bool isExact = false) {
00941     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
00942   }
00943   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
00944                     bool isExact = false) {
00945     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
00946   }
00947 
00948   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
00949     if (Constant *RC = dyn_cast<Constant>(RHS)) {
00950       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
00951         return LHS;  // LHS & -1 -> LHS
00952       if (Constant *LC = dyn_cast<Constant>(LHS))
00953         return Insert(Folder.CreateAnd(LC, RC), Name);
00954     }
00955     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
00956   }
00957   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
00958     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00959   }
00960   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
00961     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00962   }
00963 
00964   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
00965     if (Constant *RC = dyn_cast<Constant>(RHS)) {
00966       if (RC->isNullValue())
00967         return LHS;  // LHS | 0 -> LHS
00968       if (Constant *LC = dyn_cast<Constant>(LHS))
00969         return Insert(Folder.CreateOr(LC, RC), Name);
00970     }
00971     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
00972   }
00973   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
00974     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00975   }
00976   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
00977     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00978   }
00979 
00980   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
00981     if (Constant *LC = dyn_cast<Constant>(LHS))
00982       if (Constant *RC = dyn_cast<Constant>(RHS))
00983         return Insert(Folder.CreateXor(LC, RC), Name);
00984     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
00985   }
00986   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
00987     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00988   }
00989   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
00990     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00991   }
00992 
00993   Value *CreateBinOp(Instruction::BinaryOps Opc,
00994                      Value *LHS, Value *RHS, const Twine &Name = "",
00995                      MDNode *FPMathTag = nullptr) {
00996     if (Constant *LC = dyn_cast<Constant>(LHS))
00997       if (Constant *RC = dyn_cast<Constant>(RHS))
00998         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
00999     llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
01000     if (isa<FPMathOperator>(BinOp))
01001       BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
01002     return Insert(BinOp, Name);
01003   }
01004 
01005   Value *CreateNeg(Value *V, const Twine &Name = "",
01006                    bool HasNUW = false, bool HasNSW = false) {
01007     if (Constant *VC = dyn_cast<Constant>(V))
01008       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
01009     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
01010     if (HasNUW) BO->setHasNoUnsignedWrap();
01011     if (HasNSW) BO->setHasNoSignedWrap();
01012     return BO;
01013   }
01014   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
01015     return CreateNeg(V, Name, false, true);
01016   }
01017   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
01018     return CreateNeg(V, Name, true, false);
01019   }
01020   Value *CreateFNeg(Value *V, const Twine &Name = "",
01021                     MDNode *FPMathTag = nullptr) {
01022     if (Constant *VC = dyn_cast<Constant>(V))
01023       return Insert(Folder.CreateFNeg(VC), Name);
01024     return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
01025                                       FPMathTag, FMF), Name);
01026   }
01027   Value *CreateNot(Value *V, const Twine &Name = "") {
01028     if (Constant *VC = dyn_cast<Constant>(V))
01029       return Insert(Folder.CreateNot(VC), Name);
01030     return Insert(BinaryOperator::CreateNot(V), Name);
01031   }
01032 
01033   //===--------------------------------------------------------------------===//
01034   // Instruction creation methods: Memory Instructions
01035   //===--------------------------------------------------------------------===//
01036 
01037   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
01038                            const Twine &Name = "") {
01039     return Insert(new AllocaInst(Ty, ArraySize), Name);
01040   }
01041   // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
01042   // converting the string to 'bool' for the isVolatile parameter.
01043   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
01044     return Insert(new LoadInst(Ptr), Name);
01045   }
01046   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
01047     return Insert(new LoadInst(Ptr), Name);
01048   }
01049   LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
01050     return Insert(new LoadInst(Ty, Ptr), Name);
01051   }
01052   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
01053     return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
01054   }
01055   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
01056     return Insert(new StoreInst(Val, Ptr, isVolatile));
01057   }
01058   // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
01059   // correctly, instead of converting the string to 'bool' for the isVolatile
01060   // parameter.
01061   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
01062     LoadInst *LI = CreateLoad(Ptr, Name);
01063     LI->setAlignment(Align);
01064     return LI;
01065   }
01066   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
01067                               const Twine &Name = "") {
01068     LoadInst *LI = CreateLoad(Ptr, Name);
01069     LI->setAlignment(Align);
01070     return LI;
01071   }
01072   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
01073                               const Twine &Name = "") {
01074     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
01075     LI->setAlignment(Align);
01076     return LI;
01077   }
01078   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
01079                                 bool isVolatile = false) {
01080     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
01081     SI->setAlignment(Align);
01082     return SI;
01083   }
01084   FenceInst *CreateFence(AtomicOrdering Ordering,
01085                          SynchronizationScope SynchScope = CrossThread,
01086                          const Twine &Name = "") {
01087     return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
01088   }
01089   AtomicCmpXchgInst *
01090   CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
01091                       AtomicOrdering SuccessOrdering,
01092                       AtomicOrdering FailureOrdering,
01093                       SynchronizationScope SynchScope = CrossThread) {
01094     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
01095                                         FailureOrdering, SynchScope));
01096   }
01097   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
01098                                  AtomicOrdering Ordering,
01099                                SynchronizationScope SynchScope = CrossThread) {
01100     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
01101   }
01102   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
01103                    const Twine &Name = "") {
01104     return CreateGEP(nullptr, Ptr, IdxList, Name);
01105   }
01106   Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
01107                    const Twine &Name = "") {
01108     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
01109       // Every index must be constant.
01110       size_t i, e;
01111       for (i = 0, e = IdxList.size(); i != e; ++i)
01112         if (!isa<Constant>(IdxList[i]))
01113           break;
01114       if (i == e)
01115         return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
01116     }
01117     return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
01118   }
01119   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
01120                            const Twine &Name = "") {
01121     return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
01122   }
01123   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
01124                            const Twine &Name = "") {
01125     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
01126       // Every index must be constant.
01127       size_t i, e;
01128       for (i = 0, e = IdxList.size(); i != e; ++i)
01129         if (!isa<Constant>(IdxList[i]))
01130           break;
01131       if (i == e)
01132         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
01133                       Name);
01134     }
01135     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
01136   }
01137   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
01138     return CreateGEP(nullptr, Ptr, Idx, Name);
01139   }
01140   Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
01141     if (Constant *PC = dyn_cast<Constant>(Ptr))
01142       if (Constant *IC = dyn_cast<Constant>(Idx))
01143         return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
01144     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
01145   }
01146   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
01147                            const Twine &Name = "") {
01148     if (Constant *PC = dyn_cast<Constant>(Ptr))
01149       if (Constant *IC = dyn_cast<Constant>(Idx))
01150         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
01151     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
01152   }
01153   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
01154     return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
01155   }
01156   Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
01157                             const Twine &Name = "") {
01158     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
01159 
01160     if (Constant *PC = dyn_cast<Constant>(Ptr))
01161       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
01162 
01163     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
01164   }
01165   Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
01166                                     const Twine &Name = "") {
01167     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
01168 
01169     if (Constant *PC = dyn_cast<Constant>(Ptr))
01170       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
01171 
01172     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
01173   }
01174   Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
01175                             const Twine &Name = "") {
01176     Value *Idxs[] = {
01177       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
01178       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
01179     };
01180 
01181     if (Constant *PC = dyn_cast<Constant>(Ptr))
01182       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
01183 
01184     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
01185   }
01186   Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
01187                                     unsigned Idx1, const Twine &Name = "") {
01188     Value *Idxs[] = {
01189       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
01190       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
01191     };
01192 
01193     if (Constant *PC = dyn_cast<Constant>(Ptr))
01194       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
01195 
01196     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
01197   }
01198   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
01199     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
01200 
01201     if (Constant *PC = dyn_cast<Constant>(Ptr))
01202       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
01203 
01204     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
01205   }
01206   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
01207                                     const Twine &Name = "") {
01208     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
01209 
01210     if (Constant *PC = dyn_cast<Constant>(Ptr))
01211       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
01212 
01213     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
01214   }
01215   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
01216                     const Twine &Name = "") {
01217     Value *Idxs[] = {
01218       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
01219       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
01220     };
01221 
01222     if (Constant *PC = dyn_cast<Constant>(Ptr))
01223       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
01224 
01225     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
01226   }
01227   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
01228                                     const Twine &Name = "") {
01229     Value *Idxs[] = {
01230       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
01231       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
01232     };
01233 
01234     if (Constant *PC = dyn_cast<Constant>(Ptr))
01235       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
01236                     Name);
01237 
01238     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
01239   }
01240   Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
01241                          const Twine &Name = "") {
01242     return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
01243   }
01244 
01245   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
01246   /// instead of a pointer to array of i8.
01247   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
01248                                unsigned AddressSpace = 0) {
01249     GlobalVariable *gv = CreateGlobalString(Str, Name, AddressSpace);
01250     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
01251     Value *Args[] = { zero, zero };
01252     return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
01253   }
01254 
01255   //===--------------------------------------------------------------------===//
01256   // Instruction creation methods: Cast/Conversion Operators
01257   //===--------------------------------------------------------------------===//
01258 
01259   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
01260     return CreateCast(Instruction::Trunc, V, DestTy, Name);
01261   }
01262   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
01263     return CreateCast(Instruction::ZExt, V, DestTy, Name);
01264   }
01265   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
01266     return CreateCast(Instruction::SExt, V, DestTy, Name);
01267   }
01268   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
01269   /// the value untouched if the type of V is already DestTy.
01270   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
01271                            const Twine &Name = "") {
01272     assert(V->getType()->isIntOrIntVectorTy() &&
01273            DestTy->isIntOrIntVectorTy() &&
01274            "Can only zero extend/truncate integers!");
01275     Type *VTy = V->getType();
01276     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
01277       return CreateZExt(V, DestTy, Name);
01278     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
01279       return CreateTrunc(V, DestTy, Name);
01280     return V;
01281   }
01282   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
01283   /// the value untouched if the type of V is already DestTy.
01284   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
01285                            const Twine &Name = "") {
01286     assert(V->getType()->isIntOrIntVectorTy() &&
01287            DestTy->isIntOrIntVectorTy() &&
01288            "Can only sign extend/truncate integers!");
01289     Type *VTy = V->getType();
01290     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
01291       return CreateSExt(V, DestTy, Name);
01292     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
01293       return CreateTrunc(V, DestTy, Name);
01294     return V;
01295   }
01296   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
01297     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
01298   }
01299   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
01300     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
01301   }
01302   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
01303     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
01304   }
01305   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
01306     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
01307   }
01308   Value *CreateFPTrunc(Value *V, Type *DestTy,
01309                        const Twine &Name = "") {
01310     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
01311   }
01312   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
01313     return CreateCast(Instruction::FPExt, V, DestTy, Name);
01314   }
01315   Value *CreatePtrToInt(Value *V, Type *DestTy,
01316                         const Twine &Name = "") {
01317     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
01318   }
01319   Value *CreateIntToPtr(Value *V, Type *DestTy,
01320                         const Twine &Name = "") {
01321     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
01322   }
01323   Value *CreateBitCast(Value *V, Type *DestTy,
01324                        const Twine &Name = "") {
01325     return CreateCast(Instruction::BitCast, V, DestTy, Name);
01326   }
01327   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
01328                              const Twine &Name = "") {
01329     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
01330   }
01331   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
01332                              const Twine &Name = "") {
01333     if (V->getType() == DestTy)
01334       return V;
01335     if (Constant *VC = dyn_cast<Constant>(V))
01336       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
01337     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
01338   }
01339   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
01340                              const Twine &Name = "") {
01341     if (V->getType() == DestTy)
01342       return V;
01343     if (Constant *VC = dyn_cast<Constant>(V))
01344       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
01345     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
01346   }
01347   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
01348                               const Twine &Name = "") {
01349     if (V->getType() == DestTy)
01350       return V;
01351     if (Constant *VC = dyn_cast<Constant>(V))
01352       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
01353     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
01354   }
01355   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
01356                     const Twine &Name = "") {
01357     if (V->getType() == DestTy)
01358       return V;
01359     if (Constant *VC = dyn_cast<Constant>(V))
01360       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
01361     return Insert(CastInst::Create(Op, V, DestTy), Name);
01362   }
01363   Value *CreatePointerCast(Value *V, Type *DestTy,
01364                            const Twine &Name = "") {
01365     if (V->getType() == DestTy)
01366       return V;
01367     if (Constant *VC = dyn_cast<Constant>(V))
01368       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
01369     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
01370   }
01371 
01372   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
01373                                              const Twine &Name = "") {
01374     if (V->getType() == DestTy)
01375       return V;
01376 
01377     if (Constant *VC = dyn_cast<Constant>(V)) {
01378       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
01379                     Name);
01380     }
01381 
01382     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
01383                   Name);
01384   }
01385 
01386   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
01387                        const Twine &Name = "") {
01388     if (V->getType() == DestTy)
01389       return V;
01390     if (Constant *VC = dyn_cast<Constant>(V))
01391       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
01392     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
01393   }
01394 
01395   Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
01396                                 const Twine &Name = "") {
01397     if (V->getType() == DestTy)
01398       return V;
01399     if (V->getType()->getScalarType()->isPointerTy() &&
01400         DestTy->getScalarType()->isIntegerTy())
01401       return CreatePtrToInt(V, DestTy, Name);
01402     if (V->getType()->getScalarType()->isIntegerTy() &&
01403         DestTy->getScalarType()->isPointerTy())
01404       return CreateIntToPtr(V, DestTy, Name);
01405 
01406     return CreateBitCast(V, DestTy, Name);
01407   }
01408 
01409 private:
01410   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
01411   // compile time error, instead of converting the string to bool for the
01412   // isSigned parameter.
01413   Value *CreateIntCast(Value *, Type *, const char *) = delete;
01414 
01415 public:
01416   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
01417     if (V->getType() == DestTy)
01418       return V;
01419     if (Constant *VC = dyn_cast<Constant>(V))
01420       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
01421     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
01422   }
01423 
01424   //===--------------------------------------------------------------------===//
01425   // Instruction creation methods: Compare Instructions
01426   //===--------------------------------------------------------------------===//
01427 
01428   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
01429     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
01430   }
01431   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
01432     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
01433   }
01434   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
01435     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
01436   }
01437   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
01438     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
01439   }
01440   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
01441     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
01442   }
01443   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
01444     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
01445   }
01446   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
01447     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
01448   }
01449   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
01450     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
01451   }
01452   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
01453     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
01454   }
01455   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
01456     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
01457   }
01458 
01459   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
01460                        MDNode *FPMathTag = nullptr) {
01461     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
01462   }
01463   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
01464                        MDNode *FPMathTag = nullptr) {
01465     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
01466   }
01467   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
01468                        MDNode *FPMathTag = nullptr) {
01469     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
01470   }
01471   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
01472                        MDNode *FPMathTag = nullptr) {
01473     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
01474   }
01475   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
01476                        MDNode *FPMathTag = nullptr) {
01477     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
01478   }
01479   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
01480                        MDNode *FPMathTag = nullptr) {
01481     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
01482   }
01483   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
01484                        MDNode *FPMathTag = nullptr) {
01485     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
01486   }
01487   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
01488                        MDNode *FPMathTag = nullptr) {
01489     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
01490   }
01491   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
01492                        MDNode *FPMathTag = nullptr) {
01493     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
01494   }
01495   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
01496                        MDNode *FPMathTag = nullptr) {
01497     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
01498   }
01499   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
01500                        MDNode *FPMathTag = nullptr) {
01501     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
01502   }
01503   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
01504                        MDNode *FPMathTag = nullptr) {
01505     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
01506   }
01507   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
01508                        MDNode *FPMathTag = nullptr) {
01509     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
01510   }
01511   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
01512                        MDNode *FPMathTag = nullptr) {
01513     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
01514   }
01515 
01516   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
01517                     const Twine &Name = "") {
01518     if (Constant *LC = dyn_cast<Constant>(LHS))
01519       if (Constant *RC = dyn_cast<Constant>(RHS))
01520         return Insert(Folder.CreateICmp(P, LC, RC), Name);
01521     return Insert(new ICmpInst(P, LHS, RHS), Name);
01522   }
01523   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
01524                     const Twine &Name = "", MDNode *FPMathTag = nullptr) {
01525     if (Constant *LC = dyn_cast<Constant>(LHS))
01526       if (Constant *RC = dyn_cast<Constant>(RHS))
01527         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
01528     return Insert(AddFPMathAttributes(new FCmpInst(P, LHS, RHS),
01529                                       FPMathTag, FMF), Name);
01530   }
01531 
01532   //===--------------------------------------------------------------------===//
01533   // Instruction creation methods: Other Instructions
01534   //===--------------------------------------------------------------------===//
01535 
01536   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
01537                      const Twine &Name = "") {
01538     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
01539   }
01540 
01541   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
01542                        ArrayRef<OperandBundleDef> OpBundles = None,
01543                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
01544     CallInst *CI = CallInst::Create(Callee, Args, OpBundles);
01545     if (isa<FPMathOperator>(CI))
01546       CI = cast<CallInst>(AddFPMathAttributes(CI, FPMathTag, FMF));
01547     return Insert(CI, Name);
01548   }
01549 
01550   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
01551                        const Twine &Name, MDNode *FPMathTag = nullptr) {
01552     PointerType *PTy = cast<PointerType>(Callee->getType());
01553     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01554     return CreateCall(FTy, Callee, Args, Name, FPMathTag);
01555   }
01556 
01557   CallInst *CreateCall(llvm::FunctionType *FTy, Value *Callee,
01558                        ArrayRef<Value *> Args, const Twine &Name = "",
01559                        MDNode *FPMathTag = nullptr) {
01560     CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles);
01561     if (isa<FPMathOperator>(CI))
01562       CI = cast<CallInst>(AddFPMathAttributes(CI, FPMathTag, FMF));
01563     return Insert(CI, Name);
01564   }
01565 
01566   CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
01567                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
01568     return CreateCall(Callee->getFunctionType(), Callee, Args, Name, FPMathTag);
01569   }
01570 
01571   Value *CreateSelect(Value *C, Value *True, Value *False,
01572                       const Twine &Name = "") {
01573     if (Constant *CC = dyn_cast<Constant>(C))
01574       if (Constant *TC = dyn_cast<Constant>(True))
01575         if (Constant *FC = dyn_cast<Constant>(False))
01576           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
01577     return Insert(SelectInst::Create(C, True, False), Name);
01578   }
01579 
01580   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
01581     return Insert(new VAArgInst(List, Ty), Name);
01582   }
01583 
01584   Value *CreateExtractElement(Value *Vec, Value *Idx,
01585                               const Twine &Name = "") {
01586     if (Constant *VC = dyn_cast<Constant>(Vec))
01587       if (Constant *IC = dyn_cast<Constant>(Idx))
01588         return Insert(Folder.CreateExtractElement(VC, IC), Name);
01589     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
01590   }
01591 
01592   Value *CreateExtractElement(Value *Vec, uint64_t Idx,
01593                               const Twine &Name = "") {
01594     return CreateExtractElement(Vec, getInt64(Idx), Name);
01595   }
01596 
01597   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
01598                              const Twine &Name = "") {
01599     if (Constant *VC = dyn_cast<Constant>(Vec))
01600       if (Constant *NC = dyn_cast<Constant>(NewElt))
01601         if (Constant *IC = dyn_cast<Constant>(Idx))
01602           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
01603     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
01604   }
01605 
01606   Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
01607                              const Twine &Name = "") {
01608     return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
01609   }
01610 
01611   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
01612                              const Twine &Name = "") {
01613     if (Constant *V1C = dyn_cast<Constant>(V1))
01614       if (Constant *V2C = dyn_cast<Constant>(V2))
01615         if (Constant *MC = dyn_cast<Constant>(Mask))
01616           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
01617     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
01618   }
01619 
01620   Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> IntMask,
01621                              const Twine &Name = "") {
01622     size_t MaskSize = IntMask.size();
01623     SmallVector<Constant*, 8> MaskVec(MaskSize);
01624     for (size_t i = 0; i != MaskSize; ++i)
01625       MaskVec[i] = getInt32(IntMask[i]);
01626     Value *Mask = ConstantVector::get(MaskVec);
01627     return CreateShuffleVector(V1, V2, Mask, Name);
01628   }
01629 
01630   Value *CreateExtractValue(Value *Agg,
01631                             ArrayRef<unsigned> Idxs,
01632                             const Twine &Name = "") {
01633     if (Constant *AggC = dyn_cast<Constant>(Agg))
01634       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
01635     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
01636   }
01637 
01638   Value *CreateInsertValue(Value *Agg, Value *Val,
01639                            ArrayRef<unsigned> Idxs,
01640                            const Twine &Name = "") {
01641     if (Constant *AggC = dyn_cast<Constant>(Agg))
01642       if (Constant *ValC = dyn_cast<Constant>(Val))
01643         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
01644     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
01645   }
01646 
01647   LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
01648                                    const Twine &Name = "") {
01649     return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
01650   }
01651 
01652   //===--------------------------------------------------------------------===//
01653   // Utility creation methods
01654   //===--------------------------------------------------------------------===//
01655 
01656   /// \brief Return an i1 value testing if \p Arg is null.
01657   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
01658     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
01659                         Name);
01660   }
01661 
01662   /// \brief Return an i1 value testing if \p Arg is not null.
01663   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
01664     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
01665                         Name);
01666   }
01667 
01668   /// \brief Return the i64 difference between two pointer values, dividing out
01669   /// the size of the pointed-to objects.
01670   ///
01671   /// This is intended to implement C-style pointer subtraction. As such, the
01672   /// pointers must be appropriately aligned for their element types and
01673   /// pointing into the same object.
01674   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
01675     assert(LHS->getType() == RHS->getType() &&
01676            "Pointer subtraction operand types must match!");
01677     PointerType *ArgType = cast<PointerType>(LHS->getType());
01678     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
01679     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
01680     Value *Difference = CreateSub(LHS_int, RHS_int);
01681     return CreateExactSDiv(Difference,
01682                            ConstantExpr::getSizeOf(ArgType->getElementType()),
01683                            Name);
01684   }
01685 
01686   /// \brief Create an invariant.group.barrier intrinsic call, that stops
01687   /// optimizer to propagate equality using invariant.group metadata.
01688   /// If Ptr type is different from i8*, it's casted to i8* before call
01689   /// and casted back to Ptr type after call.
01690   Value *CreateInvariantGroupBarrier(Value *Ptr) {
01691     Module *M = BB->getParent()->getParent();
01692     Function *FnInvariantGroupBarrier = Intrinsic::getDeclaration(M,
01693             Intrinsic::invariant_group_barrier);
01694 
01695     Type *ArgumentAndReturnType = FnInvariantGroupBarrier->getReturnType();
01696     assert(ArgumentAndReturnType ==
01697         FnInvariantGroupBarrier->getFunctionType()->getParamType(0) &&
01698         "InvariantGroupBarrier should take and return the same type");
01699     Type *PtrType = Ptr->getType();
01700 
01701     bool PtrTypeConversionNeeded = PtrType != ArgumentAndReturnType;
01702     if (PtrTypeConversionNeeded)
01703       Ptr = CreateBitCast(Ptr, ArgumentAndReturnType);
01704 
01705     CallInst *Fn = CreateCall(FnInvariantGroupBarrier, {Ptr});
01706 
01707     if (PtrTypeConversionNeeded)
01708       return CreateBitCast(Fn, PtrType);
01709     return Fn;
01710   }
01711 
01712   /// \brief Return a vector value that contains \arg V broadcasted to \p
01713   /// NumElts elements.
01714   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
01715     assert(NumElts > 0 && "Cannot splat to an empty vector!");
01716 
01717     // First insert it into an undef vector so we can shuffle it.
01718     Type *I32Ty = getInt32Ty();
01719     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
01720     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
01721                             Name + ".splatinsert");
01722 
01723     // Shuffle the value across the desired number of elements.
01724     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
01725     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
01726   }
01727 
01728   /// \brief Return a value that has been extracted from a larger integer type.
01729   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
01730                               IntegerType *ExtractedTy, uint64_t Offset,
01731                               const Twine &Name) {
01732     IntegerType *IntTy = cast<IntegerType>(From->getType());
01733     assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
01734                DL.getTypeStoreSize(IntTy) &&
01735            "Element extends past full value");
01736     uint64_t ShAmt = 8 * Offset;
01737     Value *V = From;
01738     if (DL.isBigEndian())
01739       ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
01740                    DL.getTypeStoreSize(ExtractedTy) - Offset);
01741     if (ShAmt) {
01742       V = CreateLShr(V, ShAmt, Name + ".shift");
01743     }
01744     assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
01745            "Cannot extract to a larger integer!");
01746     if (ExtractedTy != IntTy) {
01747       V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
01748     }
01749     return V;
01750   }
01751 
01752   /// \brief Create an assume intrinsic call that represents an alignment
01753   /// assumption on the provided pointer.
01754   ///
01755   /// An optional offset can be provided, and if it is provided, the offset
01756   /// must be subtracted from the provided pointer to get the pointer with the
01757   /// specified alignment.
01758   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
01759                                       unsigned Alignment,
01760                                       Value *OffsetValue = nullptr) {
01761     assert(isa<PointerType>(PtrValue->getType()) &&
01762            "trying to create an alignment assumption on a non-pointer?");
01763 
01764     PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
01765     Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
01766     Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
01767 
01768     Value *Mask = ConstantInt::get(IntPtrTy,
01769       Alignment > 0 ? Alignment - 1 : 0);
01770     if (OffsetValue) {
01771       bool IsOffsetZero = false;
01772       if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
01773         IsOffsetZero = CI->isZero();
01774 
01775       if (!IsOffsetZero) {
01776         if (OffsetValue->getType() != IntPtrTy)
01777           OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
01778                                       "offsetcast");
01779         PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
01780       }
01781     }
01782 
01783     Value *Zero = ConstantInt::get(IntPtrTy, 0);
01784     Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
01785     Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
01786 
01787     return CreateAssumption(InvCond);
01788   }
01789 };
01790 
01791 // Create wrappers for C Binding types (see CBindingWrapping.h).
01792 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
01793 
01794 } // end namespace llvm
01795 
01796 #endif // LLVM_IR_IRBUILDER_H