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