LLVM API Documentation

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