1 //===- llvm/IRBuilder.h - Builder for LLVM Instructions ---------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the IRBuilder class, which is used as a convenient way 10 // to create LLVM instructions with a consistent and simplified interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_IR_IRBUILDER_H 15 #define LLVM_IR_IRBUILDER_H 16 17 #include "llvm-c/Types.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/STLExtras.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/FPEnv.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/GlobalVariable.h" 32 #include "llvm/IR/InstrTypes.h" 33 #include "llvm/IR/Instruction.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/LLVMContext.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/Support/Compiler.h" 45 #include <cassert> 46 #include <cstdint> 47 #include <functional> 48 #include <optional> 49 #include <utility> 50 51 namespace llvm { 52 53 class APInt; 54 class Use; 55 56 /// This provides the default implementation of the IRBuilder 57 /// 'InsertHelper' method that is called whenever an instruction is created by 58 /// IRBuilder and needs to be inserted. 59 /// 60 /// By default, this inserts the instruction at the insertion point. 61 class LLVM_ABI IRBuilderDefaultInserter { 62 public: 63 virtual ~IRBuilderDefaultInserter(); 64 InsertHelper(Instruction * I,const Twine & Name,BasicBlock::iterator InsertPt)65 virtual void InsertHelper(Instruction *I, const Twine &Name, 66 BasicBlock::iterator InsertPt) const { 67 if (InsertPt.isValid()) 68 I->insertInto(InsertPt.getNodeParent(), InsertPt); 69 I->setName(Name); 70 } 71 }; 72 73 /// Provides an 'InsertHelper' that calls a user-provided callback after 74 /// performing the default insertion. 75 class LLVM_ABI IRBuilderCallbackInserter : public IRBuilderDefaultInserter { 76 std::function<void(Instruction *)> Callback; 77 78 public: 79 ~IRBuilderCallbackInserter() override; 80 IRBuilderCallbackInserter(std::function<void (Instruction *)> Callback)81 IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback) 82 : Callback(std::move(Callback)) {} 83 InsertHelper(Instruction * I,const Twine & Name,BasicBlock::iterator InsertPt)84 void InsertHelper(Instruction *I, const Twine &Name, 85 BasicBlock::iterator InsertPt) const override { 86 IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt); 87 Callback(I); 88 } 89 }; 90 91 /// This provides a helper for copying FMF from an instruction or setting 92 /// specified flags. 93 class FMFSource { 94 std::optional<FastMathFlags> FMF; 95 96 public: 97 FMFSource() = default; FMFSource(Instruction * Source)98 FMFSource(Instruction *Source) { 99 if (Source) 100 FMF = Source->getFastMathFlags(); 101 } FMFSource(FastMathFlags FMF)102 FMFSource(FastMathFlags FMF) : FMF(FMF) {} get(FastMathFlags Default)103 FastMathFlags get(FastMathFlags Default) const { 104 return FMF.value_or(Default); 105 } 106 /// Intersect the FMF from two instructions. intersect(Value * A,Value * B)107 static FMFSource intersect(Value *A, Value *B) { 108 return FMFSource(cast<FPMathOperator>(A)->getFastMathFlags() & 109 cast<FPMathOperator>(B)->getFastMathFlags()); 110 } 111 }; 112 113 /// Common base class shared among various IRBuilders. 114 class IRBuilderBase { 115 /// Pairs of (metadata kind, MDNode *) that should be added to all newly 116 /// created instructions, excluding !dbg metadata, which is stored in the 117 /// StoredDL field. 118 SmallVector<std::pair<unsigned, MDNode *>, 2> MetadataToCopy; 119 /// The DebugLoc that will be applied to instructions inserted by this 120 /// builder. 121 DebugLoc StoredDL; 122 123 /// Add or update the an entry (Kind, MD) to MetadataToCopy, if \p MD is not 124 /// null. If \p MD is null, remove the entry with \p Kind. AddOrRemoveMetadataToCopy(unsigned Kind,MDNode * MD)125 void AddOrRemoveMetadataToCopy(unsigned Kind, MDNode *MD) { 126 assert(Kind != LLVMContext::MD_dbg && 127 "MD_dbg metadata must be stored in StoredDL"); 128 129 if (!MD) { 130 erase_if(MetadataToCopy, [Kind](const std::pair<unsigned, MDNode *> &KV) { 131 return KV.first == Kind; 132 }); 133 return; 134 } 135 136 for (auto &KV : MetadataToCopy) 137 if (KV.first == Kind) { 138 KV.second = MD; 139 return; 140 } 141 142 MetadataToCopy.emplace_back(Kind, MD); 143 } 144 145 protected: 146 BasicBlock *BB; 147 BasicBlock::iterator InsertPt; 148 LLVMContext &Context; 149 const IRBuilderFolder &Folder; 150 const IRBuilderDefaultInserter &Inserter; 151 152 MDNode *DefaultFPMathTag; 153 FastMathFlags FMF; 154 155 bool IsFPConstrained = false; 156 fp::ExceptionBehavior DefaultConstrainedExcept = fp::ebStrict; 157 RoundingMode DefaultConstrainedRounding = RoundingMode::Dynamic; 158 159 ArrayRef<OperandBundleDef> DefaultOperandBundles; 160 161 public: IRBuilderBase(LLVMContext & context,const IRBuilderFolder & Folder,const IRBuilderDefaultInserter & Inserter,MDNode * FPMathTag,ArrayRef<OperandBundleDef> OpBundles)162 IRBuilderBase(LLVMContext &context, const IRBuilderFolder &Folder, 163 const IRBuilderDefaultInserter &Inserter, MDNode *FPMathTag, 164 ArrayRef<OperandBundleDef> OpBundles) 165 : Context(context), Folder(Folder), Inserter(Inserter), 166 DefaultFPMathTag(FPMathTag), DefaultOperandBundles(OpBundles) { 167 ClearInsertionPoint(); 168 } 169 170 /// Insert and return the specified instruction. 171 template<typename InstTy> 172 InstTy *Insert(InstTy *I, const Twine &Name = "") const { 173 Inserter.InsertHelper(I, Name, InsertPt); 174 AddMetadataToInst(I); 175 return I; 176 } 177 178 /// No-op overload to handle constants. 179 Constant *Insert(Constant *C, const Twine& = "") const { 180 return C; 181 } 182 183 Value *Insert(Value *V, const Twine &Name = "") const { 184 if (Instruction *I = dyn_cast<Instruction>(V)) 185 return Insert(I, Name); 186 assert(isa<Constant>(V)); 187 return V; 188 } 189 190 //===--------------------------------------------------------------------===// 191 // Builder configuration methods 192 //===--------------------------------------------------------------------===// 193 194 /// Clear the insertion point: created instructions will not be 195 /// inserted into a block. ClearInsertionPoint()196 void ClearInsertionPoint() { 197 BB = nullptr; 198 InsertPt = BasicBlock::iterator(); 199 } 200 GetInsertBlock()201 BasicBlock *GetInsertBlock() const { return BB; } GetInsertPoint()202 BasicBlock::iterator GetInsertPoint() const { return InsertPt; } getContext()203 LLVMContext &getContext() const { return Context; } 204 205 /// This specifies that created instructions should be appended to the 206 /// end of the specified block. SetInsertPoint(BasicBlock * TheBB)207 void SetInsertPoint(BasicBlock *TheBB) { 208 BB = TheBB; 209 InsertPt = BB->end(); 210 } 211 212 /// This specifies that created instructions should be inserted before 213 /// the specified instruction. SetInsertPoint(Instruction * I)214 void SetInsertPoint(Instruction *I) { 215 BB = I->getParent(); 216 InsertPt = I->getIterator(); 217 assert(InsertPt != BB->end() && "Can't read debug loc from end()"); 218 SetCurrentDebugLocation(I->getStableDebugLoc()); 219 } 220 221 /// This specifies that created instructions should be inserted at the 222 /// specified point. SetInsertPoint(BasicBlock * TheBB,BasicBlock::iterator IP)223 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) { 224 BB = TheBB; 225 InsertPt = IP; 226 if (IP != TheBB->end()) 227 SetCurrentDebugLocation(IP->getStableDebugLoc()); 228 } 229 230 /// This specifies that created instructions should be inserted at 231 /// the specified point, but also requires that \p IP is dereferencable. SetInsertPoint(BasicBlock::iterator IP)232 void SetInsertPoint(BasicBlock::iterator IP) { 233 BB = IP->getParent(); 234 InsertPt = IP; 235 SetCurrentDebugLocation(IP->getStableDebugLoc()); 236 } 237 238 /// This specifies that created instructions should inserted at the beginning 239 /// end of the specified function, but after already existing static alloca 240 /// instructions that are at the start. SetInsertPointPastAllocas(Function * F)241 void SetInsertPointPastAllocas(Function *F) { 242 BB = &F->getEntryBlock(); 243 InsertPt = BB->getFirstNonPHIOrDbgOrAlloca(); 244 } 245 246 /// Set location information used by debugging information. SetCurrentDebugLocation(DebugLoc L)247 void SetCurrentDebugLocation(DebugLoc L) { 248 // For !dbg metadata attachments, we use DebugLoc instead of the raw MDNode 249 // to include optional introspection data for use in Debugify. 250 StoredDL = std::move(L); 251 } 252 253 /// Set nosanitize metadata. SetNoSanitizeMetadata()254 void SetNoSanitizeMetadata() { 255 AddOrRemoveMetadataToCopy(llvm::LLVMContext::MD_nosanitize, 256 llvm::MDNode::get(getContext(), {})); 257 } 258 259 /// Collect metadata with IDs \p MetadataKinds from \p Src which should be 260 /// added to all created instructions. Entries present in MedataDataToCopy but 261 /// not on \p Src will be dropped from MetadataToCopy. CollectMetadataToCopy(Instruction * Src,ArrayRef<unsigned> MetadataKinds)262 void CollectMetadataToCopy(Instruction *Src, 263 ArrayRef<unsigned> MetadataKinds) { 264 for (unsigned K : MetadataKinds) { 265 if (K == LLVMContext::MD_dbg) 266 SetCurrentDebugLocation(Src->getDebugLoc()); 267 else 268 AddOrRemoveMetadataToCopy(K, Src->getMetadata(K)); 269 } 270 } 271 272 /// Get location information used by debugging information. 273 LLVM_ABI DebugLoc getCurrentDebugLocation() const; 274 275 /// If this builder has a current debug location, set it on the 276 /// specified instruction. 277 LLVM_ABI void SetInstDebugLocation(Instruction *I) const; 278 279 /// Add all entries in MetadataToCopy to \p I. AddMetadataToInst(Instruction * I)280 void AddMetadataToInst(Instruction *I) const { 281 for (const auto &KV : MetadataToCopy) 282 I->setMetadata(KV.first, KV.second); 283 SetInstDebugLocation(I); 284 } 285 286 /// Get the return type of the current function that we're emitting 287 /// into. 288 LLVM_ABI Type *getCurrentFunctionReturnType() const; 289 290 /// InsertPoint - A saved insertion point. 291 class InsertPoint { 292 BasicBlock *Block = nullptr; 293 BasicBlock::iterator Point; 294 295 public: 296 /// Creates a new insertion point which doesn't point to anything. 297 InsertPoint() = default; 298 299 /// Creates a new insertion point at the given location. InsertPoint(BasicBlock * InsertBlock,BasicBlock::iterator InsertPoint)300 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint) 301 : Block(InsertBlock), Point(InsertPoint) {} 302 303 /// Returns true if this insert point is set. isSet()304 bool isSet() const { return (Block != nullptr); } 305 getBlock()306 BasicBlock *getBlock() const { return Block; } getPoint()307 BasicBlock::iterator getPoint() const { return Point; } 308 }; 309 310 /// Returns the current insert point. saveIP()311 InsertPoint saveIP() const { 312 return InsertPoint(GetInsertBlock(), GetInsertPoint()); 313 } 314 315 /// Returns the current insert point, clearing it in the process. saveAndClearIP()316 InsertPoint saveAndClearIP() { 317 InsertPoint IP(GetInsertBlock(), GetInsertPoint()); 318 ClearInsertionPoint(); 319 return IP; 320 } 321 322 /// Sets the current insert point to a previously-saved location. restoreIP(InsertPoint IP)323 void restoreIP(InsertPoint IP) { 324 if (IP.isSet()) 325 SetInsertPoint(IP.getBlock(), IP.getPoint()); 326 else 327 ClearInsertionPoint(); 328 } 329 330 /// Get the floating point math metadata being used. getDefaultFPMathTag()331 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; } 332 333 /// Get the flags to be applied to created floating point ops getFastMathFlags()334 FastMathFlags getFastMathFlags() const { return FMF; } 335 getFastMathFlags()336 FastMathFlags &getFastMathFlags() { return FMF; } 337 338 /// Clear the fast-math flags. clearFastMathFlags()339 void clearFastMathFlags() { FMF.clear(); } 340 341 /// Set the floating point math metadata to be used. setDefaultFPMathTag(MDNode * FPMathTag)342 void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; } 343 344 /// Set the fast-math flags to be used with generated fp-math operators setFastMathFlags(FastMathFlags NewFMF)345 void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; } 346 347 /// Enable/Disable use of constrained floating point math. When 348 /// enabled the CreateF<op>() calls instead create constrained 349 /// floating point intrinsic calls. Fast math flags are unaffected 350 /// by this setting. setIsFPConstrained(bool IsCon)351 void setIsFPConstrained(bool IsCon) { IsFPConstrained = IsCon; } 352 353 /// Query for the use of constrained floating point math getIsFPConstrained()354 bool getIsFPConstrained() { return IsFPConstrained; } 355 356 /// Set the exception handling to be used with constrained floating point setDefaultConstrainedExcept(fp::ExceptionBehavior NewExcept)357 void setDefaultConstrainedExcept(fp::ExceptionBehavior NewExcept) { 358 #ifndef NDEBUG 359 std::optional<StringRef> ExceptStr = 360 convertExceptionBehaviorToStr(NewExcept); 361 assert(ExceptStr && "Garbage strict exception behavior!"); 362 #endif 363 DefaultConstrainedExcept = NewExcept; 364 } 365 366 /// Set the rounding mode handling to be used with constrained floating point setDefaultConstrainedRounding(RoundingMode NewRounding)367 void setDefaultConstrainedRounding(RoundingMode NewRounding) { 368 #ifndef NDEBUG 369 std::optional<StringRef> RoundingStr = 370 convertRoundingModeToStr(NewRounding); 371 assert(RoundingStr && "Garbage strict rounding mode!"); 372 #endif 373 DefaultConstrainedRounding = NewRounding; 374 } 375 376 /// Get the exception handling used with constrained floating point getDefaultConstrainedExcept()377 fp::ExceptionBehavior getDefaultConstrainedExcept() { 378 return DefaultConstrainedExcept; 379 } 380 381 /// Get the rounding mode handling used with constrained floating point getDefaultConstrainedRounding()382 RoundingMode getDefaultConstrainedRounding() { 383 return DefaultConstrainedRounding; 384 } 385 setConstrainedFPFunctionAttr()386 void setConstrainedFPFunctionAttr() { 387 assert(BB && "Must have a basic block to set any function attributes!"); 388 389 Function *F = BB->getParent(); 390 if (!F->hasFnAttribute(Attribute::StrictFP)) { 391 F->addFnAttr(Attribute::StrictFP); 392 } 393 } 394 setConstrainedFPCallAttr(CallBase * I)395 void setConstrainedFPCallAttr(CallBase *I) { 396 I->addFnAttr(Attribute::StrictFP); 397 } 398 setDefaultOperandBundles(ArrayRef<OperandBundleDef> OpBundles)399 void setDefaultOperandBundles(ArrayRef<OperandBundleDef> OpBundles) { 400 DefaultOperandBundles = OpBundles; 401 } 402 403 //===--------------------------------------------------------------------===// 404 // RAII helpers. 405 //===--------------------------------------------------------------------===// 406 407 // RAII object that stores the current insertion point and restores it 408 // when the object is destroyed. This includes the debug location. 409 class InsertPointGuard { 410 IRBuilderBase &Builder; 411 AssertingVH<BasicBlock> Block; 412 BasicBlock::iterator Point; 413 DebugLoc DbgLoc; 414 415 public: InsertPointGuard(IRBuilderBase & B)416 InsertPointGuard(IRBuilderBase &B) 417 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()), 418 DbgLoc(B.getCurrentDebugLocation()) {} 419 420 InsertPointGuard(const InsertPointGuard &) = delete; 421 InsertPointGuard &operator=(const InsertPointGuard &) = delete; 422 ~InsertPointGuard()423 ~InsertPointGuard() { 424 Builder.restoreIP(InsertPoint(Block, Point)); 425 Builder.SetCurrentDebugLocation(DbgLoc); 426 } 427 }; 428 429 // RAII object that stores the current fast math settings and restores 430 // them when the object is destroyed. 431 class FastMathFlagGuard { 432 IRBuilderBase &Builder; 433 FastMathFlags FMF; 434 MDNode *FPMathTag; 435 bool IsFPConstrained; 436 fp::ExceptionBehavior DefaultConstrainedExcept; 437 RoundingMode DefaultConstrainedRounding; 438 439 public: FastMathFlagGuard(IRBuilderBase & B)440 FastMathFlagGuard(IRBuilderBase &B) 441 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag), 442 IsFPConstrained(B.IsFPConstrained), 443 DefaultConstrainedExcept(B.DefaultConstrainedExcept), 444 DefaultConstrainedRounding(B.DefaultConstrainedRounding) {} 445 446 FastMathFlagGuard(const FastMathFlagGuard &) = delete; 447 FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete; 448 ~FastMathFlagGuard()449 ~FastMathFlagGuard() { 450 Builder.FMF = FMF; 451 Builder.DefaultFPMathTag = FPMathTag; 452 Builder.IsFPConstrained = IsFPConstrained; 453 Builder.DefaultConstrainedExcept = DefaultConstrainedExcept; 454 Builder.DefaultConstrainedRounding = DefaultConstrainedRounding; 455 } 456 }; 457 458 // RAII object that stores the current default operand bundles and restores 459 // them when the object is destroyed. 460 class OperandBundlesGuard { 461 IRBuilderBase &Builder; 462 ArrayRef<OperandBundleDef> DefaultOperandBundles; 463 464 public: OperandBundlesGuard(IRBuilderBase & B)465 OperandBundlesGuard(IRBuilderBase &B) 466 : Builder(B), DefaultOperandBundles(B.DefaultOperandBundles) {} 467 468 OperandBundlesGuard(const OperandBundlesGuard &) = delete; 469 OperandBundlesGuard &operator=(const OperandBundlesGuard &) = delete; 470 ~OperandBundlesGuard()471 ~OperandBundlesGuard() { 472 Builder.DefaultOperandBundles = DefaultOperandBundles; 473 } 474 }; 475 476 477 //===--------------------------------------------------------------------===// 478 // Miscellaneous creation methods. 479 //===--------------------------------------------------------------------===// 480 481 /// Make a new global variable with initializer type i8* 482 /// 483 /// Make a new global variable with an initializer that has array of i8 type 484 /// filled in with the null terminated string value specified. The new global 485 /// variable will be marked mergable with any others of the same contents. If 486 /// Name is specified, it is the name of the global variable created. 487 /// 488 /// If no module is given via \p M, it is take from the insertion point basic 489 /// block. 490 LLVM_ABI GlobalVariable *CreateGlobalString(StringRef Str, 491 const Twine &Name = "", 492 unsigned AddressSpace = 0, 493 Module *M = nullptr, 494 bool AddNull = true); 495 496 /// Get a constant value representing either true or false. getInt1(bool V)497 ConstantInt *getInt1(bool V) { 498 return ConstantInt::get(getInt1Ty(), V); 499 } 500 501 /// Get the constant value for i1 true. getTrue()502 ConstantInt *getTrue() { 503 return ConstantInt::getTrue(Context); 504 } 505 506 /// Get the constant value for i1 false. getFalse()507 ConstantInt *getFalse() { 508 return ConstantInt::getFalse(Context); 509 } 510 511 /// Get a constant 8-bit value. getInt8(uint8_t C)512 ConstantInt *getInt8(uint8_t C) { 513 return ConstantInt::get(getInt8Ty(), C); 514 } 515 516 /// Get a constant 16-bit value. getInt16(uint16_t C)517 ConstantInt *getInt16(uint16_t C) { 518 return ConstantInt::get(getInt16Ty(), C); 519 } 520 521 /// Get a constant 32-bit value. getInt32(uint32_t C)522 ConstantInt *getInt32(uint32_t C) { 523 return ConstantInt::get(getInt32Ty(), C); 524 } 525 526 /// Get a constant 64-bit value. getInt64(uint64_t C)527 ConstantInt *getInt64(uint64_t C) { 528 return ConstantInt::get(getInt64Ty(), C); 529 } 530 531 /// Get a constant N-bit value, zero extended or truncated from 532 /// a 64-bit value. getIntN(unsigned N,uint64_t C)533 ConstantInt *getIntN(unsigned N, uint64_t C) { 534 return ConstantInt::get(getIntNTy(N), C); 535 } 536 537 /// Get a constant integer value. getInt(const APInt & AI)538 ConstantInt *getInt(const APInt &AI) { 539 return ConstantInt::get(Context, AI); 540 } 541 542 //===--------------------------------------------------------------------===// 543 // Type creation methods 544 //===--------------------------------------------------------------------===// 545 546 /// Fetch the type representing a single bit getInt1Ty()547 IntegerType *getInt1Ty() { 548 return Type::getInt1Ty(Context); 549 } 550 551 /// Fetch the type representing an 8-bit integer. getInt8Ty()552 IntegerType *getInt8Ty() { 553 return Type::getInt8Ty(Context); 554 } 555 556 /// Fetch the type representing a 16-bit integer. getInt16Ty()557 IntegerType *getInt16Ty() { 558 return Type::getInt16Ty(Context); 559 } 560 561 /// Fetch the type representing a 32-bit integer. getInt32Ty()562 IntegerType *getInt32Ty() { 563 return Type::getInt32Ty(Context); 564 } 565 566 /// Fetch the type representing a 64-bit integer. getInt64Ty()567 IntegerType *getInt64Ty() { 568 return Type::getInt64Ty(Context); 569 } 570 571 /// Fetch the type representing a 128-bit integer. getInt128Ty()572 IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); } 573 574 /// Fetch the type representing an N-bit integer. getIntNTy(unsigned N)575 IntegerType *getIntNTy(unsigned N) { 576 return Type::getIntNTy(Context, N); 577 } 578 579 /// Fetch the type representing a 16-bit floating point value. getHalfTy()580 Type *getHalfTy() { 581 return Type::getHalfTy(Context); 582 } 583 584 /// Fetch the type representing a 16-bit brain floating point value. getBFloatTy()585 Type *getBFloatTy() { 586 return Type::getBFloatTy(Context); 587 } 588 589 /// Fetch the type representing a 32-bit floating point value. getFloatTy()590 Type *getFloatTy() { 591 return Type::getFloatTy(Context); 592 } 593 594 /// Fetch the type representing a 64-bit floating point value. getDoubleTy()595 Type *getDoubleTy() { 596 return Type::getDoubleTy(Context); 597 } 598 599 /// Fetch the type representing void. getVoidTy()600 Type *getVoidTy() { 601 return Type::getVoidTy(Context); 602 } 603 604 /// Fetch the type representing a pointer. 605 PointerType *getPtrTy(unsigned AddrSpace = 0) { 606 return PointerType::get(Context, AddrSpace); 607 } 608 609 /// Fetch the type of an integer with size at least as big as that of a 610 /// pointer in the given address space. 611 IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) { 612 return DL.getIntPtrType(Context, AddrSpace); 613 } 614 615 /// Fetch the type of an integer that should be used to index GEP operations 616 /// within AddressSpace. getIndexTy(const DataLayout & DL,unsigned AddrSpace)617 IntegerType *getIndexTy(const DataLayout &DL, unsigned AddrSpace) { 618 return DL.getIndexType(Context, AddrSpace); 619 } 620 621 //===--------------------------------------------------------------------===// 622 // Intrinsic creation methods 623 //===--------------------------------------------------------------------===// 624 625 /// Create and insert a memset to the specified pointer and the 626 /// specified value. 627 /// 628 /// If the pointer isn't an i8*, it will be converted. If alias metadata is 629 /// specified, it will be added to the instruction. 630 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, 631 MaybeAlign Align, bool isVolatile = false, 632 const AAMDNodes &AAInfo = AAMDNodes()) { 633 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile, AAInfo); 634 } 635 636 LLVM_ABI CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, 637 MaybeAlign Align, bool isVolatile = false, 638 const AAMDNodes &AAInfo = AAMDNodes()); 639 640 LLVM_ABI CallInst *CreateMemSetInline(Value *Dst, MaybeAlign DstAlign, 641 Value *Val, Value *Size, 642 bool IsVolatile = false, 643 const AAMDNodes &AAInfo = AAMDNodes()); 644 645 /// Create and insert an element unordered-atomic memset of the region of 646 /// memory starting at the given pointer to the given value. 647 /// 648 /// If the pointer isn't an i8*, it will be converted. If alias metadata is 649 /// specified, it will be added to the instruction. 650 CallInst * 651 CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val, uint64_t Size, 652 Align Alignment, uint32_t ElementSize, 653 const AAMDNodes &AAInfo = AAMDNodes()) { 654 return CreateElementUnorderedAtomicMemSet( 655 Ptr, Val, getInt64(Size), Align(Alignment), ElementSize, AAInfo); 656 } 657 658 LLVM_ABI CallInst *CreateMalloc(Type *IntPtrTy, Type *AllocTy, 659 Value *AllocSize, Value *ArraySize, 660 ArrayRef<OperandBundleDef> OpB, 661 Function *MallocF = nullptr, 662 const Twine &Name = ""); 663 664 /// CreateMalloc - Generate the IR for a call to malloc: 665 /// 1. Compute the malloc call's argument as the specified type's size, 666 /// possibly multiplied by the array size if the array size is not 667 /// constant 1. 668 /// 2. Call malloc with that argument. 669 LLVM_ABI CallInst *CreateMalloc(Type *IntPtrTy, Type *AllocTy, 670 Value *AllocSize, Value *ArraySize, 671 Function *MallocF = nullptr, 672 const Twine &Name = ""); 673 /// Generate the IR for a call to the builtin free function. 674 LLVM_ABI CallInst *CreateFree(Value *Source, 675 ArrayRef<OperandBundleDef> Bundles = {}); 676 677 LLVM_ABI CallInst * 678 CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val, Value *Size, 679 Align Alignment, uint32_t ElementSize, 680 const AAMDNodes &AAInfo = AAMDNodes()); 681 682 /// Create and insert a memcpy between the specified pointers. 683 /// 684 /// If the pointers aren't i8*, they will be converted. If alias metadata is 685 /// specified, it will be added to the instruction. 686 /// and noalias tags. 687 CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, 688 MaybeAlign SrcAlign, uint64_t Size, 689 bool isVolatile = false, 690 const AAMDNodes &AAInfo = AAMDNodes()) { 691 return CreateMemCpy(Dst, DstAlign, Src, SrcAlign, getInt64(Size), 692 isVolatile, AAInfo); 693 } 694 695 LLVM_ABI CallInst * 696 CreateMemTransferInst(Intrinsic::ID IntrID, Value *Dst, MaybeAlign DstAlign, 697 Value *Src, MaybeAlign SrcAlign, Value *Size, 698 bool isVolatile = false, 699 const AAMDNodes &AAInfo = AAMDNodes()); 700 701 CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, 702 MaybeAlign SrcAlign, Value *Size, 703 bool isVolatile = false, 704 const AAMDNodes &AAInfo = AAMDNodes()) { 705 return CreateMemTransferInst(Intrinsic::memcpy, Dst, DstAlign, Src, 706 SrcAlign, Size, isVolatile, AAInfo); 707 } 708 709 CallInst *CreateMemCpyInline(Value *Dst, MaybeAlign DstAlign, Value *Src, 710 MaybeAlign SrcAlign, Value *Size, 711 bool isVolatile = false, 712 const AAMDNodes &AAInfo = AAMDNodes()) { 713 return CreateMemTransferInst(Intrinsic::memcpy_inline, Dst, DstAlign, Src, 714 SrcAlign, Size, isVolatile, AAInfo); 715 } 716 717 /// Create and insert an element unordered-atomic memcpy between the 718 /// specified pointers. 719 /// 720 /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers, 721 /// respectively. 722 /// 723 /// If the pointers aren't i8*, they will be converted. If alias metadata is 724 /// specified, it will be added to the instruction. 725 LLVM_ABI CallInst *CreateElementUnorderedAtomicMemCpy( 726 Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size, 727 uint32_t ElementSize, const AAMDNodes &AAInfo = AAMDNodes()); 728 729 CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src, 730 MaybeAlign SrcAlign, uint64_t Size, 731 bool isVolatile = false, 732 const AAMDNodes &AAInfo = AAMDNodes()) { 733 return CreateMemMove(Dst, DstAlign, Src, SrcAlign, getInt64(Size), 734 isVolatile, AAInfo); 735 } 736 737 CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src, 738 MaybeAlign SrcAlign, Value *Size, 739 bool isVolatile = false, 740 const AAMDNodes &AAInfo = AAMDNodes()) { 741 return CreateMemTransferInst(Intrinsic::memmove, Dst, DstAlign, Src, 742 SrcAlign, Size, isVolatile, AAInfo); 743 } 744 745 /// \brief Create and insert an element unordered-atomic memmove between the 746 /// specified pointers. 747 /// 748 /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers, 749 /// respectively. 750 /// 751 /// If the pointers aren't i8*, they will be converted. If alias metadata is 752 /// specified, it will be added to the instruction. 753 LLVM_ABI CallInst *CreateElementUnorderedAtomicMemMove( 754 Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size, 755 uint32_t ElementSize, const AAMDNodes &AAInfo = AAMDNodes()); 756 757 private: 758 CallInst *getReductionIntrinsic(Intrinsic::ID ID, Value *Src); 759 760 public: 761 /// Create a sequential vector fadd reduction intrinsic of the source vector. 762 /// The first parameter is a scalar accumulator value. An unordered reduction 763 /// can be created by adding the reassoc fast-math flag to the resulting 764 /// sequential reduction. 765 LLVM_ABI CallInst *CreateFAddReduce(Value *Acc, Value *Src); 766 767 /// Create a sequential vector fmul reduction intrinsic of the source vector. 768 /// The first parameter is a scalar accumulator value. An unordered reduction 769 /// can be created by adding the reassoc fast-math flag to the resulting 770 /// sequential reduction. 771 LLVM_ABI CallInst *CreateFMulReduce(Value *Acc, Value *Src); 772 773 /// Create a vector int add reduction intrinsic of the source vector. 774 LLVM_ABI CallInst *CreateAddReduce(Value *Src); 775 776 /// Create a vector int mul reduction intrinsic of the source vector. 777 LLVM_ABI CallInst *CreateMulReduce(Value *Src); 778 779 /// Create a vector int AND reduction intrinsic of the source vector. 780 LLVM_ABI CallInst *CreateAndReduce(Value *Src); 781 782 /// Create a vector int OR reduction intrinsic of the source vector. 783 LLVM_ABI CallInst *CreateOrReduce(Value *Src); 784 785 /// Create a vector int XOR reduction intrinsic of the source vector. 786 LLVM_ABI CallInst *CreateXorReduce(Value *Src); 787 788 /// Create a vector integer max reduction intrinsic of the source 789 /// vector. 790 LLVM_ABI CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false); 791 792 /// Create a vector integer min reduction intrinsic of the source 793 /// vector. 794 LLVM_ABI CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false); 795 796 /// Create a vector float max reduction intrinsic of the source 797 /// vector. 798 LLVM_ABI CallInst *CreateFPMaxReduce(Value *Src); 799 800 /// Create a vector float min reduction intrinsic of the source 801 /// vector. 802 LLVM_ABI CallInst *CreateFPMinReduce(Value *Src); 803 804 /// Create a vector float maximum reduction intrinsic of the source 805 /// vector. This variant follows the NaN and signed zero semantic of 806 /// llvm.maximum intrinsic. 807 LLVM_ABI CallInst *CreateFPMaximumReduce(Value *Src); 808 809 /// Create a vector float minimum reduction intrinsic of the source 810 /// vector. This variant follows the NaN and signed zero semantic of 811 /// llvm.minimum intrinsic. 812 LLVM_ABI CallInst *CreateFPMinimumReduce(Value *Src); 813 814 /// Create a lifetime.start intrinsic. 815 /// 816 /// If the pointer isn't i8* it will be converted. 817 LLVM_ABI CallInst *CreateLifetimeStart(Value *Ptr, 818 ConstantInt *Size = nullptr); 819 820 /// Create a lifetime.end intrinsic. 821 /// 822 /// If the pointer isn't i8* it will be converted. 823 LLVM_ABI CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr); 824 825 /// Create a call to invariant.start intrinsic. 826 /// 827 /// If the pointer isn't i8* it will be converted. 828 LLVM_ABI CallInst *CreateInvariantStart(Value *Ptr, 829 ConstantInt *Size = nullptr); 830 831 /// Create a call to llvm.threadlocal.address intrinsic. 832 LLVM_ABI CallInst *CreateThreadLocalAddress(Value *Ptr); 833 834 /// Create a call to Masked Load intrinsic 835 LLVM_ABI CallInst *CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, 836 Value *Mask, Value *PassThru = nullptr, 837 const Twine &Name = ""); 838 839 /// Create a call to Masked Store intrinsic 840 LLVM_ABI CallInst *CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, 841 Value *Mask); 842 843 /// Create a call to Masked Gather intrinsic 844 LLVM_ABI CallInst *CreateMaskedGather(Type *Ty, Value *Ptrs, Align Alignment, 845 Value *Mask = nullptr, 846 Value *PassThru = nullptr, 847 const Twine &Name = ""); 848 849 /// Create a call to Masked Scatter intrinsic 850 LLVM_ABI CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, 851 Align Alignment, 852 Value *Mask = nullptr); 853 854 /// Create a call to Masked Expand Load intrinsic 855 LLVM_ABI CallInst *CreateMaskedExpandLoad(Type *Ty, Value *Ptr, 856 MaybeAlign Align, 857 Value *Mask = nullptr, 858 Value *PassThru = nullptr, 859 const Twine &Name = ""); 860 861 /// Create a call to Masked Compress Store intrinsic 862 LLVM_ABI CallInst *CreateMaskedCompressStore(Value *Val, Value *Ptr, 863 MaybeAlign Align, 864 Value *Mask = nullptr); 865 866 /// Return an all true boolean vector (mask) with \p NumElts lanes. getAllOnesMask(ElementCount NumElts)867 Value *getAllOnesMask(ElementCount NumElts) { 868 VectorType *VTy = VectorType::get(Type::getInt1Ty(Context), NumElts); 869 return Constant::getAllOnesValue(VTy); 870 } 871 872 /// Create an assume intrinsic call that allows the optimizer to 873 /// assume that the provided condition will be true. 874 /// 875 /// The optional argument \p OpBundles specifies operand bundles that are 876 /// added to the call instruction. 877 LLVM_ABI CallInst * 878 CreateAssumption(Value *Cond, ArrayRef<OperandBundleDef> OpBundles = {}); 879 880 /// Create a llvm.experimental.noalias.scope.decl intrinsic call. 881 LLVM_ABI Instruction *CreateNoAliasScopeDeclaration(Value *Scope); CreateNoAliasScopeDeclaration(MDNode * ScopeTag)882 Instruction *CreateNoAliasScopeDeclaration(MDNode *ScopeTag) { 883 return CreateNoAliasScopeDeclaration( 884 MetadataAsValue::get(Context, ScopeTag)); 885 } 886 887 /// Create a call to the experimental.gc.statepoint intrinsic to 888 /// start a new statepoint sequence. 889 LLVM_ABI CallInst *CreateGCStatepointCall( 890 uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualCallee, 891 ArrayRef<Value *> CallArgs, std::optional<ArrayRef<Value *>> DeoptArgs, 892 ArrayRef<Value *> GCArgs, const Twine &Name = ""); 893 894 /// Create a call to the experimental.gc.statepoint intrinsic to 895 /// start a new statepoint sequence. 896 LLVM_ABI CallInst * 897 CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes, 898 FunctionCallee ActualCallee, uint32_t Flags, 899 ArrayRef<Value *> CallArgs, 900 std::optional<ArrayRef<Use>> TransitionArgs, 901 std::optional<ArrayRef<Use>> DeoptArgs, 902 ArrayRef<Value *> GCArgs, const Twine &Name = ""); 903 904 /// Conveninence function for the common case when CallArgs are filled 905 /// in using ArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be 906 /// .get()'ed to get the Value pointer. 907 LLVM_ABI CallInst * 908 CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes, 909 FunctionCallee ActualCallee, ArrayRef<Use> CallArgs, 910 std::optional<ArrayRef<Value *>> DeoptArgs, 911 ArrayRef<Value *> GCArgs, const Twine &Name = ""); 912 913 /// Create an invoke to the experimental.gc.statepoint intrinsic to 914 /// start a new statepoint sequence. 915 LLVM_ABI InvokeInst * 916 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes, 917 FunctionCallee ActualInvokee, BasicBlock *NormalDest, 918 BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs, 919 std::optional<ArrayRef<Value *>> DeoptArgs, 920 ArrayRef<Value *> GCArgs, const Twine &Name = ""); 921 922 /// Create an invoke to the experimental.gc.statepoint intrinsic to 923 /// start a new statepoint sequence. 924 LLVM_ABI InvokeInst *CreateGCStatepointInvoke( 925 uint64_t ID, uint32_t NumPatchBytes, FunctionCallee ActualInvokee, 926 BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags, 927 ArrayRef<Value *> InvokeArgs, std::optional<ArrayRef<Use>> TransitionArgs, 928 std::optional<ArrayRef<Use>> DeoptArgs, ArrayRef<Value *> GCArgs, 929 const Twine &Name = ""); 930 931 // Convenience function for the common case when CallArgs are filled in using 932 // ArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to 933 // get the Value *. 934 LLVM_ABI InvokeInst * 935 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes, 936 FunctionCallee ActualInvokee, BasicBlock *NormalDest, 937 BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs, 938 std::optional<ArrayRef<Value *>> DeoptArgs, 939 ArrayRef<Value *> GCArgs, const Twine &Name = ""); 940 941 /// Create a call to the experimental.gc.result intrinsic to extract 942 /// the result from a call wrapped in a statepoint. 943 LLVM_ABI CallInst *CreateGCResult(Instruction *Statepoint, Type *ResultType, 944 const Twine &Name = ""); 945 946 /// Create a call to the experimental.gc.relocate intrinsics to 947 /// project the relocated value of one pointer from the statepoint. 948 LLVM_ABI CallInst *CreateGCRelocate(Instruction *Statepoint, int BaseOffset, 949 int DerivedOffset, Type *ResultType, 950 const Twine &Name = ""); 951 952 /// Create a call to the experimental.gc.pointer.base intrinsic to get the 953 /// base pointer for the specified derived pointer. 954 LLVM_ABI CallInst *CreateGCGetPointerBase(Value *DerivedPtr, 955 const Twine &Name = ""); 956 957 /// Create a call to the experimental.gc.get.pointer.offset intrinsic to get 958 /// the offset of the specified derived pointer from its base. 959 LLVM_ABI CallInst *CreateGCGetPointerOffset(Value *DerivedPtr, 960 const Twine &Name = ""); 961 962 /// Create a call to llvm.vscale.<Ty>(). 963 Value *CreateVScale(Type *Ty, const Twine &Name = "") { 964 return CreateIntrinsic(Intrinsic::vscale, {Ty}, {}, {}, Name); 965 } 966 967 /// Create an expression which evaluates to the number of elements in \p EC 968 /// at runtime. This can result in poison if type \p Ty is not big enough to 969 /// hold the value. 970 LLVM_ABI Value *CreateElementCount(Type *Ty, ElementCount EC); 971 972 /// Create an expression which evaluates to the number of units in \p Size 973 /// at runtime. This works for both units of bits and bytes. This can result 974 /// in poison if type \p Ty is not big enough to hold the value. 975 LLVM_ABI Value *CreateTypeSize(Type *Ty, TypeSize Size); 976 977 /// Creates a vector of type \p DstType with the linear sequence <0, 1, ...> 978 LLVM_ABI Value *CreateStepVector(Type *DstType, const Twine &Name = ""); 979 980 /// Create a call to intrinsic \p ID with 1 operand which is mangled on its 981 /// type. 982 LLVM_ABI CallInst *CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, 983 FMFSource FMFSource = {}, 984 const Twine &Name = ""); 985 986 /// Create a call to intrinsic \p ID with 2 operands which is mangled on the 987 /// first type. 988 LLVM_ABI Value *CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, 989 Value *RHS, FMFSource FMFSource = {}, 990 const Twine &Name = ""); 991 992 /// Create a call to intrinsic \p ID with \p Args, mangled using \p Types. If 993 /// \p FMFSource is provided, copy fast-math-flags from that instruction to 994 /// the intrinsic. 995 LLVM_ABI CallInst *CreateIntrinsic(Intrinsic::ID ID, ArrayRef<Type *> Types, 996 ArrayRef<Value *> Args, 997 FMFSource FMFSource = {}, 998 const Twine &Name = ""); 999 1000 /// Create a call to intrinsic \p ID with \p RetTy and \p Args. If 1001 /// \p FMFSource is provided, copy fast-math-flags from that instruction to 1002 /// the intrinsic. 1003 LLVM_ABI CallInst *CreateIntrinsic(Type *RetTy, Intrinsic::ID ID, 1004 ArrayRef<Value *> Args, 1005 FMFSource FMFSource = {}, 1006 const Twine &Name = ""); 1007 1008 /// Create a call to non-overloaded intrinsic \p ID with \p Args. If 1009 /// \p FMFSource is provided, copy fast-math-flags from that instruction to 1010 /// the intrinsic. 1011 CallInst *CreateIntrinsic(Intrinsic::ID ID, ArrayRef<Value *> Args, 1012 FMFSource FMFSource = {}, const Twine &Name = "") { 1013 return CreateIntrinsic(ID, /*Types=*/{}, Args, FMFSource, Name); 1014 } 1015 1016 /// Create call to the minnum intrinsic. 1017 Value *CreateMinNum(Value *LHS, Value *RHS, FMFSource FMFSource = {}, 1018 const Twine &Name = "") { 1019 if (IsFPConstrained) { 1020 return CreateConstrainedFPUnroundedBinOp( 1021 Intrinsic::experimental_constrained_minnum, LHS, RHS, FMFSource, 1022 Name); 1023 } 1024 1025 return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, FMFSource, Name); 1026 } 1027 1028 /// Create call to the maxnum intrinsic. 1029 Value *CreateMaxNum(Value *LHS, Value *RHS, FMFSource FMFSource = {}, 1030 const Twine &Name = "") { 1031 if (IsFPConstrained) { 1032 return CreateConstrainedFPUnroundedBinOp( 1033 Intrinsic::experimental_constrained_maxnum, LHS, RHS, FMFSource, 1034 Name); 1035 } 1036 1037 return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, FMFSource, Name); 1038 } 1039 1040 /// Create call to the minimum intrinsic. 1041 Value *CreateMinimum(Value *LHS, Value *RHS, const Twine &Name = "") { 1042 return CreateBinaryIntrinsic(Intrinsic::minimum, LHS, RHS, nullptr, Name); 1043 } 1044 1045 /// Create call to the maximum intrinsic. 1046 Value *CreateMaximum(Value *LHS, Value *RHS, const Twine &Name = "") { 1047 return CreateBinaryIntrinsic(Intrinsic::maximum, LHS, RHS, nullptr, Name); 1048 } 1049 1050 /// Create call to the minimumnum intrinsic. 1051 Value *CreateMinimumNum(Value *LHS, Value *RHS, const Twine &Name = "") { 1052 return CreateBinaryIntrinsic(Intrinsic::minimumnum, LHS, RHS, nullptr, 1053 Name); 1054 } 1055 1056 /// Create call to the maximum intrinsic. 1057 Value *CreateMaximumNum(Value *LHS, Value *RHS, const Twine &Name = "") { 1058 return CreateBinaryIntrinsic(Intrinsic::maximumnum, LHS, RHS, nullptr, 1059 Name); 1060 } 1061 1062 /// Create call to the copysign intrinsic. 1063 Value *CreateCopySign(Value *LHS, Value *RHS, FMFSource FMFSource = {}, 1064 const Twine &Name = "") { 1065 return CreateBinaryIntrinsic(Intrinsic::copysign, LHS, RHS, FMFSource, 1066 Name); 1067 } 1068 1069 /// Create call to the ldexp intrinsic. 1070 Value *CreateLdexp(Value *Src, Value *Exp, FMFSource FMFSource = {}, 1071 const Twine &Name = "") { 1072 assert(!IsFPConstrained && "TODO: Support strictfp"); 1073 return CreateIntrinsic(Intrinsic::ldexp, {Src->getType(), Exp->getType()}, 1074 {Src, Exp}, FMFSource, Name); 1075 } 1076 1077 /// Create call to the fma intrinsic. 1078 Value *CreateFMA(Value *Factor1, Value *Factor2, Value *Summand, 1079 FMFSource FMFSource = {}, const Twine &Name = "") { 1080 if (IsFPConstrained) { 1081 return CreateConstrainedFPIntrinsic( 1082 Intrinsic::experimental_constrained_fma, {Factor1->getType()}, 1083 {Factor1, Factor2, Summand}, FMFSource, Name); 1084 } 1085 1086 return CreateIntrinsic(Intrinsic::fma, {Factor1->getType()}, 1087 {Factor1, Factor2, Summand}, FMFSource, Name); 1088 } 1089 1090 /// Create a call to the arithmetic_fence intrinsic. 1091 CallInst *CreateArithmeticFence(Value *Val, Type *DstType, 1092 const Twine &Name = "") { 1093 return CreateIntrinsic(Intrinsic::arithmetic_fence, DstType, Val, nullptr, 1094 Name); 1095 } 1096 1097 /// Create a call to the vector.extract intrinsic. 1098 CallInst *CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, 1099 const Twine &Name = "") { 1100 return CreateIntrinsic(Intrinsic::vector_extract, 1101 {DstType, SrcVec->getType()}, {SrcVec, Idx}, nullptr, 1102 Name); 1103 } 1104 1105 /// Create a call to the vector.extract intrinsic. 1106 CallInst *CreateExtractVector(Type *DstType, Value *SrcVec, uint64_t Idx, 1107 const Twine &Name = "") { 1108 return CreateExtractVector(DstType, SrcVec, getInt64(Idx), Name); 1109 } 1110 1111 /// Create a call to the vector.insert intrinsic. 1112 CallInst *CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec, 1113 Value *Idx, const Twine &Name = "") { 1114 return CreateIntrinsic(Intrinsic::vector_insert, 1115 {DstType, SubVec->getType()}, {SrcVec, SubVec, Idx}, 1116 nullptr, Name); 1117 } 1118 1119 /// Create a call to the vector.extract intrinsic. 1120 CallInst *CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec, 1121 uint64_t Idx, const Twine &Name = "") { 1122 return CreateInsertVector(DstType, SrcVec, SubVec, getInt64(Idx), Name); 1123 } 1124 1125 /// Create a call to llvm.stacksave 1126 CallInst *CreateStackSave(const Twine &Name = "") { 1127 const DataLayout &DL = BB->getDataLayout(); 1128 return CreateIntrinsic(Intrinsic::stacksave, {DL.getAllocaPtrType(Context)}, 1129 {}, nullptr, Name); 1130 } 1131 1132 /// Create a call to llvm.stackrestore 1133 CallInst *CreateStackRestore(Value *Ptr, const Twine &Name = "") { 1134 return CreateIntrinsic(Intrinsic::stackrestore, {Ptr->getType()}, {Ptr}, 1135 nullptr, Name); 1136 } 1137 1138 /// Create a call to llvm.experimental_cttz_elts 1139 Value *CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, 1140 bool ZeroIsPoison = true, 1141 const Twine &Name = "") { 1142 return CreateIntrinsic(Intrinsic::experimental_cttz_elts, 1143 {ResTy, Mask->getType()}, 1144 {Mask, getInt1(ZeroIsPoison)}, nullptr, Name); 1145 } 1146 1147 private: 1148 /// Create a call to a masked intrinsic with given Id. 1149 CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops, 1150 ArrayRef<Type *> OverloadedTypes, 1151 const Twine &Name = ""); 1152 1153 //===--------------------------------------------------------------------===// 1154 // Instruction creation methods: Terminators 1155 //===--------------------------------------------------------------------===// 1156 1157 private: 1158 /// Helper to add branch weight and unpredictable metadata onto an 1159 /// instruction. 1160 /// \returns The annotated instruction. 1161 template <typename InstTy> addBranchMetadata(InstTy * I,MDNode * Weights,MDNode * Unpredictable)1162 InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) { 1163 if (Weights) 1164 I->setMetadata(LLVMContext::MD_prof, Weights); 1165 if (Unpredictable) 1166 I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable); 1167 return I; 1168 } 1169 1170 public: 1171 /// Create a 'ret void' instruction. CreateRetVoid()1172 ReturnInst *CreateRetVoid() { 1173 return Insert(ReturnInst::Create(Context)); 1174 } 1175 1176 /// Create a 'ret <val>' instruction. CreateRet(Value * V)1177 ReturnInst *CreateRet(Value *V) { 1178 return Insert(ReturnInst::Create(Context, V)); 1179 } 1180 1181 /// Create a sequence of N insertvalue instructions, 1182 /// with one Value from the retVals array each, that build a aggregate 1183 /// return value one value at a time, and a ret instruction to return 1184 /// the resulting aggregate value. 1185 /// 1186 /// This is a convenience function for code that uses aggregate return values 1187 /// as a vehicle for having multiple return values. CreateAggregateRet(Value * const * retVals,unsigned N)1188 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) { 1189 Value *V = PoisonValue::get(getCurrentFunctionReturnType()); 1190 for (unsigned i = 0; i != N; ++i) 1191 V = CreateInsertValue(V, retVals[i], i, "mrv"); 1192 return Insert(ReturnInst::Create(Context, V)); 1193 } 1194 1195 /// Create an unconditional 'br label X' instruction. CreateBr(BasicBlock * Dest)1196 BranchInst *CreateBr(BasicBlock *Dest) { 1197 return Insert(BranchInst::Create(Dest)); 1198 } 1199 1200 /// Create a conditional 'br Cond, TrueDest, FalseDest' 1201 /// instruction. 1202 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, 1203 MDNode *BranchWeights = nullptr, 1204 MDNode *Unpredictable = nullptr) { 1205 return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond), 1206 BranchWeights, Unpredictable)); 1207 } 1208 1209 /// Create a conditional 'br Cond, TrueDest, FalseDest' 1210 /// instruction. Copy branch meta data if available. CreateCondBr(Value * Cond,BasicBlock * True,BasicBlock * False,Instruction * MDSrc)1211 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, 1212 Instruction *MDSrc) { 1213 BranchInst *Br = BranchInst::Create(True, False, Cond); 1214 if (MDSrc) { 1215 unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable, 1216 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg}; 1217 Br->copyMetadata(*MDSrc, WL); 1218 } 1219 return Insert(Br); 1220 } 1221 1222 /// Create a switch instruction with the specified value, default dest, 1223 /// and with a hint for the number of cases that will be added (for efficient 1224 /// allocation). 1225 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10, 1226 MDNode *BranchWeights = nullptr, 1227 MDNode *Unpredictable = nullptr) { 1228 return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases), 1229 BranchWeights, Unpredictable)); 1230 } 1231 1232 /// Create an indirect branch instruction with the specified address 1233 /// operand, with an optional hint for the number of destinations that will be 1234 /// added (for efficient allocation). 1235 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) { 1236 return Insert(IndirectBrInst::Create(Addr, NumDests)); 1237 } 1238 1239 /// Create an invoke instruction. 1240 InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee, 1241 BasicBlock *NormalDest, BasicBlock *UnwindDest, 1242 ArrayRef<Value *> Args, 1243 ArrayRef<OperandBundleDef> OpBundles, 1244 const Twine &Name = "") { 1245 InvokeInst *II = 1246 InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args, OpBundles); 1247 if (IsFPConstrained) 1248 setConstrainedFPCallAttr(II); 1249 return Insert(II, Name); 1250 } 1251 InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee, 1252 BasicBlock *NormalDest, BasicBlock *UnwindDest, 1253 ArrayRef<Value *> Args = {}, 1254 const Twine &Name = "") { 1255 InvokeInst *II = 1256 InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args); 1257 if (IsFPConstrained) 1258 setConstrainedFPCallAttr(II); 1259 return Insert(II, Name); 1260 } 1261 1262 InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest, 1263 BasicBlock *UnwindDest, ArrayRef<Value *> Args, 1264 ArrayRef<OperandBundleDef> OpBundles, 1265 const Twine &Name = "") { 1266 return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(), 1267 NormalDest, UnwindDest, Args, OpBundles, Name); 1268 } 1269 1270 InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest, 1271 BasicBlock *UnwindDest, ArrayRef<Value *> Args = {}, 1272 const Twine &Name = "") { 1273 return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(), 1274 NormalDest, UnwindDest, Args, Name); 1275 } 1276 1277 /// \brief Create a callbr instruction. 1278 CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee, 1279 BasicBlock *DefaultDest, 1280 ArrayRef<BasicBlock *> IndirectDests, 1281 ArrayRef<Value *> Args = {}, 1282 const Twine &Name = "") { 1283 return Insert(CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, 1284 Args), Name); 1285 } 1286 CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee, 1287 BasicBlock *DefaultDest, 1288 ArrayRef<BasicBlock *> IndirectDests, 1289 ArrayRef<Value *> Args, 1290 ArrayRef<OperandBundleDef> OpBundles, 1291 const Twine &Name = "") { 1292 return Insert( 1293 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args, 1294 OpBundles), Name); 1295 } 1296 1297 CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest, 1298 ArrayRef<BasicBlock *> IndirectDests, 1299 ArrayRef<Value *> Args = {}, 1300 const Twine &Name = "") { 1301 return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(), 1302 DefaultDest, IndirectDests, Args, Name); 1303 } 1304 CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest, 1305 ArrayRef<BasicBlock *> IndirectDests, 1306 ArrayRef<Value *> Args, 1307 ArrayRef<OperandBundleDef> OpBundles, 1308 const Twine &Name = "") { 1309 return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(), 1310 DefaultDest, IndirectDests, Args, Name); 1311 } 1312 CreateResume(Value * Exn)1313 ResumeInst *CreateResume(Value *Exn) { 1314 return Insert(ResumeInst::Create(Exn)); 1315 } 1316 1317 CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad, 1318 BasicBlock *UnwindBB = nullptr) { 1319 return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB)); 1320 } 1321 1322 CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB, 1323 unsigned NumHandlers, 1324 const Twine &Name = "") { 1325 return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers), 1326 Name); 1327 } 1328 1329 CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args, 1330 const Twine &Name = "") { 1331 return Insert(CatchPadInst::Create(ParentPad, Args), Name); 1332 } 1333 1334 CleanupPadInst *CreateCleanupPad(Value *ParentPad, 1335 ArrayRef<Value *> Args = {}, 1336 const Twine &Name = "") { 1337 return Insert(CleanupPadInst::Create(ParentPad, Args), Name); 1338 } 1339 CreateCatchRet(CatchPadInst * CatchPad,BasicBlock * BB)1340 CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) { 1341 return Insert(CatchReturnInst::Create(CatchPad, BB)); 1342 } 1343 CreateUnreachable()1344 UnreachableInst *CreateUnreachable() { 1345 return Insert(new UnreachableInst(Context)); 1346 } 1347 1348 //===--------------------------------------------------------------------===// 1349 // Instruction creation methods: Binary Operators 1350 //===--------------------------------------------------------------------===// 1351 private: CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,Value * LHS,Value * RHS,const Twine & Name,bool HasNUW,bool HasNSW)1352 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc, 1353 Value *LHS, Value *RHS, 1354 const Twine &Name, 1355 bool HasNUW, bool HasNSW) { 1356 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name); 1357 if (HasNUW) BO->setHasNoUnsignedWrap(); 1358 if (HasNSW) BO->setHasNoSignedWrap(); 1359 return BO; 1360 } 1361 setFPAttrs(Instruction * I,MDNode * FPMD,FastMathFlags FMF)1362 Instruction *setFPAttrs(Instruction *I, MDNode *FPMD, 1363 FastMathFlags FMF) const { 1364 if (!FPMD) 1365 FPMD = DefaultFPMathTag; 1366 if (FPMD) 1367 I->setMetadata(LLVMContext::MD_fpmath, FPMD); 1368 I->setFastMathFlags(FMF); 1369 return I; 1370 } 1371 getConstrainedFPRounding(std::optional<RoundingMode> Rounding)1372 Value *getConstrainedFPRounding(std::optional<RoundingMode> Rounding) { 1373 RoundingMode UseRounding = DefaultConstrainedRounding; 1374 1375 if (Rounding) 1376 UseRounding = *Rounding; 1377 1378 std::optional<StringRef> RoundingStr = 1379 convertRoundingModeToStr(UseRounding); 1380 assert(RoundingStr && "Garbage strict rounding mode!"); 1381 auto *RoundingMDS = MDString::get(Context, *RoundingStr); 1382 1383 return MetadataAsValue::get(Context, RoundingMDS); 1384 } 1385 getConstrainedFPExcept(std::optional<fp::ExceptionBehavior> Except)1386 Value *getConstrainedFPExcept(std::optional<fp::ExceptionBehavior> Except) { 1387 std::optional<StringRef> ExceptStr = convertExceptionBehaviorToStr( 1388 Except.value_or(DefaultConstrainedExcept)); 1389 assert(ExceptStr && "Garbage strict exception behavior!"); 1390 auto *ExceptMDS = MDString::get(Context, *ExceptStr); 1391 1392 return MetadataAsValue::get(Context, ExceptMDS); 1393 } 1394 getConstrainedFPPredicate(CmpInst::Predicate Predicate)1395 Value *getConstrainedFPPredicate(CmpInst::Predicate Predicate) { 1396 assert(CmpInst::isFPPredicate(Predicate) && 1397 Predicate != CmpInst::FCMP_FALSE && 1398 Predicate != CmpInst::FCMP_TRUE && 1399 "Invalid constrained FP comparison predicate!"); 1400 1401 StringRef PredicateStr = CmpInst::getPredicateName(Predicate); 1402 auto *PredicateMDS = MDString::get(Context, PredicateStr); 1403 1404 return MetadataAsValue::get(Context, PredicateMDS); 1405 } 1406 1407 public: 1408 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "", 1409 bool HasNUW = false, bool HasNSW = false) { 1410 if (Value *V = 1411 Folder.FoldNoWrapBinOp(Instruction::Add, LHS, RHS, HasNUW, HasNSW)) 1412 return V; 1413 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name, HasNUW, 1414 HasNSW); 1415 } 1416 1417 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") { 1418 return CreateAdd(LHS, RHS, Name, false, true); 1419 } 1420 1421 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") { 1422 return CreateAdd(LHS, RHS, Name, true, false); 1423 } 1424 1425 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "", 1426 bool HasNUW = false, bool HasNSW = false) { 1427 if (Value *V = 1428 Folder.FoldNoWrapBinOp(Instruction::Sub, LHS, RHS, HasNUW, HasNSW)) 1429 return V; 1430 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name, HasNUW, 1431 HasNSW); 1432 } 1433 1434 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") { 1435 return CreateSub(LHS, RHS, Name, false, true); 1436 } 1437 1438 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") { 1439 return CreateSub(LHS, RHS, Name, true, false); 1440 } 1441 1442 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "", 1443 bool HasNUW = false, bool HasNSW = false) { 1444 if (Value *V = 1445 Folder.FoldNoWrapBinOp(Instruction::Mul, LHS, RHS, HasNUW, HasNSW)) 1446 return V; 1447 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name, HasNUW, 1448 HasNSW); 1449 } 1450 1451 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") { 1452 return CreateMul(LHS, RHS, Name, false, true); 1453 } 1454 1455 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") { 1456 return CreateMul(LHS, RHS, Name, true, false); 1457 } 1458 1459 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "", 1460 bool isExact = false) { 1461 if (Value *V = Folder.FoldExactBinOp(Instruction::UDiv, LHS, RHS, isExact)) 1462 return V; 1463 if (!isExact) 1464 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name); 1465 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name); 1466 } 1467 1468 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") { 1469 return CreateUDiv(LHS, RHS, Name, true); 1470 } 1471 1472 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "", 1473 bool isExact = false) { 1474 if (Value *V = Folder.FoldExactBinOp(Instruction::SDiv, LHS, RHS, isExact)) 1475 return V; 1476 if (!isExact) 1477 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name); 1478 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name); 1479 } 1480 1481 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") { 1482 return CreateSDiv(LHS, RHS, Name, true); 1483 } 1484 1485 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") { 1486 if (Value *V = Folder.FoldBinOp(Instruction::URem, LHS, RHS)) 1487 return V; 1488 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name); 1489 } 1490 1491 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") { 1492 if (Value *V = Folder.FoldBinOp(Instruction::SRem, LHS, RHS)) 1493 return V; 1494 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name); 1495 } 1496 1497 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "", 1498 bool HasNUW = false, bool HasNSW = false) { 1499 if (Value *V = 1500 Folder.FoldNoWrapBinOp(Instruction::Shl, LHS, RHS, HasNUW, HasNSW)) 1501 return V; 1502 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name, 1503 HasNUW, HasNSW); 1504 } 1505 1506 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "", 1507 bool HasNUW = false, bool HasNSW = false) { 1508 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name, 1509 HasNUW, HasNSW); 1510 } 1511 1512 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "", 1513 bool HasNUW = false, bool HasNSW = false) { 1514 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name, 1515 HasNUW, HasNSW); 1516 } 1517 1518 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "", 1519 bool isExact = false) { 1520 if (Value *V = Folder.FoldExactBinOp(Instruction::LShr, LHS, RHS, isExact)) 1521 return V; 1522 if (!isExact) 1523 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name); 1524 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name); 1525 } 1526 1527 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "", 1528 bool isExact = false) { 1529 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact); 1530 } 1531 1532 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "", 1533 bool isExact = false) { 1534 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact); 1535 } 1536 1537 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "", 1538 bool isExact = false) { 1539 if (Value *V = Folder.FoldExactBinOp(Instruction::AShr, LHS, RHS, isExact)) 1540 return V; 1541 if (!isExact) 1542 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name); 1543 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name); 1544 } 1545 1546 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "", 1547 bool isExact = false) { 1548 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact); 1549 } 1550 1551 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "", 1552 bool isExact = false) { 1553 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact); 1554 } 1555 1556 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") { 1557 if (auto *V = Folder.FoldBinOp(Instruction::And, LHS, RHS)) 1558 return V; 1559 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name); 1560 } 1561 1562 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") { 1563 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1564 } 1565 1566 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") { 1567 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1568 } 1569 CreateAnd(ArrayRef<Value * > Ops)1570 Value *CreateAnd(ArrayRef<Value*> Ops) { 1571 assert(!Ops.empty()); 1572 Value *Accum = Ops[0]; 1573 for (unsigned i = 1; i < Ops.size(); i++) 1574 Accum = CreateAnd(Accum, Ops[i]); 1575 return Accum; 1576 } 1577 1578 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "", 1579 bool IsDisjoint = false) { 1580 if (auto *V = Folder.FoldBinOp(Instruction::Or, LHS, RHS)) 1581 return V; 1582 return Insert( 1583 IsDisjoint ? BinaryOperator::CreateDisjoint(Instruction::Or, LHS, RHS) 1584 : BinaryOperator::CreateOr(LHS, RHS), 1585 Name); 1586 } 1587 1588 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") { 1589 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1590 } 1591 1592 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") { 1593 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1594 } 1595 CreateOr(ArrayRef<Value * > Ops)1596 Value *CreateOr(ArrayRef<Value*> Ops) { 1597 assert(!Ops.empty()); 1598 Value *Accum = Ops[0]; 1599 for (unsigned i = 1; i < Ops.size(); i++) 1600 Accum = CreateOr(Accum, Ops[i]); 1601 return Accum; 1602 } 1603 1604 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") { 1605 if (Value *V = Folder.FoldBinOp(Instruction::Xor, LHS, RHS)) 1606 return V; 1607 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name); 1608 } 1609 1610 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") { 1611 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1612 } 1613 1614 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") { 1615 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name); 1616 } 1617 1618 Value *CreateFAdd(Value *L, Value *R, const Twine &Name = "", 1619 MDNode *FPMD = nullptr) { 1620 return CreateFAddFMF(L, R, {}, Name, FPMD); 1621 } 1622 1623 Value *CreateFAddFMF(Value *L, Value *R, FMFSource FMFSource, 1624 const Twine &Name = "", MDNode *FPMD = nullptr) { 1625 if (IsFPConstrained) 1626 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd, 1627 L, R, FMFSource, Name, FPMD); 1628 1629 if (Value *V = 1630 Folder.FoldBinOpFMF(Instruction::FAdd, L, R, FMFSource.get(FMF))) 1631 return V; 1632 Instruction *I = 1633 setFPAttrs(BinaryOperator::CreateFAdd(L, R), FPMD, FMFSource.get(FMF)); 1634 return Insert(I, Name); 1635 } 1636 1637 Value *CreateFSub(Value *L, Value *R, const Twine &Name = "", 1638 MDNode *FPMD = nullptr) { 1639 return CreateFSubFMF(L, R, {}, Name, FPMD); 1640 } 1641 1642 Value *CreateFSubFMF(Value *L, Value *R, FMFSource FMFSource, 1643 const Twine &Name = "", MDNode *FPMD = nullptr) { 1644 if (IsFPConstrained) 1645 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub, 1646 L, R, FMFSource, Name, FPMD); 1647 1648 if (Value *V = 1649 Folder.FoldBinOpFMF(Instruction::FSub, L, R, FMFSource.get(FMF))) 1650 return V; 1651 Instruction *I = 1652 setFPAttrs(BinaryOperator::CreateFSub(L, R), FPMD, FMFSource.get(FMF)); 1653 return Insert(I, Name); 1654 } 1655 1656 Value *CreateFMul(Value *L, Value *R, const Twine &Name = "", 1657 MDNode *FPMD = nullptr) { 1658 return CreateFMulFMF(L, R, {}, Name, FPMD); 1659 } 1660 1661 Value *CreateFMulFMF(Value *L, Value *R, FMFSource FMFSource, 1662 const Twine &Name = "", MDNode *FPMD = nullptr) { 1663 if (IsFPConstrained) 1664 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul, 1665 L, R, FMFSource, Name, FPMD); 1666 1667 if (Value *V = 1668 Folder.FoldBinOpFMF(Instruction::FMul, L, R, FMFSource.get(FMF))) 1669 return V; 1670 Instruction *I = 1671 setFPAttrs(BinaryOperator::CreateFMul(L, R), FPMD, FMFSource.get(FMF)); 1672 return Insert(I, Name); 1673 } 1674 1675 Value *CreateFDiv(Value *L, Value *R, const Twine &Name = "", 1676 MDNode *FPMD = nullptr) { 1677 return CreateFDivFMF(L, R, {}, Name, FPMD); 1678 } 1679 1680 Value *CreateFDivFMF(Value *L, Value *R, FMFSource FMFSource, 1681 const Twine &Name = "", MDNode *FPMD = nullptr) { 1682 if (IsFPConstrained) 1683 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv, 1684 L, R, FMFSource, Name, FPMD); 1685 1686 if (Value *V = 1687 Folder.FoldBinOpFMF(Instruction::FDiv, L, R, FMFSource.get(FMF))) 1688 return V; 1689 Instruction *I = 1690 setFPAttrs(BinaryOperator::CreateFDiv(L, R), FPMD, FMFSource.get(FMF)); 1691 return Insert(I, Name); 1692 } 1693 1694 Value *CreateFRem(Value *L, Value *R, const Twine &Name = "", 1695 MDNode *FPMD = nullptr) { 1696 return CreateFRemFMF(L, R, {}, Name, FPMD); 1697 } 1698 1699 Value *CreateFRemFMF(Value *L, Value *R, FMFSource FMFSource, 1700 const Twine &Name = "", MDNode *FPMD = nullptr) { 1701 if (IsFPConstrained) 1702 return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem, 1703 L, R, FMFSource, Name, FPMD); 1704 1705 if (Value *V = 1706 Folder.FoldBinOpFMF(Instruction::FRem, L, R, FMFSource.get(FMF))) 1707 return V; 1708 Instruction *I = 1709 setFPAttrs(BinaryOperator::CreateFRem(L, R), FPMD, FMFSource.get(FMF)); 1710 return Insert(I, Name); 1711 } 1712 1713 Value *CreateBinOp(Instruction::BinaryOps Opc, 1714 Value *LHS, Value *RHS, const Twine &Name = "", 1715 MDNode *FPMathTag = nullptr) { 1716 return CreateBinOpFMF(Opc, LHS, RHS, {}, Name, FPMathTag); 1717 } 1718 1719 Value *CreateBinOpFMF(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, 1720 FMFSource FMFSource, const Twine &Name = "", 1721 MDNode *FPMathTag = nullptr) { 1722 if (Value *V = Folder.FoldBinOp(Opc, LHS, RHS)) 1723 return V; 1724 Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS); 1725 if (isa<FPMathOperator>(BinOp)) 1726 setFPAttrs(BinOp, FPMathTag, FMFSource.get(FMF)); 1727 return Insert(BinOp, Name); 1728 } 1729 1730 Value *CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name = "") { 1731 assert(Cond2->getType()->isIntOrIntVectorTy(1)); 1732 return CreateSelect(Cond1, Cond2, 1733 ConstantInt::getNullValue(Cond2->getType()), Name); 1734 } 1735 1736 Value *CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name = "") { 1737 assert(Cond2->getType()->isIntOrIntVectorTy(1)); 1738 return CreateSelect(Cond1, ConstantInt::getAllOnesValue(Cond2->getType()), 1739 Cond2, Name); 1740 } 1741 1742 Value *CreateLogicalOp(Instruction::BinaryOps Opc, Value *Cond1, Value *Cond2, 1743 const Twine &Name = "") { 1744 switch (Opc) { 1745 case Instruction::And: 1746 return CreateLogicalAnd(Cond1, Cond2, Name); 1747 case Instruction::Or: 1748 return CreateLogicalOr(Cond1, Cond2, Name); 1749 default: 1750 break; 1751 } 1752 llvm_unreachable("Not a logical operation."); 1753 } 1754 1755 // NOTE: this is sequential, non-commutative, ordered reduction! CreateLogicalOr(ArrayRef<Value * > Ops)1756 Value *CreateLogicalOr(ArrayRef<Value *> Ops) { 1757 assert(!Ops.empty()); 1758 Value *Accum = Ops[0]; 1759 for (unsigned i = 1; i < Ops.size(); i++) 1760 Accum = CreateLogicalOr(Accum, Ops[i]); 1761 return Accum; 1762 } 1763 1764 /// This function is like @ref CreateIntrinsic for constrained fp 1765 /// intrinsics. It sets the rounding mode and exception behavior of 1766 /// the created intrinsic call according to \p Rounding and \p 1767 /// Except and it sets \p FPMathTag as the 'fpmath' metadata, using 1768 /// defaults if a value equals nullopt/null. 1769 LLVM_ABI CallInst *CreateConstrainedFPIntrinsic( 1770 Intrinsic::ID ID, ArrayRef<Type *> Types, ArrayRef<Value *> Args, 1771 FMFSource FMFSource, const Twine &Name, MDNode *FPMathTag = nullptr, 1772 std::optional<RoundingMode> Rounding = std::nullopt, 1773 std::optional<fp::ExceptionBehavior> Except = std::nullopt); 1774 1775 LLVM_ABI CallInst *CreateConstrainedFPBinOp( 1776 Intrinsic::ID ID, Value *L, Value *R, FMFSource FMFSource = {}, 1777 const Twine &Name = "", MDNode *FPMathTag = nullptr, 1778 std::optional<RoundingMode> Rounding = std::nullopt, 1779 std::optional<fp::ExceptionBehavior> Except = std::nullopt); 1780 1781 LLVM_ABI CallInst *CreateConstrainedFPUnroundedBinOp( 1782 Intrinsic::ID ID, Value *L, Value *R, FMFSource FMFSource = {}, 1783 const Twine &Name = "", MDNode *FPMathTag = nullptr, 1784 std::optional<fp::ExceptionBehavior> Except = std::nullopt); 1785 1786 Value *CreateNeg(Value *V, const Twine &Name = "", bool HasNSW = false) { 1787 return CreateSub(Constant::getNullValue(V->getType()), V, Name, 1788 /*HasNUW=*/0, HasNSW); 1789 } 1790 1791 Value *CreateNSWNeg(Value *V, const Twine &Name = "") { 1792 return CreateNeg(V, Name, /*HasNSW=*/true); 1793 } 1794 1795 Value *CreateFNeg(Value *V, const Twine &Name = "", 1796 MDNode *FPMathTag = nullptr) { 1797 return CreateFNegFMF(V, {}, Name, FPMathTag); 1798 } 1799 1800 Value *CreateFNegFMF(Value *V, FMFSource FMFSource, const Twine &Name = "", 1801 MDNode *FPMathTag = nullptr) { 1802 if (Value *Res = 1803 Folder.FoldUnOpFMF(Instruction::FNeg, V, FMFSource.get(FMF))) 1804 return Res; 1805 return Insert( 1806 setFPAttrs(UnaryOperator::CreateFNeg(V), FPMathTag, FMFSource.get(FMF)), 1807 Name); 1808 } 1809 1810 Value *CreateNot(Value *V, const Twine &Name = "") { 1811 return CreateXor(V, Constant::getAllOnesValue(V->getType()), Name); 1812 } 1813 1814 Value *CreateUnOp(Instruction::UnaryOps Opc, 1815 Value *V, const Twine &Name = "", 1816 MDNode *FPMathTag = nullptr) { 1817 if (Value *Res = Folder.FoldUnOpFMF(Opc, V, FMF)) 1818 return Res; 1819 Instruction *UnOp = UnaryOperator::Create(Opc, V); 1820 if (isa<FPMathOperator>(UnOp)) 1821 setFPAttrs(UnOp, FPMathTag, FMF); 1822 return Insert(UnOp, Name); 1823 } 1824 1825 /// Create either a UnaryOperator or BinaryOperator depending on \p Opc. 1826 /// Correct number of operands must be passed accordingly. 1827 LLVM_ABI Value *CreateNAryOp(unsigned Opc, ArrayRef<Value *> Ops, 1828 const Twine &Name = "", 1829 MDNode *FPMathTag = nullptr); 1830 1831 //===--------------------------------------------------------------------===// 1832 // Instruction creation methods: Memory Instructions 1833 //===--------------------------------------------------------------------===// 1834 1835 AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace, 1836 Value *ArraySize = nullptr, const Twine &Name = "") { 1837 const DataLayout &DL = BB->getDataLayout(); 1838 Align AllocaAlign = DL.getPrefTypeAlign(Ty); 1839 return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name); 1840 } 1841 1842 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr, 1843 const Twine &Name = "") { 1844 const DataLayout &DL = BB->getDataLayout(); 1845 Align AllocaAlign = DL.getPrefTypeAlign(Ty); 1846 unsigned AddrSpace = DL.getAllocaAddrSpace(); 1847 return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name); 1848 } 1849 1850 /// Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of 1851 /// converting the string to 'bool' for the isVolatile parameter. CreateLoad(Type * Ty,Value * Ptr,const char * Name)1852 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const char *Name) { 1853 return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), Name); 1854 } 1855 1856 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") { 1857 return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), Name); 1858 } 1859 1860 LoadInst *CreateLoad(Type *Ty, Value *Ptr, bool isVolatile, 1861 const Twine &Name = "") { 1862 return CreateAlignedLoad(Ty, Ptr, MaybeAlign(), isVolatile, Name); 1863 } 1864 1865 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) { 1866 return CreateAlignedStore(Val, Ptr, MaybeAlign(), isVolatile); 1867 } 1868 CreateAlignedLoad(Type * Ty,Value * Ptr,MaybeAlign Align,const char * Name)1869 LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, 1870 const char *Name) { 1871 return CreateAlignedLoad(Ty, Ptr, Align, /*isVolatile*/false, Name); 1872 } 1873 1874 LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, 1875 const Twine &Name = "") { 1876 return CreateAlignedLoad(Ty, Ptr, Align, /*isVolatile*/false, Name); 1877 } 1878 1879 LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, 1880 bool isVolatile, const Twine &Name = "") { 1881 if (!Align) { 1882 const DataLayout &DL = BB->getDataLayout(); 1883 Align = DL.getABITypeAlign(Ty); 1884 } 1885 return Insert(new LoadInst(Ty, Ptr, Twine(), isVolatile, *Align), Name); 1886 } 1887 1888 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, 1889 bool isVolatile = false) { 1890 if (!Align) { 1891 const DataLayout &DL = BB->getDataLayout(); 1892 Align = DL.getABITypeAlign(Val->getType()); 1893 } 1894 return Insert(new StoreInst(Val, Ptr, isVolatile, *Align)); 1895 } 1896 FenceInst *CreateFence(AtomicOrdering Ordering, 1897 SyncScope::ID SSID = SyncScope::System, 1898 const Twine &Name = "") { 1899 return Insert(new FenceInst(Context, Ordering, SSID), Name); 1900 } 1901 1902 AtomicCmpXchgInst * 1903 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New, MaybeAlign Align, 1904 AtomicOrdering SuccessOrdering, 1905 AtomicOrdering FailureOrdering, 1906 SyncScope::ID SSID = SyncScope::System) { 1907 if (!Align) { 1908 const DataLayout &DL = BB->getDataLayout(); 1909 Align = llvm::Align(DL.getTypeStoreSize(New->getType())); 1910 } 1911 1912 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, *Align, SuccessOrdering, 1913 FailureOrdering, SSID)); 1914 } 1915 1916 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, 1917 Value *Val, MaybeAlign Align, 1918 AtomicOrdering Ordering, 1919 SyncScope::ID SSID = SyncScope::System) { 1920 if (!Align) { 1921 const DataLayout &DL = BB->getDataLayout(); 1922 Align = llvm::Align(DL.getTypeStoreSize(Val->getType())); 1923 } 1924 1925 return Insert(new AtomicRMWInst(Op, Ptr, Val, *Align, Ordering, SSID)); 1926 } 1927 1928 Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList, 1929 const Twine &Name = "", 1930 GEPNoWrapFlags NW = GEPNoWrapFlags::none()) { 1931 if (auto *V = Folder.FoldGEP(Ty, Ptr, IdxList, NW)) 1932 return V; 1933 return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList, NW), Name); 1934 } 1935 1936 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList, 1937 const Twine &Name = "") { 1938 return CreateGEP(Ty, Ptr, IdxList, Name, GEPNoWrapFlags::inBounds()); 1939 } 1940 1941 Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, 1942 const Twine &Name = "") { 1943 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0); 1944 1945 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, GEPNoWrapFlags::none())) 1946 return V; 1947 1948 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name); 1949 } 1950 1951 Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, 1952 const Twine &Name = "") { 1953 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0); 1954 1955 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, GEPNoWrapFlags::inBounds())) 1956 return V; 1957 1958 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name); 1959 } 1960 1961 Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, 1962 const Twine &Name = "", 1963 GEPNoWrapFlags NWFlags = GEPNoWrapFlags::none()) { 1964 Value *Idxs[] = { 1965 ConstantInt::get(Type::getInt32Ty(Context), Idx0), 1966 ConstantInt::get(Type::getInt32Ty(Context), Idx1) 1967 }; 1968 1969 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, NWFlags)) 1970 return V; 1971 1972 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs, NWFlags), Name); 1973 } 1974 1975 Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, 1976 unsigned Idx1, const Twine &Name = "") { 1977 Value *Idxs[] = { 1978 ConstantInt::get(Type::getInt32Ty(Context), Idx0), 1979 ConstantInt::get(Type::getInt32Ty(Context), Idx1) 1980 }; 1981 1982 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, GEPNoWrapFlags::inBounds())) 1983 return V; 1984 1985 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name); 1986 } 1987 1988 Value *CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, 1989 const Twine &Name = "") { 1990 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0); 1991 1992 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, GEPNoWrapFlags::none())) 1993 return V; 1994 1995 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name); 1996 } 1997 1998 Value *CreateConstInBoundsGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, 1999 const Twine &Name = "") { 2000 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0); 2001 2002 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idx, GEPNoWrapFlags::inBounds())) 2003 return V; 2004 2005 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name); 2006 } 2007 2008 Value *CreateConstGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1, 2009 const Twine &Name = "") { 2010 Value *Idxs[] = { 2011 ConstantInt::get(Type::getInt64Ty(Context), Idx0), 2012 ConstantInt::get(Type::getInt64Ty(Context), Idx1) 2013 }; 2014 2015 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, GEPNoWrapFlags::none())) 2016 return V; 2017 2018 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name); 2019 } 2020 2021 Value *CreateConstInBoundsGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, 2022 uint64_t Idx1, const Twine &Name = "") { 2023 Value *Idxs[] = { 2024 ConstantInt::get(Type::getInt64Ty(Context), Idx0), 2025 ConstantInt::get(Type::getInt64Ty(Context), Idx1) 2026 }; 2027 2028 if (auto *V = Folder.FoldGEP(Ty, Ptr, Idxs, GEPNoWrapFlags::inBounds())) 2029 return V; 2030 2031 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name); 2032 } 2033 2034 Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx, 2035 const Twine &Name = "") { 2036 GEPNoWrapFlags NWFlags = 2037 GEPNoWrapFlags::inBounds() | GEPNoWrapFlags::noUnsignedWrap(); 2038 return CreateConstGEP2_32(Ty, Ptr, 0, Idx, Name, NWFlags); 2039 } 2040 2041 Value *CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name = "", 2042 GEPNoWrapFlags NW = GEPNoWrapFlags::none()) { 2043 return CreateGEP(getInt8Ty(), Ptr, Offset, Name, NW); 2044 } 2045 2046 Value *CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, 2047 const Twine &Name = "") { 2048 return CreateGEP(getInt8Ty(), Ptr, Offset, Name, 2049 GEPNoWrapFlags::inBounds()); 2050 } 2051 2052 /// Same as CreateGlobalString, but return a pointer with "i8*" type 2053 /// instead of a pointer to array of i8. 2054 /// 2055 /// If no module is given via \p M, it is take from the insertion point basic 2056 /// block. 2057 LLVM_DEPRECATED("Use CreateGlobalString instead", "CreateGlobalString") 2058 Constant *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "", 2059 unsigned AddressSpace = 0, 2060 Module *M = nullptr, bool AddNull = true) { 2061 GlobalVariable *GV = 2062 CreateGlobalString(Str, Name, AddressSpace, M, AddNull); 2063 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0); 2064 Constant *Indices[] = {Zero, Zero}; 2065 return ConstantExpr::getInBoundsGetElementPtr(GV->getValueType(), GV, 2066 Indices); 2067 } 2068 2069 //===--------------------------------------------------------------------===// 2070 // Instruction creation methods: Cast/Conversion Operators 2071 //===--------------------------------------------------------------------===// 2072 2073 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "", 2074 bool IsNUW = false, bool IsNSW = false) { 2075 if (V->getType() == DestTy) 2076 return V; 2077 if (Value *Folded = Folder.FoldCast(Instruction::Trunc, V, DestTy)) 2078 return Folded; 2079 Instruction *I = CastInst::Create(Instruction::Trunc, V, DestTy); 2080 if (IsNUW) 2081 I->setHasNoUnsignedWrap(); 2082 if (IsNSW) 2083 I->setHasNoSignedWrap(); 2084 return Insert(I, Name); 2085 } 2086 2087 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "", 2088 bool IsNonNeg = false) { 2089 if (V->getType() == DestTy) 2090 return V; 2091 if (Value *Folded = Folder.FoldCast(Instruction::ZExt, V, DestTy)) 2092 return Folded; 2093 Instruction *I = Insert(new ZExtInst(V, DestTy), Name); 2094 if (IsNonNeg) 2095 I->setNonNeg(); 2096 return I; 2097 } 2098 2099 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") { 2100 return CreateCast(Instruction::SExt, V, DestTy, Name); 2101 } 2102 2103 /// Create a ZExt or Trunc from the integer value V to DestTy. Return 2104 /// the value untouched if the type of V is already DestTy. 2105 Value *CreateZExtOrTrunc(Value *V, Type *DestTy, 2106 const Twine &Name = "") { 2107 assert(V->getType()->isIntOrIntVectorTy() && 2108 DestTy->isIntOrIntVectorTy() && 2109 "Can only zero extend/truncate integers!"); 2110 Type *VTy = V->getType(); 2111 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits()) 2112 return CreateZExt(V, DestTy, Name); 2113 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits()) 2114 return CreateTrunc(V, DestTy, Name); 2115 return V; 2116 } 2117 2118 /// Create a SExt or Trunc from the integer value V to DestTy. Return 2119 /// the value untouched if the type of V is already DestTy. 2120 Value *CreateSExtOrTrunc(Value *V, Type *DestTy, 2121 const Twine &Name = "") { 2122 assert(V->getType()->isIntOrIntVectorTy() && 2123 DestTy->isIntOrIntVectorTy() && 2124 "Can only sign extend/truncate integers!"); 2125 Type *VTy = V->getType(); 2126 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits()) 2127 return CreateSExt(V, DestTy, Name); 2128 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits()) 2129 return CreateTrunc(V, DestTy, Name); 2130 return V; 2131 } 2132 2133 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = "") { 2134 if (IsFPConstrained) 2135 return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptoui, 2136 V, DestTy, nullptr, Name); 2137 return CreateCast(Instruction::FPToUI, V, DestTy, Name); 2138 } 2139 2140 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = "") { 2141 if (IsFPConstrained) 2142 return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptosi, 2143 V, DestTy, nullptr, Name); 2144 return CreateCast(Instruction::FPToSI, V, DestTy, Name); 2145 } 2146 2147 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = "", 2148 bool IsNonNeg = false) { 2149 if (IsFPConstrained) 2150 return CreateConstrainedFPCast(Intrinsic::experimental_constrained_uitofp, 2151 V, DestTy, nullptr, Name); 2152 if (Value *Folded = Folder.FoldCast(Instruction::UIToFP, V, DestTy)) 2153 return Folded; 2154 Instruction *I = Insert(new UIToFPInst(V, DestTy), Name); 2155 if (IsNonNeg) 2156 I->setNonNeg(); 2157 return I; 2158 } 2159 2160 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){ 2161 if (IsFPConstrained) 2162 return CreateConstrainedFPCast(Intrinsic::experimental_constrained_sitofp, 2163 V, DestTy, nullptr, Name); 2164 return CreateCast(Instruction::SIToFP, V, DestTy, Name); 2165 } 2166 2167 Value *CreateFPTrunc(Value *V, Type *DestTy, const Twine &Name = "", 2168 MDNode *FPMathTag = nullptr) { 2169 return CreateFPTruncFMF(V, DestTy, {}, Name, FPMathTag); 2170 } 2171 2172 Value *CreateFPTruncFMF(Value *V, Type *DestTy, FMFSource FMFSource, 2173 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 2174 if (IsFPConstrained) 2175 return CreateConstrainedFPCast( 2176 Intrinsic::experimental_constrained_fptrunc, V, DestTy, FMFSource, 2177 Name, FPMathTag); 2178 return CreateCast(Instruction::FPTrunc, V, DestTy, Name, FPMathTag, 2179 FMFSource); 2180 } 2181 2182 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "", 2183 MDNode *FPMathTag = nullptr) { 2184 return CreateFPExtFMF(V, DestTy, {}, Name, FPMathTag); 2185 } 2186 2187 Value *CreateFPExtFMF(Value *V, Type *DestTy, FMFSource FMFSource, 2188 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 2189 if (IsFPConstrained) 2190 return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fpext, 2191 V, DestTy, FMFSource, Name, FPMathTag); 2192 return CreateCast(Instruction::FPExt, V, DestTy, Name, FPMathTag, 2193 FMFSource); 2194 } 2195 2196 Value *CreatePtrToInt(Value *V, Type *DestTy, 2197 const Twine &Name = "") { 2198 return CreateCast(Instruction::PtrToInt, V, DestTy, Name); 2199 } 2200 2201 Value *CreateIntToPtr(Value *V, Type *DestTy, 2202 const Twine &Name = "") { 2203 return CreateCast(Instruction::IntToPtr, V, DestTy, Name); 2204 } 2205 2206 Value *CreateBitCast(Value *V, Type *DestTy, 2207 const Twine &Name = "") { 2208 return CreateCast(Instruction::BitCast, V, DestTy, Name); 2209 } 2210 2211 Value *CreateAddrSpaceCast(Value *V, Type *DestTy, 2212 const Twine &Name = "") { 2213 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name); 2214 } 2215 2216 Value *CreateZExtOrBitCast(Value *V, Type *DestTy, const Twine &Name = "") { 2217 Instruction::CastOps CastOp = 2218 V->getType()->getScalarSizeInBits() == DestTy->getScalarSizeInBits() 2219 ? Instruction::BitCast 2220 : Instruction::ZExt; 2221 return CreateCast(CastOp, V, DestTy, Name); 2222 } 2223 2224 Value *CreateSExtOrBitCast(Value *V, Type *DestTy, const Twine &Name = "") { 2225 Instruction::CastOps CastOp = 2226 V->getType()->getScalarSizeInBits() == DestTy->getScalarSizeInBits() 2227 ? Instruction::BitCast 2228 : Instruction::SExt; 2229 return CreateCast(CastOp, V, DestTy, Name); 2230 } 2231 2232 Value *CreateTruncOrBitCast(Value *V, Type *DestTy, const Twine &Name = "") { 2233 Instruction::CastOps CastOp = 2234 V->getType()->getScalarSizeInBits() == DestTy->getScalarSizeInBits() 2235 ? Instruction::BitCast 2236 : Instruction::Trunc; 2237 return CreateCast(CastOp, V, DestTy, Name); 2238 } 2239 2240 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, 2241 const Twine &Name = "", MDNode *FPMathTag = nullptr, 2242 FMFSource FMFSource = {}) { 2243 if (V->getType() == DestTy) 2244 return V; 2245 if (Value *Folded = Folder.FoldCast(Op, V, DestTy)) 2246 return Folded; 2247 Instruction *Cast = CastInst::Create(Op, V, DestTy); 2248 if (isa<FPMathOperator>(Cast)) 2249 setFPAttrs(Cast, FPMathTag, FMFSource.get(FMF)); 2250 return Insert(Cast, Name); 2251 } 2252 2253 Value *CreatePointerCast(Value *V, Type *DestTy, 2254 const Twine &Name = "") { 2255 if (V->getType() == DestTy) 2256 return V; 2257 if (auto *VC = dyn_cast<Constant>(V)) 2258 return Insert(Folder.CreatePointerCast(VC, DestTy), Name); 2259 return Insert(CastInst::CreatePointerCast(V, DestTy), Name); 2260 } 2261 2262 // With opaque pointers enabled, this can be substituted with 2263 // CreateAddrSpaceCast. 2264 // TODO: Replace uses of this method and remove the method itself. 2265 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, 2266 const Twine &Name = "") { 2267 if (V->getType() == DestTy) 2268 return V; 2269 2270 if (auto *VC = dyn_cast<Constant>(V)) { 2271 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy), 2272 Name); 2273 } 2274 2275 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy), 2276 Name); 2277 } 2278 2279 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned, 2280 const Twine &Name = "") { 2281 Instruction::CastOps CastOp = 2282 V->getType()->getScalarSizeInBits() > DestTy->getScalarSizeInBits() 2283 ? Instruction::Trunc 2284 : (isSigned ? Instruction::SExt : Instruction::ZExt); 2285 return CreateCast(CastOp, V, DestTy, Name); 2286 } 2287 2288 Value *CreateBitOrPointerCast(Value *V, Type *DestTy, 2289 const Twine &Name = "") { 2290 if (V->getType() == DestTy) 2291 return V; 2292 if (V->getType()->isPtrOrPtrVectorTy() && DestTy->isIntOrIntVectorTy()) 2293 return CreatePtrToInt(V, DestTy, Name); 2294 if (V->getType()->isIntOrIntVectorTy() && DestTy->isPtrOrPtrVectorTy()) 2295 return CreateIntToPtr(V, DestTy, Name); 2296 2297 return CreateBitCast(V, DestTy, Name); 2298 } 2299 2300 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "", 2301 MDNode *FPMathTag = nullptr) { 2302 Instruction::CastOps CastOp = 2303 V->getType()->getScalarSizeInBits() > DestTy->getScalarSizeInBits() 2304 ? Instruction::FPTrunc 2305 : Instruction::FPExt; 2306 return CreateCast(CastOp, V, DestTy, Name, FPMathTag); 2307 } 2308 2309 LLVM_ABI CallInst *CreateConstrainedFPCast( 2310 Intrinsic::ID ID, Value *V, Type *DestTy, FMFSource FMFSource = {}, 2311 const Twine &Name = "", MDNode *FPMathTag = nullptr, 2312 std::optional<RoundingMode> Rounding = std::nullopt, 2313 std::optional<fp::ExceptionBehavior> Except = std::nullopt); 2314 2315 // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a 2316 // compile time error, instead of converting the string to bool for the 2317 // isSigned parameter. 2318 Value *CreateIntCast(Value *, Type *, const char *) = delete; 2319 2320 /// Cast between aggregate types that must have identical structure but may 2321 /// differ in their leaf types. The leaf values are recursively extracted, 2322 /// casted, and then reinserted into a value of type DestTy. The leaf types 2323 /// must be castable using a bitcast or ptrcast, because signedness is 2324 /// not specified. 2325 LLVM_ABI Value *CreateAggregateCast(Value *V, Type *DestTy); 2326 2327 //===--------------------------------------------------------------------===// 2328 // Instruction creation methods: Compare Instructions 2329 //===--------------------------------------------------------------------===// 2330 2331 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") { 2332 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name); 2333 } 2334 2335 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") { 2336 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name); 2337 } 2338 2339 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") { 2340 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name); 2341 } 2342 2343 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") { 2344 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name); 2345 } 2346 2347 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") { 2348 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name); 2349 } 2350 2351 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") { 2352 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name); 2353 } 2354 2355 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") { 2356 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name); 2357 } 2358 2359 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") { 2360 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name); 2361 } 2362 2363 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") { 2364 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name); 2365 } 2366 2367 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") { 2368 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name); 2369 } 2370 2371 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "", 2372 MDNode *FPMathTag = nullptr) { 2373 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag); 2374 } 2375 2376 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "", 2377 MDNode *FPMathTag = nullptr) { 2378 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag); 2379 } 2380 2381 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "", 2382 MDNode *FPMathTag = nullptr) { 2383 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag); 2384 } 2385 2386 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "", 2387 MDNode *FPMathTag = nullptr) { 2388 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag); 2389 } 2390 2391 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "", 2392 MDNode *FPMathTag = nullptr) { 2393 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag); 2394 } 2395 2396 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "", 2397 MDNode *FPMathTag = nullptr) { 2398 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag); 2399 } 2400 2401 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "", 2402 MDNode *FPMathTag = nullptr) { 2403 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag); 2404 } 2405 2406 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "", 2407 MDNode *FPMathTag = nullptr) { 2408 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag); 2409 } 2410 2411 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "", 2412 MDNode *FPMathTag = nullptr) { 2413 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag); 2414 } 2415 2416 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "", 2417 MDNode *FPMathTag = nullptr) { 2418 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag); 2419 } 2420 2421 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "", 2422 MDNode *FPMathTag = nullptr) { 2423 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag); 2424 } 2425 2426 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "", 2427 MDNode *FPMathTag = nullptr) { 2428 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag); 2429 } 2430 2431 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "", 2432 MDNode *FPMathTag = nullptr) { 2433 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag); 2434 } 2435 2436 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "", 2437 MDNode *FPMathTag = nullptr) { 2438 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag); 2439 } 2440 2441 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, 2442 const Twine &Name = "") { 2443 if (auto *V = Folder.FoldCmp(P, LHS, RHS)) 2444 return V; 2445 return Insert(new ICmpInst(P, LHS, RHS), Name); 2446 } 2447 2448 // Create a quiet floating-point comparison (i.e. one that raises an FP 2449 // exception only in the case where an input is a signaling NaN). 2450 // Note that this differs from CreateFCmpS only if IsFPConstrained is true. 2451 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, 2452 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 2453 return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, {}, false); 2454 } 2455 2456 // Create a quiet floating-point comparison (i.e. one that raises an FP 2457 // exception only in the case where an input is a signaling NaN). 2458 // Note that this differs from CreateFCmpS only if IsFPConstrained is true. 2459 Value *CreateFCmpFMF(CmpInst::Predicate P, Value *LHS, Value *RHS, 2460 FMFSource FMFSource, const Twine &Name = "", 2461 MDNode *FPMathTag = nullptr) { 2462 return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, FMFSource, false); 2463 } 2464 2465 Value *CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, 2466 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 2467 return CmpInst::isFPPredicate(Pred) 2468 ? CreateFCmp(Pred, LHS, RHS, Name, FPMathTag) 2469 : CreateICmp(Pred, LHS, RHS, Name); 2470 } 2471 2472 // Create a signaling floating-point comparison (i.e. one that raises an FP 2473 // exception whenever an input is any NaN, signaling or quiet). 2474 // Note that this differs from CreateFCmp only if IsFPConstrained is true. 2475 Value *CreateFCmpS(CmpInst::Predicate P, Value *LHS, Value *RHS, 2476 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 2477 return CreateFCmpHelper(P, LHS, RHS, Name, FPMathTag, {}, true); 2478 } 2479 2480 private: 2481 // Helper routine to create either a signaling or a quiet FP comparison. 2482 LLVM_ABI Value *CreateFCmpHelper(CmpInst::Predicate P, Value *LHS, Value *RHS, 2483 const Twine &Name, MDNode *FPMathTag, 2484 FMFSource FMFSource, bool IsSignaling); 2485 2486 public: 2487 LLVM_ABI CallInst *CreateConstrainedFPCmp( 2488 Intrinsic::ID ID, CmpInst::Predicate P, Value *L, Value *R, 2489 const Twine &Name = "", 2490 std::optional<fp::ExceptionBehavior> Except = std::nullopt); 2491 2492 //===--------------------------------------------------------------------===// 2493 // Instruction creation methods: Other Instructions 2494 //===--------------------------------------------------------------------===// 2495 2496 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues, 2497 const Twine &Name = "") { 2498 PHINode *Phi = PHINode::Create(Ty, NumReservedValues); 2499 if (isa<FPMathOperator>(Phi)) 2500 setFPAttrs(Phi, nullptr /* MDNode* */, FMF); 2501 return Insert(Phi, Name); 2502 } 2503 2504 private: 2505 CallInst *createCallHelper(Function *Callee, ArrayRef<Value *> Ops, 2506 const Twine &Name = "", FMFSource FMFSource = {}, 2507 ArrayRef<OperandBundleDef> OpBundles = {}); 2508 2509 public: 2510 CallInst *CreateCall(FunctionType *FTy, Value *Callee, 2511 ArrayRef<Value *> Args = {}, const Twine &Name = "", 2512 MDNode *FPMathTag = nullptr) { 2513 CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles); 2514 if (IsFPConstrained) 2515 setConstrainedFPCallAttr(CI); 2516 if (isa<FPMathOperator>(CI)) 2517 setFPAttrs(CI, FPMathTag, FMF); 2518 return Insert(CI, Name); 2519 } 2520 2521 CallInst *CreateCall(FunctionType *FTy, Value *Callee, ArrayRef<Value *> Args, 2522 ArrayRef<OperandBundleDef> OpBundles, 2523 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 2524 CallInst *CI = CallInst::Create(FTy, Callee, Args, OpBundles); 2525 if (IsFPConstrained) 2526 setConstrainedFPCallAttr(CI); 2527 if (isa<FPMathOperator>(CI)) 2528 setFPAttrs(CI, FPMathTag, FMF); 2529 return Insert(CI, Name); 2530 } 2531 2532 CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args = {}, 2533 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 2534 return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args, Name, 2535 FPMathTag); 2536 } 2537 2538 CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args, 2539 ArrayRef<OperandBundleDef> OpBundles, 2540 const Twine &Name = "", MDNode *FPMathTag = nullptr) { 2541 return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args, 2542 OpBundles, Name, FPMathTag); 2543 } 2544 2545 LLVM_ABI CallInst *CreateConstrainedFPCall( 2546 Function *Callee, ArrayRef<Value *> Args, const Twine &Name = "", 2547 std::optional<RoundingMode> Rounding = std::nullopt, 2548 std::optional<fp::ExceptionBehavior> Except = std::nullopt); 2549 2550 LLVM_ABI Value *CreateSelect(Value *C, Value *True, Value *False, 2551 const Twine &Name = "", 2552 Instruction *MDFrom = nullptr); 2553 LLVM_ABI Value *CreateSelectFMF(Value *C, Value *True, Value *False, 2554 FMFSource FMFSource, const Twine &Name = "", 2555 Instruction *MDFrom = nullptr); 2556 2557 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") { 2558 return Insert(new VAArgInst(List, Ty), Name); 2559 } 2560 2561 Value *CreateExtractElement(Value *Vec, Value *Idx, 2562 const Twine &Name = "") { 2563 if (Value *V = Folder.FoldExtractElement(Vec, Idx)) 2564 return V; 2565 return Insert(ExtractElementInst::Create(Vec, Idx), Name); 2566 } 2567 2568 Value *CreateExtractElement(Value *Vec, uint64_t Idx, 2569 const Twine &Name = "") { 2570 return CreateExtractElement(Vec, getInt64(Idx), Name); 2571 } 2572 2573 Value *CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, 2574 const Twine &Name = "") { 2575 return CreateInsertElement(PoisonValue::get(VecTy), NewElt, Idx, Name); 2576 } 2577 2578 Value *CreateInsertElement(Type *VecTy, Value *NewElt, uint64_t Idx, 2579 const Twine &Name = "") { 2580 return CreateInsertElement(PoisonValue::get(VecTy), NewElt, Idx, Name); 2581 } 2582 2583 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, 2584 const Twine &Name = "") { 2585 if (Value *V = Folder.FoldInsertElement(Vec, NewElt, Idx)) 2586 return V; 2587 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name); 2588 } 2589 2590 Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx, 2591 const Twine &Name = "") { 2592 return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name); 2593 } 2594 2595 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask, 2596 const Twine &Name = "") { 2597 SmallVector<int, 16> IntMask; 2598 ShuffleVectorInst::getShuffleMask(cast<Constant>(Mask), IntMask); 2599 return CreateShuffleVector(V1, V2, IntMask, Name); 2600 } 2601 2602 /// See class ShuffleVectorInst for a description of the mask representation. 2603 Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> Mask, 2604 const Twine &Name = "") { 2605 if (Value *V = Folder.FoldShuffleVector(V1, V2, Mask)) 2606 return V; 2607 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name); 2608 } 2609 2610 /// Create a unary shuffle. The second vector operand of the IR instruction 2611 /// is poison. 2612 Value *CreateShuffleVector(Value *V, ArrayRef<int> Mask, 2613 const Twine &Name = "") { 2614 return CreateShuffleVector(V, PoisonValue::get(V->getType()), Mask, Name); 2615 } 2616 2617 Value *CreateExtractValue(Value *Agg, ArrayRef<unsigned> Idxs, 2618 const Twine &Name = "") { 2619 if (auto *V = Folder.FoldExtractValue(Agg, Idxs)) 2620 return V; 2621 return Insert(ExtractValueInst::Create(Agg, Idxs), Name); 2622 } 2623 2624 Value *CreateInsertValue(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 2625 const Twine &Name = "") { 2626 if (auto *V = Folder.FoldInsertValue(Agg, Val, Idxs)) 2627 return V; 2628 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name); 2629 } 2630 2631 LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses, 2632 const Twine &Name = "") { 2633 return Insert(LandingPadInst::Create(Ty, NumClauses), Name); 2634 } 2635 2636 Value *CreateFreeze(Value *V, const Twine &Name = "") { 2637 return Insert(new FreezeInst(V), Name); 2638 } 2639 2640 //===--------------------------------------------------------------------===// 2641 // Utility creation methods 2642 //===--------------------------------------------------------------------===// 2643 2644 /// Return a boolean value testing if \p Arg == 0. 2645 Value *CreateIsNull(Value *Arg, const Twine &Name = "") { 2646 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()), Name); 2647 } 2648 2649 /// Return a boolean value testing if \p Arg != 0. 2650 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") { 2651 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()), Name); 2652 } 2653 2654 /// Return a boolean value testing if \p Arg < 0. 2655 Value *CreateIsNeg(Value *Arg, const Twine &Name = "") { 2656 return CreateICmpSLT(Arg, ConstantInt::getNullValue(Arg->getType()), Name); 2657 } 2658 2659 /// Return a boolean value testing if \p Arg > -1. 2660 Value *CreateIsNotNeg(Value *Arg, const Twine &Name = "") { 2661 return CreateICmpSGT(Arg, ConstantInt::getAllOnesValue(Arg->getType()), 2662 Name); 2663 } 2664 2665 /// Return the i64 difference between two pointer values, dividing out 2666 /// the size of the pointed-to objects. 2667 /// 2668 /// This is intended to implement C-style pointer subtraction. As such, the 2669 /// pointers must be appropriately aligned for their element types and 2670 /// pointing into the same object. 2671 LLVM_ABI Value *CreatePtrDiff(Type *ElemTy, Value *LHS, Value *RHS, 2672 const Twine &Name = ""); 2673 2674 /// Create a launder.invariant.group intrinsic call. If Ptr type is 2675 /// different from pointer to i8, it's casted to pointer to i8 in the same 2676 /// address space before call and casted back to Ptr type after call. 2677 LLVM_ABI Value *CreateLaunderInvariantGroup(Value *Ptr); 2678 2679 /// \brief Create a strip.invariant.group intrinsic call. If Ptr type is 2680 /// different from pointer to i8, it's casted to pointer to i8 in the same 2681 /// address space before call and casted back to Ptr type after call. 2682 LLVM_ABI Value *CreateStripInvariantGroup(Value *Ptr); 2683 2684 /// Return a vector value that contains the vector V reversed 2685 LLVM_ABI Value *CreateVectorReverse(Value *V, const Twine &Name = ""); 2686 2687 /// Return a vector splice intrinsic if using scalable vectors, otherwise 2688 /// return a shufflevector. If the immediate is positive, a vector is 2689 /// extracted from concat(V1, V2), starting at Imm. If the immediate 2690 /// is negative, we extract -Imm elements from V1 and the remaining 2691 /// elements from V2. Imm is a signed integer in the range 2692 /// -VL <= Imm < VL (where VL is the runtime vector length of the 2693 /// source/result vector) 2694 LLVM_ABI Value *CreateVectorSplice(Value *V1, Value *V2, int64_t Imm, 2695 const Twine &Name = ""); 2696 2697 /// Return a vector value that contains \arg V broadcasted to \p 2698 /// NumElts elements. 2699 LLVM_ABI Value *CreateVectorSplat(unsigned NumElts, Value *V, 2700 const Twine &Name = ""); 2701 2702 /// Return a vector value that contains \arg V broadcasted to \p 2703 /// EC elements. 2704 LLVM_ABI Value *CreateVectorSplat(ElementCount EC, Value *V, 2705 const Twine &Name = ""); 2706 2707 LLVM_ABI Value *CreatePreserveArrayAccessIndex(Type *ElTy, Value *Base, 2708 unsigned Dimension, 2709 unsigned LastIndex, 2710 MDNode *DbgInfo); 2711 2712 LLVM_ABI Value *CreatePreserveUnionAccessIndex(Value *Base, 2713 unsigned FieldIndex, 2714 MDNode *DbgInfo); 2715 2716 LLVM_ABI Value *CreatePreserveStructAccessIndex(Type *ElTy, Value *Base, 2717 unsigned Index, 2718 unsigned FieldIndex, 2719 MDNode *DbgInfo); 2720 2721 LLVM_ABI Value *createIsFPClass(Value *FPNum, unsigned Test); 2722 2723 private: 2724 /// Helper function that creates an assume intrinsic call that 2725 /// represents an alignment assumption on the provided pointer \p PtrValue 2726 /// with offset \p OffsetValue and alignment value \p AlignValue. 2727 CallInst *CreateAlignmentAssumptionHelper(const DataLayout &DL, 2728 Value *PtrValue, Value *AlignValue, 2729 Value *OffsetValue); 2730 2731 public: 2732 /// Create an assume intrinsic call that represents an alignment 2733 /// assumption on the provided pointer. 2734 /// 2735 /// An optional offset can be provided, and if it is provided, the offset 2736 /// must be subtracted from the provided pointer to get the pointer with the 2737 /// specified alignment. 2738 LLVM_ABI CallInst *CreateAlignmentAssumption(const DataLayout &DL, 2739 Value *PtrValue, 2740 unsigned Alignment, 2741 Value *OffsetValue = nullptr); 2742 2743 /// Create an assume intrinsic call that represents an alignment 2744 /// assumption on the provided pointer. 2745 /// 2746 /// An optional offset can be provided, and if it is provided, the offset 2747 /// must be subtracted from the provided pointer to get the pointer with the 2748 /// specified alignment. 2749 /// 2750 /// This overload handles the condition where the Alignment is dependent 2751 /// on an existing value rather than a static value. 2752 LLVM_ABI CallInst *CreateAlignmentAssumption(const DataLayout &DL, 2753 Value *PtrValue, 2754 Value *Alignment, 2755 Value *OffsetValue = nullptr); 2756 2757 /// Create an assume intrinsic call that represents an dereferencable 2758 /// assumption on the provided pointer. 2759 LLVM_ABI CallInst *CreateDereferenceableAssumption(Value *PtrValue, 2760 Value *SizeValue); 2761 }; 2762 2763 /// This provides a uniform API for creating instructions and inserting 2764 /// them into a basic block: either at the end of a BasicBlock, or at a specific 2765 /// iterator location in a block. 2766 /// 2767 /// Note that the builder does not expose the full generality of LLVM 2768 /// instructions. For access to extra instruction properties, use the mutators 2769 /// (e.g. setVolatile) on the instructions after they have been 2770 /// created. Convenience state exists to specify fast-math flags and fp-math 2771 /// tags. 2772 /// 2773 /// The first template argument specifies a class to use for creating constants. 2774 /// This defaults to creating minimally folded constants. The second template 2775 /// argument allows clients to specify custom insertion hooks that are called on 2776 /// every newly created insertion. 2777 template <typename FolderTy = ConstantFolder, 2778 typename InserterTy = IRBuilderDefaultInserter> 2779 class IRBuilder : public IRBuilderBase { 2780 private: 2781 FolderTy Folder; 2782 InserterTy Inserter; 2783 2784 public: 2785 IRBuilder(LLVMContext &C, FolderTy Folder, InserterTy Inserter, 2786 MDNode *FPMathTag = nullptr, 2787 ArrayRef<OperandBundleDef> OpBundles = {}) 2788 : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles), 2789 Folder(Folder), Inserter(Inserter) {} 2790 2791 IRBuilder(LLVMContext &C, FolderTy Folder, MDNode *FPMathTag = nullptr, 2792 ArrayRef<OperandBundleDef> OpBundles = {}) 2793 : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles), 2794 Folder(Folder) {} 2795 2796 explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr, 2797 ArrayRef<OperandBundleDef> OpBundles = {}) 2798 : IRBuilderBase(C, this->Folder, this->Inserter, FPMathTag, OpBundles) {} 2799 2800 explicit IRBuilder(BasicBlock *TheBB, FolderTy Folder, 2801 MDNode *FPMathTag = nullptr, 2802 ArrayRef<OperandBundleDef> OpBundles = {}) 2803 : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter, 2804 FPMathTag, OpBundles), 2805 Folder(Folder) { 2806 SetInsertPoint(TheBB); 2807 } 2808 2809 explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr, 2810 ArrayRef<OperandBundleDef> OpBundles = {}) 2811 : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter, 2812 FPMathTag, OpBundles) { 2813 SetInsertPoint(TheBB); 2814 } 2815 2816 explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr, 2817 ArrayRef<OperandBundleDef> OpBundles = {}) 2818 : IRBuilderBase(IP->getContext(), this->Folder, this->Inserter, FPMathTag, 2819 OpBundles) { 2820 SetInsertPoint(IP); 2821 } 2822 2823 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, FolderTy Folder, 2824 MDNode *FPMathTag = nullptr, 2825 ArrayRef<OperandBundleDef> OpBundles = {}) 2826 : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter, 2827 FPMathTag, OpBundles), 2828 Folder(Folder) { 2829 SetInsertPoint(TheBB, IP); 2830 } 2831 2832 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, 2833 MDNode *FPMathTag = nullptr, 2834 ArrayRef<OperandBundleDef> OpBundles = {}) 2835 : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter, 2836 FPMathTag, OpBundles) { 2837 SetInsertPoint(TheBB, IP); 2838 } 2839 2840 /// Avoid copying the full IRBuilder. Prefer using InsertPointGuard 2841 /// or FastMathFlagGuard instead. 2842 IRBuilder(const IRBuilder &) = delete; 2843 getInserter()2844 InserterTy &getInserter() { return Inserter; } getInserter()2845 const InserterTy &getInserter() const { return Inserter; } 2846 }; 2847 2848 template <typename FolderTy, typename InserterTy> 2849 IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, 2850 ArrayRef<OperandBundleDef>) -> IRBuilder<FolderTy, InserterTy>; 2851 IRBuilder(LLVMContext &, MDNode *, ArrayRef<OperandBundleDef>) -> IRBuilder<>; 2852 template <typename FolderTy> 2853 IRBuilder(BasicBlock *, FolderTy, MDNode *, ArrayRef<OperandBundleDef>) 2854 -> IRBuilder<FolderTy>; 2855 IRBuilder(BasicBlock *, MDNode *, ArrayRef<OperandBundleDef>) -> IRBuilder<>; 2856 IRBuilder(Instruction *, MDNode *, ArrayRef<OperandBundleDef>) -> IRBuilder<>; 2857 template <typename FolderTy> 2858 IRBuilder(BasicBlock *, BasicBlock::iterator, FolderTy, MDNode *, 2859 ArrayRef<OperandBundleDef>) -> IRBuilder<FolderTy>; 2860 IRBuilder(BasicBlock *, BasicBlock::iterator, MDNode *, 2861 ArrayRef<OperandBundleDef>) -> IRBuilder<>; 2862 2863 2864 // Create wrappers for C Binding types (see CBindingWrapping.h). 2865 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef) 2866 2867 } // end namespace llvm 2868 2869 #endif // LLVM_IR_IRBUILDER_H 2870