1 //===---- llvm/IRBuilder.h - Builder for LLVM Instructions ------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the IRBuilder class, which is used as a convenient way 11 // to create LLVM instructions with a consistent and simplified interface. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_IR_IRBUILDER_H 16 #define LLVM_IR_IRBUILDER_H 17 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/None.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/ADT/Twine.h" 22 #include "llvm/IR/BasicBlock.h" 23 #include "llvm/IR/Constant.h" 24 #include "llvm/IR/ConstantFolder.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/DebugLoc.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/GlobalVariable.h" 31 #include "llvm/IR/InstrTypes.h" 32 #include "llvm/IR/Instruction.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/IR/LLVMContext.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/Operator.h" 38 #include "llvm/IR/Type.h" 39 #include "llvm/IR/Value.h" 40 #include "llvm/IR/ValueHandle.h" 41 #include "llvm/Support/AtomicOrdering.h" 42 #include "llvm/Support/CBindingWrapping.h" 43 #include "llvm/Support/Casting.h" 44 #include "llvm-c/Types.h" 45 #include <cassert> 46 #include <cstddef> 47 #include <cstdint> 48 #include <algorithm> 49 #include <functional> 50 51 namespace llvm { 52 53 class APInt; 54 class MDNode; 55 class Module; 56 class Use; 57 58 /// \brief This provides the default implementation of the IRBuilder 59 /// 'InsertHelper' method that is called whenever an instruction is created by 60 /// IRBuilder and needs to be inserted. 61 /// 62 /// By default, this inserts the instruction at the insertion point. 63 class IRBuilderDefaultInserter { 64 protected: 65 void InsertHelper(Instruction *I, const Twine &Name, 66 BasicBlock *BB, BasicBlock::iterator InsertPt) const { 67 if (BB) BB->getInstList().insert(InsertPt, I); 68 I->setName(Name); 69 } 70 }; 71 72 /// Provides an 'InsertHelper' that calls a user-provided callback after 73 /// performing the default insertion. 74 class IRBuilderCallbackInserter : IRBuilderDefaultInserter { 75 std::function<void(Instruction *)> Callback; 76 77 public: 78 IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback) 79 : Callback(std::move(Callback)) {} 80 81 protected: 82 void InsertHelper(Instruction *I, const Twine &Name, 83 BasicBlock *BB, BasicBlock::iterator InsertPt) const { 84 IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt); 85 Callback(I); 86 } 87 }; 88 89 /// \brief Common base class shared among various IRBuilders. 90 class IRBuilderBase { 91 DebugLoc CurDbgLocation; 92 93 protected: 94 BasicBlock *BB; 95 BasicBlock::iterator InsertPt; 96 LLVMContext &Context; 97 98 MDNode *DefaultFPMathTag; 99 FastMathFlags FMF; 100 101 ArrayRef<OperandBundleDef> DefaultOperandBundles; 102 103 public: 104 IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr, 105 ArrayRef<OperandBundleDef> OpBundles = None) 106 : Context(context), DefaultFPMathTag(FPMathTag), 107 DefaultOperandBundles(OpBundles) { 108 ClearInsertionPoint(); 109 } 110 111 //===--------------------------------------------------------------------===// 112 // Builder configuration methods 113 //===--------------------------------------------------------------------===// 114 115 /// \brief Clear the insertion point: created instructions will not be 116 /// inserted into a block. 117 void ClearInsertionPoint() { 118 BB = nullptr; 119 InsertPt = BasicBlock::iterator(); 120 } 121 122 BasicBlock *GetInsertBlock() const { return BB; } 123 BasicBlock::iterator GetInsertPoint() const { return InsertPt; } 124 LLVMContext &getContext() const { return Context; } 125 126 /// \brief This specifies that created instructions should be appended to the 127 /// end of the specified block. 128 void SetInsertPoint(BasicBlock *TheBB) { 129 BB = TheBB; 130 InsertPt = BB->end(); 131 } 132 133 /// \brief This specifies that created instructions should be inserted before 134 /// the specified instruction. 135 void SetInsertPoint(Instruction *I) { 136 BB = I->getParent(); 137 InsertPt = I->getIterator(); 138 assert(InsertPt != BB->end() && "Can't read debug loc from end()"); 139 SetCurrentDebugLocation(I->getDebugLoc()); 140 } 141 142 /// \brief This specifies that created instructions should be inserted at the 143 /// specified point. 144 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) { 145 BB = TheBB; 146 InsertPt = IP; 147 if (IP != TheBB->end()) 148 SetCurrentDebugLocation(IP->getDebugLoc()); 149 } 150 151 /// \brief Set location information used by debugging information. 152 void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); } 153 154 /// \brief Get location information used by debugging information. 155 const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; } 156 157 /// \brief If this builder has a current debug location, set it on the 158 /// specified instruction. 159 void SetInstDebugLocation(Instruction *I) const { 160 if (CurDbgLocation) 161 I->setDebugLoc(CurDbgLocation); 162 } 163 164 /// \brief Get the return type of the current function that we're emitting 165 /// into. 166 Type *getCurrentFunctionReturnType() const; 167 168 /// InsertPoint - A saved insertion point. 169 class InsertPoint { 170 BasicBlock *Block = nullptr; 171 BasicBlock::iterator Point; 172 173 public: 174 /// \brief Creates a new insertion point which doesn't point to anything. 175 InsertPoint() = default; 176 177 /// \brief Creates a new insertion point at the given location. 178 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint) 179 : Block(InsertBlock), Point(InsertPoint) {} 180 181 /// \brief Returns true if this insert point is set. 182 bool isSet() const { return (Block != nullptr); } 183 184 BasicBlock *getBlock() const { return Block; } 185 BasicBlock::iterator getPoint() const { return Point; } 186 }; 187 188 /// \brief Returns the current insert point. 189 InsertPoint saveIP() const { 190 return InsertPoint(GetInsertBlock(), GetInsertPoint()); 191 } 192 193 /// \brief Returns the current insert point, clearing it in the process. 194 InsertPoint saveAndClearIP() { 195 InsertPoint IP(GetInsertBlock(), GetInsertPoint()); 196 ClearInsertionPoint(); 197 return IP; 198 } 199 200 /// \brief Sets the current insert point to a previously-saved location. 201 void restoreIP(InsertPoint IP) { 202 if (IP.isSet()) 203 SetInsertPoint(IP.getBlock(), IP.getPoint()); 204 else 205 ClearInsertionPoint(); 206 } 207 208 /// \brief Get the floating point math metadata being used. 209 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; } 210 211 /// \brief Get the flags to be applied to created floating point ops 212 FastMathFlags getFastMathFlags() const { return FMF; } 213 214 /// \brief Clear the fast-math flags. 215 void clearFastMathFlags() { FMF.clear(); } 216 217 /// \brief Set the floating point math metadata to be used. 218 void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; } 219 220 /// \brief Set the fast-math flags to be used with generated fp-math operators 221 void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; } 222 223 //===--------------------------------------------------------------------===// 224 // RAII helpers. 225 //===--------------------------------------------------------------------===// 226 227 // \brief RAII object that stores the current insertion point and restores it 228 // when the object is destroyed. This includes the debug location. 229 class InsertPointGuard { 230 IRBuilderBase &Builder; 231 AssertingVH<BasicBlock> Block; 232 BasicBlock::iterator Point; 233 DebugLoc DbgLoc; 234 235 public: 236 InsertPointGuard(IRBuilderBase &B) 237 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()), 238 DbgLoc(B.getCurrentDebugLocation()) {} 239 240 InsertPointGuard(const InsertPointGuard &) = delete; 241 InsertPointGuard &operator=(const InsertPointGuard &) = delete; 242 243 ~InsertPointGuard() { 244 Builder.restoreIP(InsertPoint(Block, Point)); 245 Builder.SetCurrentDebugLocation(DbgLoc); 246 } 247 }; 248 249 // \brief RAII object that stores the current fast math settings and restores 250 // them when the object is destroyed. 251 class FastMathFlagGuard { 252 IRBuilderBase &Builder; 253 FastMathFlags FMF; 254 MDNode *FPMathTag; 255 256 public: 257 FastMathFlagGuard(IRBuilderBase &B) 258 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {} 259 260 FastMathFlagGuard(const FastMathFlagGuard &) = delete; 261 FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete; 262 263 ~FastMathFlagGuard() { 264 Builder.FMF = FMF; 265 Builder.DefaultFPMathTag = FPMathTag; 266 } 267 }; 268 269 //===--------------------------------------------------------------------===// 270 // Miscellaneous creation methods. 271 //===--------------------------------------------------------------------===// 272 273 /// \brief Make a new global variable with initializer type i8* 274 /// 275 /// Make a new global variable with an initializer that has array of i8 type 276 /// filled in with the null terminated string value specified. The new global 277 /// variable will be marked mergable with any others of the same contents. If 278 /// Name is specified, it is the name of the global variable created. 279 GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "", 280 unsigned AddressSpace = 0); 281 282 /// \brief Get a constant value representing either true or false. 283 ConstantInt *getInt1(bool V) { 284 return ConstantInt::get(getInt1Ty(), V); 285 } 286 287 /// \brief Get the constant value for i1 true. 288 ConstantInt *getTrue() { 289 return ConstantInt::getTrue(Context); 290 } 291 292 /// \brief Get the constant value for i1 false. 293 ConstantInt *getFalse() { 294 return ConstantInt::getFalse(Context); 295 } 296 297 /// \brief Get a constant 8-bit value. 298 ConstantInt *getInt8(uint8_t C) { 299 return ConstantInt::get(getInt8Ty(), C); 300 } 301 302 /// \brief Get a constant 16-bit value. 303 ConstantInt *getInt16(uint16_t C) { 304 return ConstantInt::get(getInt16Ty(), C); 305 } 306 307 /// \brief Get a constant 32-bit value. 308 ConstantInt *getInt32(uint32_t C) { 309 return ConstantInt::get(getInt32Ty(), C); 310 } 311 312 /// \brief Get a constant 64-bit value. 313 ConstantInt *getInt64(uint64_t C) { 314 return ConstantInt::get(getInt64Ty(), C); 315 } 316 317 /// \brief Get a constant N-bit value, zero extended or truncated from 318 /// a 64-bit value. 319 ConstantInt *getIntN(unsigned N, uint64_t C) { 320 return ConstantInt::get(getIntNTy(N), C); 321 } 322 323 /// \brief Get a constant integer value. 324 ConstantInt *getInt(const APInt &AI) { 325 return ConstantInt::get(Context, AI); 326 } 327 328 //===--------------------------------------------------------------------===// 329 // Type creation methods 330 //===--------------------------------------------------------------------===// 331 332 /// \brief Fetch the type representing a single bit 333 IntegerType *getInt1Ty() { 334 return Type::getInt1Ty(Context); 335 } 336 337 /// \brief Fetch the type representing an 8-bit integer. 338 IntegerType *getInt8Ty() { 339 return Type::getInt8Ty(Context); 340 } 341 342 /// \brief Fetch the type representing a 16-bit integer. 343 IntegerType *getInt16Ty() { 344 return Type::getInt16Ty(Context); 345 } 346 347 /// \brief Fetch the type representing a 32-bit integer. 348 IntegerType *getInt32Ty() { 349 return Type::getInt32Ty(Context); 350 } 351 352 /// \brief Fetch the type representing a 64-bit integer. 353 IntegerType *getInt64Ty() { 354 return Type::getInt64Ty(Context); 355 } 356 357 /// \brief Fetch the type representing a 128-bit integer. 358 IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); } 359 360 /// \brief Fetch the type representing an N-bit integer. 361 IntegerType *getIntNTy(unsigned N) { 362 return Type::getIntNTy(Context, N); 363 } 364 365 /// \brief Fetch the type representing a 16-bit floating point value. 366 Type *getHalfTy() { 367 return Type::getHalfTy(Context); 368 } 369 370 /// \brief Fetch the type representing a 32-bit floating point value. 371 Type *getFloatTy() { 372 return Type::getFloatTy(Context); 373 } 374 375 /// \brief Fetch the type representing a 64-bit floating point value. 376 Type *getDoubleTy() { 377 return Type::getDoubleTy(Context); 378 } 379 380 /// \brief Fetch the type representing void. 381 Type *getVoidTy() { 382 return Type::getVoidTy(Context); 383 } 384 385 /// \brief Fetch the type representing a pointer to an 8-bit integer value. 386 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) { 387 return Type::getInt8PtrTy(Context, AddrSpace); 388 } 389 390 /// \brief Fetch the type representing a pointer to an integer value. 391 IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) { 392 return DL.getIntPtrType(Context, AddrSpace); 393 } 394 395 //===--------------------------------------------------------------------===// 396 // Intrinsic creation methods 397 //===--------------------------------------------------------------------===// 398 399 /// \brief Create and insert a memset to the specified pointer and the 400 /// specified value. 401 /// 402 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is 403 /// specified, it will be added to the instruction. Likewise with alias.scope 404 /// and noalias tags. 405 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align, 406 bool isVolatile = false, MDNode *TBAATag = nullptr, 407 MDNode *ScopeTag = nullptr, 408 MDNode *NoAliasTag = nullptr) { 409 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile, 410 TBAATag, ScopeTag, NoAliasTag); 411 } 412 413 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align, 414 bool isVolatile = false, MDNode *TBAATag = nullptr, 415 MDNode *ScopeTag = nullptr, 416 MDNode *NoAliasTag = nullptr); 417 418 /// \brief Create and insert a memcpy between the specified pointers. 419 /// 420 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is 421 /// specified, it will be added to the instruction. Likewise with alias.scope 422 /// and noalias tags. 423 CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align, 424 bool isVolatile = false, MDNode *TBAATag = nullptr, 425 MDNode *TBAAStructTag = nullptr, 426 MDNode *ScopeTag = nullptr, 427 MDNode *NoAliasTag = nullptr) { 428 return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag, 429 TBAAStructTag, ScopeTag, NoAliasTag); 430 } 431 432 CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align, 433 bool isVolatile = false, MDNode *TBAATag = nullptr, 434 MDNode *TBAAStructTag = nullptr, 435 MDNode *ScopeTag = nullptr, 436 MDNode *NoAliasTag = nullptr); 437 438 /// \brief Create and insert a memmove between the specified 439 /// pointers. 440 /// 441 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is 442 /// specified, it will be added to the instruction. Likewise with alias.scope 443 /// and noalias tags. 444 CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align, 445 bool isVolatile = false, MDNode *TBAATag = nullptr, 446 MDNode *ScopeTag = nullptr, 447 MDNode *NoAliasTag = nullptr) { 448 return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile, 449 TBAATag, ScopeTag, NoAliasTag); 450 } 451 452 CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align, 453 bool isVolatile = false, MDNode *TBAATag = nullptr, 454 MDNode *ScopeTag = nullptr, 455 MDNode *NoAliasTag = nullptr); 456 457 /// \brief Create a lifetime.start intrinsic. 458 /// 459 /// If the pointer isn't i8* it will be converted. 460 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr); 461 462 /// \brief Create a lifetime.end intrinsic. 463 /// 464 /// If the pointer isn't i8* it will be converted. 465 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr); 466 467 /// Create a call to invariant.start intrinsic. 468 /// 469 /// If the pointer isn't i8* it will be converted. 470 CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr); 471 472 /// \brief Create a call to Masked Load intrinsic 473 CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask, 474 Value *PassThru = nullptr, const Twine &Name = ""); 475 476 /// \brief Create a call to Masked Store intrinsic 477 CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align, 478 Value *Mask); 479 480 /// \brief Create a call to Masked Gather intrinsic 481 CallInst *CreateMaskedGather(Value *Ptrs, unsigned Align, 482 Value *Mask = nullptr, 483 Value *PassThru = nullptr, 484 const Twine& Name = ""); 485 486 /// \brief Create a call to Masked Scatter intrinsic 487 CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned Align, 488 Value *Mask = nullptr); 489 490 /// \brief Create an assume intrinsic call that allows the optimizer to 491 /// assume that the provided condition will be true. 492 CallInst *CreateAssumption(Value *Cond); 493 494 /// \brief Create a call to the experimental.gc.statepoint intrinsic to 495 /// start a new statepoint sequence. 496 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes, 497 Value *ActualCallee, 498 ArrayRef<Value *> CallArgs, 499 ArrayRef<Value *> DeoptArgs, 500 ArrayRef<Value *> GCArgs, 501 const Twine &Name = ""); 502 503 /// \brief Create a call to the experimental.gc.statepoint intrinsic to 504 /// start a new statepoint sequence. 505 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes, 506 Value *ActualCallee, uint32_t Flags, 507 ArrayRef<Use> CallArgs, 508 ArrayRef<Use> TransitionArgs, 509 ArrayRef<Use> DeoptArgs, 510 ArrayRef<Value *> GCArgs, 511 const Twine &Name = ""); 512 513 // \brief Conveninence function for the common case when CallArgs are filled 514 // in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be 515 // .get()'ed to get the Value pointer. 516 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes, 517 Value *ActualCallee, ArrayRef<Use> CallArgs, 518 ArrayRef<Value *> DeoptArgs, 519 ArrayRef<Value *> GCArgs, 520 const Twine &Name = ""); 521 522 /// brief Create an invoke to the experimental.gc.statepoint intrinsic to 523 /// start a new statepoint sequence. 524 InvokeInst * 525 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes, 526 Value *ActualInvokee, BasicBlock *NormalDest, 527 BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs, 528 ArrayRef<Value *> DeoptArgs, 529 ArrayRef<Value *> GCArgs, const Twine &Name = ""); 530 531 /// brief Create an invoke to the experimental.gc.statepoint intrinsic to 532 /// start a new statepoint sequence. 533 InvokeInst *CreateGCStatepointInvoke( 534 uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee, 535 BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags, 536 ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs, 537 ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs, 538 const Twine &Name = ""); 539 540 // Conveninence function for the common case when CallArgs are filled in using 541 // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to 542 // get the Value *. 543 InvokeInst * 544 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes, 545 Value *ActualInvokee, BasicBlock *NormalDest, 546 BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs, 547 ArrayRef<Value *> DeoptArgs, 548 ArrayRef<Value *> GCArgs, const Twine &Name = ""); 549 550 /// \brief Create a call to the experimental.gc.result intrinsic to extract 551 /// the result from a call wrapped in a statepoint. 552 CallInst *CreateGCResult(Instruction *Statepoint, 553 Type *ResultType, 554 const Twine &Name = ""); 555 556 /// \brief Create a call to the experimental.gc.relocate intrinsics to 557 /// project the relocated value of one pointer from the statepoint. 558 CallInst *CreateGCRelocate(Instruction *Statepoint, 559 int BaseOffset, 560 int DerivedOffset, 561 Type *ResultType, 562 const Twine &Name = ""); 563 564 /// Create a call to intrinsic \p ID with 2 operands which is mangled on the 565 /// first type. 566 CallInst *CreateBinaryIntrinsic(Intrinsic::ID ID, 567 Value *LHS, Value *RHS, 568 const Twine &Name = ""); 569 570 /// Create call to the minnum intrinsic. 571 CallInst *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") { 572 return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, Name); 573 } 574 575 /// Create call to the maxnum intrinsic. 576 CallInst *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") { 577 return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, Name); 578 } 579 580 private: 581 /// \brief Create a call to a masked intrinsic with given Id. 582 CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops, 583 ArrayRef<Type *> OverloadedTypes, 584 const Twine &Name = ""); 585 586 Value *getCastedInt8PtrValue(Value *Ptr); 587 }; 588 589 /// \brief This provides a uniform API for creating instructions and inserting 590 /// them into a basic block: either at the end of a BasicBlock, or at a specific 591 /// iterator location in a block. 592 /// 593 /// Note that the builder does not expose the full generality of LLVM 594 /// instructions. For access to extra instruction properties, use the mutators 595 /// (e.g. setVolatile) on the instructions after they have been 596 /// created. Convenience state exists to specify fast-math flags and fp-math 597 /// tags. 598 /// 599 /// The first template argument specifies a class to use for creating constants. 600 /// This defaults to creating minimally folded constants. The second template 601 /// argument allows clients to specify custom insertion hooks that are called on 602 /// every newly created insertion. 603 template <typename T = ConstantFolder, 604 typename Inserter = IRBuilderDefaultInserter> 605 class IRBuilder : public IRBuilderBase, public Inserter { 606 T Folder; 607 608 public: 609 IRBuilder(LLVMContext &C, const T &F, Inserter I = Inserter(), 610 MDNode *FPMathTag = nullptr, 611 ArrayRef<OperandBundleDef> OpBundles = None) 612 : IRBuilderBase(C, FPMathTag, OpBundles), Inserter(std::move(I)), 613 Folder(F) {} 614 615 explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr, 616 ArrayRef<OperandBundleDef> OpBundles = None) 617 : IRBuilderBase(C, FPMathTag, OpBundles), Folder() {} 618 619 explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr, 620 ArrayRef<OperandBundleDef> OpBundles = None) 621 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) { 622 SetInsertPoint(TheBB); 623 } 624 625 explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr, 626 ArrayRef<OperandBundleDef> OpBundles = None) 627 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder() { 628 SetInsertPoint(TheBB); 629 } 630 631 explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr, 632 ArrayRef<OperandBundleDef> OpBundles = None) 633 : IRBuilderBase(IP->getContext(), FPMathTag, OpBundles), Folder() { 634 SetInsertPoint(IP); 635 } 636 637 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T &F, 638 MDNode *FPMathTag = nullptr, 639 ArrayRef<OperandBundleDef> OpBundles = None) 640 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) { 641 SetInsertPoint(TheBB, IP); 642 } 643 644 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, 645 MDNode *FPMathTag = nullptr, 646 ArrayRef<OperandBundleDef> OpBundles = None) 647 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder() { 648 SetInsertPoint(TheBB, IP); 649 } 650 651 /// \brief Get the constant folder being used. 652 const T &getFolder() { return Folder; } 653 654 /// \brief Insert and return the specified instruction. 655 template<typename InstTy> 656 InstTy *Insert(InstTy *I, const Twine &Name = "") const { 657 this->InsertHelper(I, Name, BB, InsertPt); 658 this->SetInstDebugLocation(I); 659 return I; 660 } 661 662 /// \brief No-op overload to handle constants. 663 Constant *Insert(Constant *C, const Twine& = "") const { 664 return C; 665 } 666 667 //===--------------------------------------------------------------------===// 668 // Instruction creation methods: Terminators 669 //===--------------------------------------------------------------------===// 670 671 private: 672 /// \brief Helper to add branch weight and unpredictable metadata onto an 673 /// instruction. 674 /// \returns The annotated instruction. 675 template <typename InstTy> 676 InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) { 677 if (Weights) 678 I->setMetadata(LLVMContext::MD_prof, Weights); 679 if (Unpredictable) 680 I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable); 681 return I; 682 } 683 684 public: 685 /// \brief Create a 'ret void' instruction. 686 ReturnInst *CreateRetVoid() { 687 return Insert(ReturnInst::Create(Context)); 688 } 689 690 /// \brief Create a 'ret <val>' instruction. 691 ReturnInst *CreateRet(Value *V) { 692 return Insert(ReturnInst::Create(Context, V)); 693 } 694 695 /// \brief Create a sequence of N insertvalue instructions, 696 /// with one Value from the retVals array each, that build a aggregate 697 /// return value one value at a time, and a ret instruction to return 698 /// the resulting aggregate value. 699 /// 700 /// This is a convenience function for code that uses aggregate return values 701 /// as a vehicle for having multiple return values. 702 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) { 703 Value *V = UndefValue::get(getCurrentFunctionReturnType()); 704 for (unsigned i = 0; i != N; ++i) 705 V = CreateInsertValue(V, retVals[i], i, "mrv"); 706 return Insert(ReturnInst::Create(Context, V)); 707 } 708 709 /// \brief Create an unconditional 'br label X' instruction. 710 BranchInst *CreateBr(BasicBlock *Dest) { 711 return Insert(BranchInst::Create(Dest)); 712 } 713 714 /// \brief Create a conditional 'br Cond, TrueDest, FalseDest' 715 /// instruction. 716 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, 717 MDNode *BranchWeights = nullptr, 718 MDNode *Unpredictable = nullptr) { 719 return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond), 720 BranchWeights, Unpredictable)); 721 } 722 723 /// \brief Create a conditional 'br Cond, TrueDest, FalseDest' 724 /// instruction. Copy branch meta data if available. 725 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, 726 Instruction *MDSrc) { 727 BranchInst *Br = BranchInst::Create(True, False, Cond); 728 if (MDSrc) { 729 unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable, 730 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg}; 731 Br->copyMetadata(*MDSrc, makeArrayRef(&WL[0], 4)); 732 } 733 return Insert(Br); 734 } 735 736 /// \brief Create a switch instruction with the specified value, default dest, 737 /// and with a hint for the number of cases that will be added (for efficient 738 /// allocation). 739 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10, 740 MDNode *BranchWeights = nullptr, 741 MDNode *Unpredictable = nullptr) { 742 return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases), 743 BranchWeights, Unpredictable)); 744 } 745 746 /// \brief Create an indirect branch instruction with the specified address 747 /// operand, with an optional hint for the number of destinations that will be 748 /// added (for efficient allocation). 749 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) { 750 return Insert(IndirectBrInst::Create(Addr, NumDests)); 751 } 752 753 /// \brief Create an invoke instruction. 754 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest, 755 BasicBlock *UnwindDest, 756 ArrayRef<Value *> Args = None, 757 const Twine &Name = "") { 758 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args), 759 Name); 760 } 761 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest, 762 BasicBlock *UnwindDest, ArrayRef<Value *> Args, 763 ArrayRef<OperandBundleDef> OpBundles, 764 const Twine &Name = "") { 765 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args, 766 OpBundles), Name); 767 } 768 769 ResumeInst *CreateResume(Value *Exn) { 770 return Insert(ResumeInst::Create(Exn)); 771 } 772 773 CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad, 774 BasicBlock *UnwindBB = nullptr) { 775 return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB)); 776 } 777 778 CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB, 779 unsigned NumHandlers, 780 const Twine &Name = "") { 781 return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers), 782 Name); 783 } 784 785 CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args, 786 const Twine &Name = "") { 787 return Insert(CatchPadInst::Create(ParentPad, Args), Name); 788 } 789 790 CleanupPadInst *CreateCleanupPad(Value *ParentPad, 791 ArrayRef<Value *> Args = None, 792 const Twine &Name = "") { 793 return Insert(CleanupPadInst::Create(ParentPad, Args), Name); 794 } 795 796 CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) { 797 return Insert(CatchReturnInst::Create(CatchPad, BB)); 798 } 799 800 UnreachableInst *CreateUnreachable() { 801 return Insert(new UnreachableInst(Context)); 802 } 803 804 //===--------------------------------------------------------------------===// 805 // Instruction creation methods: Binary Operators 806 //===--------------------------------------------------------------------===// 807 private: 808 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc, 809 Value *LHS, Value *RHS, 810 const Twine &Name, 811 bool HasNUW, bool HasNSW) { 812 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name); 813 if (HasNUW) BO->setHasNoUnsignedWrap(); 814 if (HasNSW) BO->setHasNoSignedWrap(); 815 return BO; 816 } 817 818 Instruction *AddFPMathAttributes(Instruction *I, 819 MDNode *FPMathTag, 820 FastMathFlags FMF) const { 821 if (!FPMathTag) 822 FPMathTag = DefaultFPMathTag; 823 if (FPMathTag) 824 I->setMetadata(LLVMContext::MD_fpmath, FPMathTag); 825 I->setFastMathFlags(FMF); 826 return I; 827 } 828 829 public: 830 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "", 831 bool HasNUW = false, bool HasNSW = false) { 832 if (Constant *LC = dyn_cast<Constant>(LHS)) 833 if (Constant *RC = dyn_cast<Constant>(RHS)) 834 return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name); 835 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name, 836 HasNUW, HasNSW); 837 } 838 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") { 839 return CreateAdd(LHS, RHS, Name, false, true); 840 } 841 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") { 842 return CreateAdd(LHS, RHS, Name, true, false); 843 } 844 Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "", 845 MDNode *FPMathTag = nullptr) { 846 if (Constant *LC = dyn_cast<Constant>(LHS)) 847 if (Constant *RC = dyn_cast<Constant>(RHS)) 848 return Insert(Folder.CreateFAdd(LC, RC), Name); 849 return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS), 850 FPMathTag, FMF), Name); 851 } 852 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "", 853 bool HasNUW = false, bool HasNSW = false) { 854 if (Constant *LC = dyn_cast<Constant>(LHS)) 855 if (Constant *RC = dyn_cast<Constant>(RHS)) 856 return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name); 857 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name, 858 HasNUW, HasNSW); 859 } 860 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") { 861 return CreateSub(LHS, RHS, Name, false, true); 862 } 863 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") { 864 return CreateSub(LHS, RHS, Name, true, false); 865 } 866 Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "", 867 MDNode *FPMathTag = nullptr) { 868 if (Constant *LC = dyn_cast<Constant>(LHS)) 869 if (Constant *RC = dyn_cast<Constant>(RHS)) 870 return Insert(Folder.CreateFSub(LC, RC), Name); 871 return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS), 872 FPMathTag, FMF), Name); 873 } 874 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "", 875 bool HasNUW = false, bool HasNSW = false) { 876 if (Constant *LC = dyn_cast<Constant>(LHS)) 877 if (Constant *RC = dyn_cast<Constant>(RHS)) 878 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name); 879 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name, 880 HasNUW, HasNSW); 881 } 882 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") { 883 return CreateMul(LHS, RHS, Name, false, true); 884 } 885 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") { 886 return CreateMul(LHS, RHS, Name, true, false); 887 } 888 Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "", 889 MDNode *FPMathTag = nullptr) { 890 if (Constant *LC = dyn_cast<Constant>(LHS)) 891 if (Constant *RC = dyn_cast<Constant>(RHS)) 892 return Insert(Folder.CreateFMul(LC, RC), Name); 893 return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS), 894 FPMathTag, FMF), Name); 895 } 896 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "", 897 bool isExact = false) { 898 if (Constant *LC = dyn_cast<Constant>(LHS)) 899 if (Constant *RC = dyn_cast<Constant>(RHS)) 900 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name); 901 if (!isExact) 902 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name); 903 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name); 904 } 905 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") { 906 return CreateUDiv(LHS, RHS, Name, true); 907 } 908 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "", 909 bool isExact = false) { 910 if (Constant *LC = dyn_cast<Constant>(LHS)) 911 if (Constant *RC = dyn_cast<Constant>(RHS)) 912 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name); 913 if (!isExact) 914 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name); 915 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name); 916 } 917 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") { 918 return CreateSDiv(LHS, RHS, Name, true); 919 } 920 Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "", 921 MDNode *FPMathTag = nullptr) { 922 if (Constant *LC = dyn_cast<Constant>(LHS)) 923 if (Constant *RC = dyn_cast<Constant>(RHS)) 924 return Insert(Folder.CreateFDiv(LC, RC), Name); 925 return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS), 926 FPMathTag, FMF), Name); 927 } 928 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") { 929 if (Constant *LC = dyn_cast<Constant>(LHS)) 930 if (Constant *RC = dyn_cast<Constant>(RHS)) 931 return Insert(Folder.CreateURem(LC, RC), Name); 932 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name); 933 } 934 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") { 935 if (Constant *LC = dyn_cast<Constant>(LHS)) 936 if (Constant *RC = dyn_cast<Constant>(RHS)) 937 return Insert(Folder.CreateSRem(LC, RC), Name); 938 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name); 939 } 940 Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "", 941 MDNode *FPMathTag = nullptr) { 942 if (Constant *LC = dyn_cast<Constant>(LHS)) 943 if (Constant *RC = dyn_cast<Constant>(RHS)) 944 return Insert(Folder.CreateFRem(LC, RC), Name); 945 return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS), 946 FPMathTag, FMF), Name); 947 } 948 949 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "", 950 bool HasNUW = false, bool HasNSW = false) { 951 if (Constant *LC = dyn_cast<Constant>(LHS)) 952 if (Constant *RC = dyn_cast<Constant>(RHS)) 953 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name); 954 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name, 955 HasNUW, HasNSW); 956 } 957 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "", 958 bool HasNUW = false, bool HasNSW = false) { 959 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name, 960 HasNUW, HasNSW); 961 } 962 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "", 963 bool HasNUW = false, bool HasNSW = false) { 964 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name, 965 HasNUW, HasNSW); 966 } 967 968 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "", 969 bool isExact = false) { 970 if (Constant *LC = dyn_cast<Constant>(LHS)) 971 if (Constant *RC = dyn_cast<Constant>(RHS)) 972 return Insert(Folder.CreateLShr(LC, RC, isExact), Name); 973 if (!isExact) 974 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name); 975 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name); 976 } 977 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "", 978 bool isExact = false) { 979 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact); 980 } 981 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "", 982 bool isExact = false) { 983 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact); 984 } 985 986 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "", 987 bool isExact = false) { 988 if (Constant *LC = dyn_cast<Constant>(LHS)) 989 if (Constant *RC = dyn_cast<Constant>(RHS)) 990 return Insert(Folder.CreateAShr(LC, RC, isExact), Name); 991 if (!isExact) 992 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name); 993 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name); 994 } 995 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "", 996 bool isExact = false) { 997 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact); 998 } 999 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "", 1000 bool isExact = false) { 1001 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact); 1002 } 1003 1004 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") { 1005 if (Constant *RC = dyn_cast<Constant>(RHS)) { 1006 if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue()) 1007 return LHS; // LHS & -1 -> LHS 1008 if (Constant *LC = dyn_cast<Constant>(LHS)) 1009 return Insert(Folder.CreateAnd(LC, RC), Name); 1010 } 1011 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name); 1012 } 1013 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") { 1014 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1015 } 1016 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") { 1017 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1018 } 1019 1020 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") { 1021 if (Constant *RC = dyn_cast<Constant>(RHS)) { 1022 if (RC->isNullValue()) 1023 return LHS; // LHS | 0 -> LHS 1024 if (Constant *LC = dyn_cast<Constant>(LHS)) 1025 return Insert(Folder.CreateOr(LC, RC), Name); 1026 } 1027 return Insert(BinaryOperator::CreateOr(LHS, RHS), Name); 1028 } 1029 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") { 1030 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1031 } 1032 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") { 1033 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1034 } 1035 1036 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") { 1037 if (Constant *LC = dyn_cast<Constant>(LHS)) 1038 if (Constant *RC = dyn_cast<Constant>(RHS)) 1039 return Insert(Folder.CreateXor(LC, RC), Name); 1040 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name); 1041 } 1042 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") { 1043 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1044 } 1045 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") { 1046 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1047 } 1048 1049 Value *CreateBinOp(Instruction::BinaryOps Opc, 1050 Value *LHS, Value *RHS, const Twine &Name = "", 1051 MDNode *FPMathTag = nullptr) { 1052 if (Constant *LC = dyn_cast<Constant>(LHS)) 1053 if (Constant *RC = dyn_cast<Constant>(RHS)) 1054 return Insert(Folder.CreateBinOp(Opc, LC, RC), Name); 1055 Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS); 1056 if (isa<FPMathOperator>(BinOp)) 1057 BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF); 1058 return Insert(BinOp, Name); 1059 } 1060 1061 Value *CreateNeg(Value *V, const Twine &Name = "", 1062 bool HasNUW = false, bool HasNSW = false) { 1063 if (Constant *VC = dyn_cast<Constant>(V)) 1064 return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name); 1065 BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name); 1066 if (HasNUW) BO->setHasNoUnsignedWrap(); 1067 if (HasNSW) BO->setHasNoSignedWrap(); 1068 return BO; 1069 } 1070 Value *CreateNSWNeg(Value *V, const Twine &Name = "") { 1071 return CreateNeg(V, Name, false, true); 1072 } 1073 Value *CreateNUWNeg(Value *V, const Twine &Name = "") { 1074 return CreateNeg(V, Name, true, false); 1075 } 1076 Value *CreateFNeg(Value *V, const Twine &Name = "", 1077 MDNode *FPMathTag = nullptr) { 1078 if (Constant *VC = dyn_cast<Constant>(V)) 1079 return Insert(Folder.CreateFNeg(VC), Name); 1080 return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V), 1081 FPMathTag, FMF), Name); 1082 } 1083 Value *CreateNot(Value *V, const Twine &Name = "") { 1084 if (Constant *VC = dyn_cast<Constant>(V)) 1085 return Insert(Folder.CreateNot(VC), Name); 1086 return Insert(BinaryOperator::CreateNot(V), Name); 1087 } 1088 1089 //===--------------------------------------------------------------------===// 1090 // Instruction creation methods: Memory Instructions 1091 //===--------------------------------------------------------------------===// 1092 1093 AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace, 1094 Value *ArraySize = nullptr, const Twine &Name = "") { 1095 return Insert(new AllocaInst(Ty, AddrSpace, ArraySize), Name); 1096 } 1097 1098 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr, 1099 const Twine &Name = "") { 1100 const DataLayout &DL = BB->getParent()->getParent()->getDataLayout(); 1101 return Insert(new AllocaInst(Ty, DL.getAllocaAddrSpace(), ArraySize), Name); 1102 } 1103 // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of 1104 // converting the string to 'bool' for the isVolatile parameter. 1105 LoadInst *CreateLoad(Value *Ptr, const char *Name) { 1106 return Insert(new LoadInst(Ptr), Name); 1107 } 1108 LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") { 1109 return Insert(new LoadInst(Ptr), Name); 1110 } 1111 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") { 1112 return Insert(new LoadInst(Ty, Ptr), Name); 1113 } 1114 LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") { 1115 return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name); 1116 } 1117 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) { 1118 return Insert(new StoreInst(Val, Ptr, isVolatile)); 1119 } 1120 // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' 1121 // correctly, instead of converting the string to 'bool' for the isVolatile 1122 // parameter. 1123 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) { 1124 LoadInst *LI = CreateLoad(Ptr, Name); 1125 LI->setAlignment(Align); 1126 return LI; 1127 } 1128 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, 1129 const Twine &Name = "") { 1130 LoadInst *LI = CreateLoad(Ptr, Name); 1131 LI->setAlignment(Align); 1132 return LI; 1133 } 1134 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile, 1135 const Twine &Name = "") { 1136 LoadInst *LI = CreateLoad(Ptr, isVolatile, Name); 1137 LI->setAlignment(Align); 1138 return LI; 1139 } 1140 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align, 1141 bool isVolatile = false) { 1142 StoreInst *SI = CreateStore(Val, Ptr, isVolatile); 1143 SI->setAlignment(Align); 1144 return SI; 1145 } 1146 FenceInst *CreateFence(AtomicOrdering Ordering, 1147 SynchronizationScope SynchScope = CrossThread, 1148 const Twine &Name = "") { 1149 return Insert(new FenceInst(Context, Ordering, SynchScope), Name); 1150 } 1151 AtomicCmpXchgInst * 1152 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New, 1153 AtomicOrdering SuccessOrdering, 1154 AtomicOrdering FailureOrdering, 1155 SynchronizationScope SynchScope = CrossThread) { 1156 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, 1157 FailureOrdering, SynchScope)); 1158 } 1159 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val, 1160 AtomicOrdering Ordering, 1161 SynchronizationScope SynchScope = CrossThread) { 1162 return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope)); 1163 } 1164 Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList, 1165 const Twine &Name = "") { 1166 return CreateGEP(nullptr, Ptr, IdxList, Name); 1167 } 1168 Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList, 1169 const Twine &Name = "") { 1170 if (Constant *PC = dyn_cast<Constant>(Ptr)) { 1171 // Every index must be constant. 1172 size_t i, e; 1173 for (i = 0, e = IdxList.size(); i != e; ++i) 1174 if (!isa<Constant>(IdxList[i])) 1175 break; 1176 if (i == e) 1177 return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name); 1178 } 1179 return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name); 1180 } 1181 Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList, 1182 const Twine &Name = "") { 1183 return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name); 1184 } 1185 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList, 1186 const Twine &Name = "") { 1187 if (Constant *PC = dyn_cast<Constant>(Ptr)) { 1188 // Every index must be constant. 1189 size_t i, e; 1190 for (i = 0, e = IdxList.size(); i != e; ++i) 1191 if (!isa<Constant>(IdxList[i])) 1192 break; 1193 if (i == e) 1194 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList), 1195 Name); 1196 } 1197 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name); 1198 } 1199 Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") { 1200 return CreateGEP(nullptr, Ptr, Idx, Name); 1201 } 1202 Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") { 1203 if (Constant *PC = dyn_cast<Constant>(Ptr)) 1204 if (Constant *IC = dyn_cast<Constant>(Idx)) 1205 return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name); 1206 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name); 1207 } 1208 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx, 1209 const Twine &Name = "") { 1210 if (Constant *PC = dyn_cast<Constant>(Ptr)) 1211 if (Constant *IC = dyn_cast<Constant>(Idx)) 1212 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name); 1213 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name); 1214 } 1215 Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") { 1216 return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name); 1217 } 1218 Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, 1219 const Twine &Name = "") { 1220 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0); 1221 1222 if (Constant *PC = dyn_cast<Constant>(Ptr)) 1223 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name); 1224 1225 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name); 1226 } 1227 Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, 1228 const Twine &Name = "") { 1229 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0); 1230 1231 if (Constant *PC = dyn_cast<Constant>(Ptr)) 1232 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name); 1233 1234 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name); 1235 } 1236 Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, 1237 const Twine &Name = "") { 1238 Value *Idxs[] = { 1239 ConstantInt::get(Type::getInt32Ty(Context), Idx0), 1240 ConstantInt::get(Type::getInt32Ty(Context), Idx1) 1241 }; 1242 1243 if (Constant *PC = dyn_cast<Constant>(Ptr)) 1244 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name); 1245 1246 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name); 1247 } 1248 Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, 1249 unsigned Idx1, const Twine &Name = "") { 1250 Value *Idxs[] = { 1251 ConstantInt::get(Type::getInt32Ty(Context), Idx0), 1252 ConstantInt::get(Type::getInt32Ty(Context), Idx1) 1253 }; 1254 1255 if (Constant *PC = dyn_cast<Constant>(Ptr)) 1256 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name); 1257 1258 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name); 1259 } 1260 Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") { 1261 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0); 1262 1263 if (Constant *PC = dyn_cast<Constant>(Ptr)) 1264 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name); 1265 1266 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name); 1267 } 1268 Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0, 1269 const Twine &Name = "") { 1270 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0); 1271 1272 if (Constant *PC = dyn_cast<Constant>(Ptr)) 1273 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name); 1274 1275 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name); 1276 } 1277 Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1, 1278 const Twine &Name = "") { 1279 Value *Idxs[] = { 1280 ConstantInt::get(Type::getInt64Ty(Context), Idx0), 1281 ConstantInt::get(Type::getInt64Ty(Context), Idx1) 1282 }; 1283 1284 if (Constant *PC = dyn_cast<Constant>(Ptr)) 1285 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name); 1286 1287 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name); 1288 } 1289 Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1, 1290 const Twine &Name = "") { 1291 Value *Idxs[] = { 1292 ConstantInt::get(Type::getInt64Ty(Context), Idx0), 1293 ConstantInt::get(Type::getInt64Ty(Context), Idx1) 1294 }; 1295 1296 if (Constant *PC = dyn_cast<Constant>(Ptr)) 1297 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs), 1298 Name); 1299 1300 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name); 1301 } 1302 Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx, 1303 const Twine &Name = "") { 1304 return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name); 1305 } 1306 1307 /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type 1308 /// instead of a pointer to array of i8. 1309 Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "", 1310 unsigned AddressSpace = 0) { 1311 GlobalVariable *gv = CreateGlobalString(Str, Name, AddressSpace); 1312 Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0); 1313 Value *Args[] = { zero, zero }; 1314 return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name); 1315 } 1316 1317 //===--------------------------------------------------------------------===// 1318 // Instruction creation methods: Cast/Conversion Operators 1319 //===--------------------------------------------------------------------===// 1320 1321 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") { 1322 return CreateCast(Instruction::Trunc, V, DestTy, Name); 1323 } 1324 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") { 1325 return CreateCast(Instruction::ZExt, V, DestTy, Name); 1326 } 1327 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") { 1328 return CreateCast(Instruction::SExt, V, DestTy, Name); 1329 } 1330 /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return 1331 /// the value untouched if the type of V is already DestTy. 1332 Value *CreateZExtOrTrunc(Value *V, Type *DestTy, 1333 const Twine &Name = "") { 1334 assert(V->getType()->isIntOrIntVectorTy() && 1335 DestTy->isIntOrIntVectorTy() && 1336 "Can only zero extend/truncate integers!"); 1337 Type *VTy = V->getType(); 1338 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits()) 1339 return CreateZExt(V, DestTy, Name); 1340 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits()) 1341 return CreateTrunc(V, DestTy, Name); 1342 return V; 1343 } 1344 /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return 1345 /// the value untouched if the type of V is already DestTy. 1346 Value *CreateSExtOrTrunc(Value *V, Type *DestTy, 1347 const Twine &Name = "") { 1348 assert(V->getType()->isIntOrIntVectorTy() && 1349 DestTy->isIntOrIntVectorTy() && 1350 "Can only sign extend/truncate integers!"); 1351 Type *VTy = V->getType(); 1352 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits()) 1353 return CreateSExt(V, DestTy, Name); 1354 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits()) 1355 return CreateTrunc(V, DestTy, Name); 1356 return V; 1357 } 1358 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){ 1359 return CreateCast(Instruction::FPToUI, V, DestTy, Name); 1360 } 1361 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){ 1362 return CreateCast(Instruction::FPToSI, V, DestTy, Name); 1363 } 1364 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){ 1365 return CreateCast(Instruction::UIToFP, V, DestTy, Name); 1366 } 1367 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){ 1368 return CreateCast(Instruction::SIToFP, V, DestTy, Name); 1369 } 1370 Value *CreateFPTrunc(Value *V, Type *DestTy, 1371 const Twine &Name = "") { 1372 return CreateCast(Instruction::FPTrunc, V, DestTy, Name); 1373 } 1374 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") { 1375 return CreateCast(Instruction::FPExt, V, DestTy, Name); 1376 } 1377 Value *CreatePtrToInt(Value *V, Type *DestTy, 1378 const Twine &Name = "") { 1379 return CreateCast(Instruction::PtrToInt, V, DestTy, Name); 1380 } 1381 Value *CreateIntToPtr(Value *V, Type *DestTy, 1382 const Twine &Name = "") { 1383 return CreateCast(Instruction::IntToPtr, V, DestTy, Name); 1384 } 1385 Value *CreateBitCast(Value *V, Type *DestTy, 1386 const Twine &Name = "") { 1387 return CreateCast(Instruction::BitCast, V, DestTy, Name); 1388 } 1389 Value *CreateAddrSpaceCast(Value *V, Type *DestTy, 1390 const Twine &Name = "") { 1391 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name); 1392 } 1393 Value *CreateZExtOrBitCast(Value *V, Type *DestTy, 1394 const Twine &Name = "") { 1395 if (V->getType() == DestTy) 1396 return V; 1397 if (Constant *VC = dyn_cast<Constant>(V)) 1398 return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name); 1399 return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name); 1400 } 1401 Value *CreateSExtOrBitCast(Value *V, Type *DestTy, 1402 const Twine &Name = "") { 1403 if (V->getType() == DestTy) 1404 return V; 1405 if (Constant *VC = dyn_cast<Constant>(V)) 1406 return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name); 1407 return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name); 1408 } 1409 Value *CreateTruncOrBitCast(Value *V, Type *DestTy, 1410 const Twine &Name = "") { 1411 if (V->getType() == DestTy) 1412 return V; 1413 if (Constant *VC = dyn_cast<Constant>(V)) 1414 return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name); 1415 return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name); 1416 } 1417 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, 1418 const Twine &Name = "") { 1419 if (V->getType() == DestTy) 1420 return V; 1421 if (Constant *VC = dyn_cast<Constant>(V)) 1422 return Insert(Folder.CreateCast(Op, VC, DestTy), Name); 1423 return Insert(CastInst::Create(Op, V, DestTy), Name); 1424 } 1425 Value *CreatePointerCast(Value *V, Type *DestTy, 1426 const Twine &Name = "") { 1427 if (V->getType() == DestTy) 1428 return V; 1429 if (Constant *VC = dyn_cast<Constant>(V)) 1430 return Insert(Folder.CreatePointerCast(VC, DestTy), Name); 1431 return Insert(CastInst::CreatePointerCast(V, DestTy), Name); 1432 } 1433 1434 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, 1435 const Twine &Name = "") { 1436 if (V->getType() == DestTy) 1437 return V; 1438 1439 if (Constant *VC = dyn_cast<Constant>(V)) { 1440 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy), 1441 Name); 1442 } 1443 1444 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy), 1445 Name); 1446 } 1447 1448 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned, 1449 const Twine &Name = "") { 1450 if (V->getType() == DestTy) 1451 return V; 1452 if (Constant *VC = dyn_cast<Constant>(V)) 1453 return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name); 1454 return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name); 1455 } 1456 1457 Value *CreateBitOrPointerCast(Value *V, Type *DestTy, 1458 const Twine &Name = "") { 1459 if (V->getType() == DestTy) 1460 return V; 1461 if (V->getType()->getScalarType()->isPointerTy() && 1462 DestTy->getScalarType()->isIntegerTy()) 1463 return CreatePtrToInt(V, DestTy, Name); 1464 if (V->getType()->getScalarType()->isIntegerTy() && 1465 DestTy->getScalarType()->isPointerTy()) 1466 return CreateIntToPtr(V, DestTy, Name); 1467 1468 return CreateBitCast(V, DestTy, Name); 1469 } 1470 1471 public: 1472 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") { 1473 if (V->getType() == DestTy) 1474 return V; 1475 if (Constant *VC = dyn_cast<Constant>(V)) 1476 return Insert(Folder.CreateFPCast(VC, DestTy), Name); 1477 return Insert(CastInst::CreateFPCast(V, DestTy), Name); 1478 } 1479 1480 // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a 1481 // compile time error, instead of converting the string to bool for the 1482 // isSigned parameter. 1483 Value *CreateIntCast(Value *, Type *, const char *) = delete; 1484 1485 //===--------------------------------------------------------------------===// 1486 // Instruction creation methods: Compare Instructions 1487 //===--------------------------------------------------------------------===// 1488 1489 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") { 1490 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name); 1491 } 1492 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") { 1493 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name); 1494 } 1495 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") { 1496 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name); 1497 } 1498 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") { 1499 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name); 1500 } 1501 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") { 1502 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name); 1503 } 1504 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") { 1505 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name); 1506 } 1507 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") { 1508 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name); 1509 } 1510 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") { 1511 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name); 1512 } 1513 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") { 1514 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name); 1515 } 1516 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") { 1517 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name); 1518 } 1519 1520 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "", 1521 MDNode *FPMathTag = nullptr) { 1522 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag); 1523 } 1524 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "", 1525 MDNode *FPMathTag = nullptr) { 1526 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag); 1527 } 1528 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "", 1529 MDNode *FPMathTag = nullptr) { 1530 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag); 1531 } 1532 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "", 1533 MDNode *FPMathTag = nullptr) { 1534 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag); 1535 } 1536 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "", 1537 MDNode *FPMathTag = nullptr) { 1538 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag); 1539 } 1540 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "", 1541 MDNode *FPMathTag = nullptr) { 1542 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag); 1543 } 1544 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "", 1545 MDNode *FPMathTag = nullptr) { 1546 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag); 1547 } 1548 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "", 1549 MDNode *FPMathTag = nullptr) { 1550 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag); 1551 } 1552 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "", 1553 MDNode *FPMathTag = nullptr) { 1554 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag); 1555 } 1556 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "", 1557 MDNode *FPMathTag = nullptr) { 1558 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag); 1559 } 1560 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "", 1561 MDNode *FPMathTag = nullptr) { 1562 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag); 1563 } 1564 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "", 1565 MDNode *FPMathTag = nullptr) { 1566 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag); 1567 } 1568 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "", 1569 MDNode *FPMathTag = nullptr) { 1570 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag); 1571 } 1572 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "", 1573 MDNode *FPMathTag = nullptr) { 1574 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag); 1575 } 1576 1577 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, 1578 const Twine &Name = "") { 1579 if (Constant *LC = dyn_cast<Constant>(LHS)) 1580 if (Constant *RC = dyn_cast<Constant>(RHS)) 1581 return Insert(Folder.CreateICmp(P, LC, RC), Name); 1582 return Insert(new ICmpInst(P, LHS, RHS), Name); 1583 } 1584 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, 1585 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 1586 if (Constant *LC = dyn_cast<Constant>(LHS)) 1587 if (Constant *RC = dyn_cast<Constant>(RHS)) 1588 return Insert(Folder.CreateFCmp(P, LC, RC), Name); 1589 return Insert(AddFPMathAttributes(new FCmpInst(P, LHS, RHS), 1590 FPMathTag, FMF), Name); 1591 } 1592 1593 //===--------------------------------------------------------------------===// 1594 // Instruction creation methods: Other Instructions 1595 //===--------------------------------------------------------------------===// 1596 1597 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues, 1598 const Twine &Name = "") { 1599 return Insert(PHINode::Create(Ty, NumReservedValues), Name); 1600 } 1601 1602 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None, 1603 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 1604 PointerType *PTy = cast<PointerType>(Callee->getType()); 1605 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1606 return CreateCall(FTy, Callee, Args, Name, FPMathTag); 1607 } 1608 1609 CallInst *CreateCall(FunctionType *FTy, Value *Callee, 1610 ArrayRef<Value *> Args, const Twine &Name = "", 1611 MDNode *FPMathTag = nullptr) { 1612 CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles); 1613 if (isa<FPMathOperator>(CI)) 1614 CI = cast<CallInst>(AddFPMathAttributes(CI, FPMathTag, FMF)); 1615 return Insert(CI, Name); 1616 } 1617 1618 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args, 1619 ArrayRef<OperandBundleDef> OpBundles, 1620 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 1621 CallInst *CI = CallInst::Create(Callee, Args, OpBundles); 1622 if (isa<FPMathOperator>(CI)) 1623 CI = cast<CallInst>(AddFPMathAttributes(CI, FPMathTag, FMF)); 1624 return Insert(CI, Name); 1625 } 1626 1627 CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args, 1628 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 1629 return CreateCall(Callee->getFunctionType(), Callee, Args, Name, FPMathTag); 1630 } 1631 1632 Value *CreateSelect(Value *C, Value *True, Value *False, 1633 const Twine &Name = "", Instruction *MDFrom = nullptr) { 1634 if (Constant *CC = dyn_cast<Constant>(C)) 1635 if (Constant *TC = dyn_cast<Constant>(True)) 1636 if (Constant *FC = dyn_cast<Constant>(False)) 1637 return Insert(Folder.CreateSelect(CC, TC, FC), Name); 1638 1639 SelectInst *Sel = SelectInst::Create(C, True, False); 1640 if (MDFrom) { 1641 MDNode *Prof = MDFrom->getMetadata(LLVMContext::MD_prof); 1642 MDNode *Unpred = MDFrom->getMetadata(LLVMContext::MD_unpredictable); 1643 Sel = addBranchMetadata(Sel, Prof, Unpred); 1644 } 1645 return Insert(Sel, Name); 1646 } 1647 1648 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") { 1649 return Insert(new VAArgInst(List, Ty), Name); 1650 } 1651 1652 Value *CreateExtractElement(Value *Vec, Value *Idx, 1653 const Twine &Name = "") { 1654 if (Constant *VC = dyn_cast<Constant>(Vec)) 1655 if (Constant *IC = dyn_cast<Constant>(Idx)) 1656 return Insert(Folder.CreateExtractElement(VC, IC), Name); 1657 return Insert(ExtractElementInst::Create(Vec, Idx), Name); 1658 } 1659 1660 Value *CreateExtractElement(Value *Vec, uint64_t Idx, 1661 const Twine &Name = "") { 1662 return CreateExtractElement(Vec, getInt64(Idx), Name); 1663 } 1664 1665 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, 1666 const Twine &Name = "") { 1667 if (Constant *VC = dyn_cast<Constant>(Vec)) 1668 if (Constant *NC = dyn_cast<Constant>(NewElt)) 1669 if (Constant *IC = dyn_cast<Constant>(Idx)) 1670 return Insert(Folder.CreateInsertElement(VC, NC, IC), Name); 1671 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name); 1672 } 1673 1674 Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx, 1675 const Twine &Name = "") { 1676 return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name); 1677 } 1678 1679 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask, 1680 const Twine &Name = "") { 1681 if (Constant *V1C = dyn_cast<Constant>(V1)) 1682 if (Constant *V2C = dyn_cast<Constant>(V2)) 1683 if (Constant *MC = dyn_cast<Constant>(Mask)) 1684 return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name); 1685 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name); 1686 } 1687 1688 Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<uint32_t> IntMask, 1689 const Twine &Name = "") { 1690 Value *Mask = ConstantDataVector::get(Context, IntMask); 1691 return CreateShuffleVector(V1, V2, Mask, Name); 1692 } 1693 1694 Value *CreateExtractValue(Value *Agg, 1695 ArrayRef<unsigned> Idxs, 1696 const Twine &Name = "") { 1697 if (Constant *AggC = dyn_cast<Constant>(Agg)) 1698 return Insert(Folder.CreateExtractValue(AggC, Idxs), Name); 1699 return Insert(ExtractValueInst::Create(Agg, Idxs), Name); 1700 } 1701 1702 Value *CreateInsertValue(Value *Agg, Value *Val, 1703 ArrayRef<unsigned> Idxs, 1704 const Twine &Name = "") { 1705 if (Constant *AggC = dyn_cast<Constant>(Agg)) 1706 if (Constant *ValC = dyn_cast<Constant>(Val)) 1707 return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name); 1708 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name); 1709 } 1710 1711 LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses, 1712 const Twine &Name = "") { 1713 return Insert(LandingPadInst::Create(Ty, NumClauses), Name); 1714 } 1715 1716 //===--------------------------------------------------------------------===// 1717 // Utility creation methods 1718 //===--------------------------------------------------------------------===// 1719 1720 /// \brief Return an i1 value testing if \p Arg is null. 1721 Value *CreateIsNull(Value *Arg, const Twine &Name = "") { 1722 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()), 1723 Name); 1724 } 1725 1726 /// \brief Return an i1 value testing if \p Arg is not null. 1727 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") { 1728 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()), 1729 Name); 1730 } 1731 1732 /// \brief Return the i64 difference between two pointer values, dividing out 1733 /// the size of the pointed-to objects. 1734 /// 1735 /// This is intended to implement C-style pointer subtraction. As such, the 1736 /// pointers must be appropriately aligned for their element types and 1737 /// pointing into the same object. 1738 Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") { 1739 assert(LHS->getType() == RHS->getType() && 1740 "Pointer subtraction operand types must match!"); 1741 PointerType *ArgType = cast<PointerType>(LHS->getType()); 1742 Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context)); 1743 Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context)); 1744 Value *Difference = CreateSub(LHS_int, RHS_int); 1745 return CreateExactSDiv(Difference, 1746 ConstantExpr::getSizeOf(ArgType->getElementType()), 1747 Name); 1748 } 1749 1750 /// \brief Create an invariant.group.barrier intrinsic call, that stops 1751 /// optimizer to propagate equality using invariant.group metadata. 1752 /// If Ptr type is different from i8*, it's casted to i8* before call 1753 /// and casted back to Ptr type after call. 1754 Value *CreateInvariantGroupBarrier(Value *Ptr) { 1755 Module *M = BB->getParent()->getParent(); 1756 Function *FnInvariantGroupBarrier = Intrinsic::getDeclaration(M, 1757 Intrinsic::invariant_group_barrier); 1758 1759 Type *ArgumentAndReturnType = FnInvariantGroupBarrier->getReturnType(); 1760 assert(ArgumentAndReturnType == 1761 FnInvariantGroupBarrier->getFunctionType()->getParamType(0) && 1762 "InvariantGroupBarrier should take and return the same type"); 1763 Type *PtrType = Ptr->getType(); 1764 1765 bool PtrTypeConversionNeeded = PtrType != ArgumentAndReturnType; 1766 if (PtrTypeConversionNeeded) 1767 Ptr = CreateBitCast(Ptr, ArgumentAndReturnType); 1768 1769 CallInst *Fn = CreateCall(FnInvariantGroupBarrier, {Ptr}); 1770 1771 if (PtrTypeConversionNeeded) 1772 return CreateBitCast(Fn, PtrType); 1773 return Fn; 1774 } 1775 1776 /// \brief Return a vector value that contains \arg V broadcasted to \p 1777 /// NumElts elements. 1778 Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") { 1779 assert(NumElts > 0 && "Cannot splat to an empty vector!"); 1780 1781 // First insert it into an undef vector so we can shuffle it. 1782 Type *I32Ty = getInt32Ty(); 1783 Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts)); 1784 V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0), 1785 Name + ".splatinsert"); 1786 1787 // Shuffle the value across the desired number of elements. 1788 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts)); 1789 return CreateShuffleVector(V, Undef, Zeros, Name + ".splat"); 1790 } 1791 1792 /// \brief Return a value that has been extracted from a larger integer type. 1793 Value *CreateExtractInteger(const DataLayout &DL, Value *From, 1794 IntegerType *ExtractedTy, uint64_t Offset, 1795 const Twine &Name) { 1796 IntegerType *IntTy = cast<IntegerType>(From->getType()); 1797 assert(DL.getTypeStoreSize(ExtractedTy) + Offset <= 1798 DL.getTypeStoreSize(IntTy) && 1799 "Element extends past full value"); 1800 uint64_t ShAmt = 8 * Offset; 1801 Value *V = From; 1802 if (DL.isBigEndian()) 1803 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - 1804 DL.getTypeStoreSize(ExtractedTy) - Offset); 1805 if (ShAmt) { 1806 V = CreateLShr(V, ShAmt, Name + ".shift"); 1807 } 1808 assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() && 1809 "Cannot extract to a larger integer!"); 1810 if (ExtractedTy != IntTy) { 1811 V = CreateTrunc(V, ExtractedTy, Name + ".trunc"); 1812 } 1813 return V; 1814 } 1815 1816 private: 1817 /// \brief Helper function that creates an assume intrinsic call that 1818 /// represents an alignment assumption on the provided Ptr, Mask, Type 1819 /// and Offset. 1820 CallInst *CreateAlignmentAssumptionHelper(const DataLayout &DL, 1821 Value *PtrValue, Value *Mask, 1822 Type *IntPtrTy, 1823 Value *OffsetValue) { 1824 Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint"); 1825 1826 if (OffsetValue) { 1827 bool IsOffsetZero = false; 1828 if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue)) 1829 IsOffsetZero = CI->isZero(); 1830 1831 if (!IsOffsetZero) { 1832 if (OffsetValue->getType() != IntPtrTy) 1833 OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true, 1834 "offsetcast"); 1835 PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr"); 1836 } 1837 } 1838 1839 Value *Zero = ConstantInt::get(IntPtrTy, 0); 1840 Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr"); 1841 Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond"); 1842 return CreateAssumption(InvCond); 1843 } 1844 1845 public: 1846 /// \brief Create an assume intrinsic call that represents an alignment 1847 /// assumption on the provided pointer. 1848 /// 1849 /// An optional offset can be provided, and if it is provided, the offset 1850 /// must be subtracted from the provided pointer to get the pointer with the 1851 /// specified alignment. 1852 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue, 1853 unsigned Alignment, 1854 Value *OffsetValue = nullptr) { 1855 assert(isa<PointerType>(PtrValue->getType()) && 1856 "trying to create an alignment assumption on a non-pointer?"); 1857 PointerType *PtrTy = cast<PointerType>(PtrValue->getType()); 1858 Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace()); 1859 1860 Value *Mask = ConstantInt::get(IntPtrTy, Alignment > 0 ? Alignment - 1 : 0); 1861 return CreateAlignmentAssumptionHelper(DL, PtrValue, Mask, IntPtrTy, 1862 OffsetValue); 1863 } 1864 // 1865 /// \brief Create an assume intrinsic call that represents an alignment 1866 /// assumption on the provided pointer. 1867 /// 1868 /// An optional offset can be provided, and if it is provided, the offset 1869 /// must be subtracted from the provided pointer to get the pointer with the 1870 /// specified alignment. 1871 /// 1872 /// This overload handles the condition where the Alignment is dependent 1873 /// on an existing value rather than a static value. 1874 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue, 1875 Value *Alignment, 1876 Value *OffsetValue = nullptr) { 1877 assert(isa<PointerType>(PtrValue->getType()) && 1878 "trying to create an alignment assumption on a non-pointer?"); 1879 PointerType *PtrTy = cast<PointerType>(PtrValue->getType()); 1880 Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace()); 1881 1882 if (Alignment->getType() != IntPtrTy) 1883 Alignment = CreateIntCast(Alignment, IntPtrTy, /*isSigned*/ true, 1884 "alignmentcast"); 1885 Value *IsPositive = 1886 CreateICmp(CmpInst::ICMP_SGT, Alignment, 1887 ConstantInt::get(Alignment->getType(), 0), "ispositive"); 1888 Value *PositiveMask = 1889 CreateSub(Alignment, ConstantInt::get(IntPtrTy, 1), "positivemask"); 1890 Value *Mask = CreateSelect(IsPositive, PositiveMask, 1891 ConstantInt::get(IntPtrTy, 0), "mask"); 1892 1893 return CreateAlignmentAssumptionHelper(DL, PtrValue, Mask, IntPtrTy, 1894 OffsetValue); 1895 } 1896 }; 1897 1898 // Create wrappers for C Binding types (see CBindingWrapping.h). 1899 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef) 1900 1901 } // end namespace llvm 1902 1903 #endif // LLVM_IR_IRBUILDER_H 1904