1 //===- llvm/Function.h - Class to represent a single function ---*- 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 contains the declaration of the Function class, which represents a 10 // single function/procedure in LLVM. 11 // 12 // A function basically consists of a list of basic blocks, a list of arguments, 13 // and a symbol table. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #ifndef LLVM_IR_FUNCTION_H 18 #define LLVM_IR_FUNCTION_H 19 20 #include "llvm/ADT/DenseSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/ADT/ilist_node.h" 24 #include "llvm/ADT/iterator_range.h" 25 #include "llvm/IR/Argument.h" 26 #include "llvm/IR/Attributes.h" 27 #include "llvm/IR/BasicBlock.h" 28 #include "llvm/IR/CallingConv.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/GlobalObject.h" 31 #include "llvm/IR/GlobalValue.h" 32 #include "llvm/IR/OperandTraits.h" 33 #include "llvm/IR/SymbolTableListTraits.h" 34 #include "llvm/IR/Value.h" 35 #include <cassert> 36 #include <cstddef> 37 #include <cstdint> 38 #include <memory> 39 #include <string> 40 41 namespace llvm { 42 43 namespace Intrinsic { 44 typedef unsigned ID; 45 } 46 47 class AssemblyAnnotationWriter; 48 class Constant; 49 class ConstantRange; 50 class DataLayout; 51 struct DenormalMode; 52 class DISubprogram; 53 enum LibFunc : unsigned; 54 class LLVMContext; 55 class Module; 56 class raw_ostream; 57 class TargetLibraryInfoImpl; 58 class Type; 59 class User; 60 class BranchProbabilityInfo; 61 class BlockFrequencyInfo; 62 63 class LLVM_ABI Function : public GlobalObject, public ilist_node<Function> { 64 public: 65 using BasicBlockListType = SymbolTableList<BasicBlock>; 66 67 // BasicBlock iterators... 68 using iterator = BasicBlockListType::iterator; 69 using const_iterator = BasicBlockListType::const_iterator; 70 71 using arg_iterator = Argument *; 72 using const_arg_iterator = const Argument *; 73 74 private: 75 constexpr static HungOffOperandsAllocMarker AllocMarker{}; 76 77 // Important things that make up a function! 78 BasicBlockListType BasicBlocks; ///< The basic blocks 79 80 // Basic blocks need to get their number when added to a function. 81 friend void BasicBlock::setParent(Function *); 82 unsigned NextBlockNum = 0; 83 /// Epoch of block numbers. (Could be shrinked to uint8_t if required.) 84 unsigned BlockNumEpoch = 0; 85 86 mutable Argument *Arguments = nullptr; ///< The formal arguments 87 size_t NumArgs; 88 std::unique_ptr<ValueSymbolTable> 89 SymTab; ///< Symbol table of args/instructions 90 AttributeList AttributeSets; ///< Parameter attributes 91 92 /* 93 * Value::SubclassData 94 * 95 * bit 0 : HasLazyArguments 96 * bit 1 : HasPrefixData 97 * bit 2 : HasPrologueData 98 * bit 3 : HasPersonalityFn 99 * bits 4-13 : CallingConvention 100 * bits 14 : HasGC 101 * bits 15 : [reserved] 102 */ 103 104 /// Bits from GlobalObject::GlobalObjectSubclassData. 105 enum { 106 /// Whether this function is materializable. 107 IsMaterializableBit = 0, 108 }; 109 110 friend class SymbolTableListTraits<Function>; 111 112 public: 113 /// Is this function using intrinsics to record the position of debugging 114 /// information, or non-intrinsic records? See IsNewDbgInfoFormat in 115 /// \ref BasicBlock. 116 bool IsNewDbgInfoFormat; 117 118 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is 119 /// built on demand, so that the list isn't allocated until the first client 120 /// needs it. The hasLazyArguments predicate returns true if the arg list 121 /// hasn't been set up yet. 122 bool hasLazyArguments() const { 123 return getSubclassDataFromValue() & (1<<0); 124 } 125 126 /// \see BasicBlock::convertToNewDbgValues. 127 void convertToNewDbgValues(); 128 129 /// \see BasicBlock::convertFromNewDbgValues. 130 void convertFromNewDbgValues(); 131 132 void setIsNewDbgInfoFormat(bool NewVal); 133 void setNewDbgInfoFormatFlag(bool NewVal); 134 135 private: 136 friend class TargetLibraryInfoImpl; 137 138 static constexpr LibFunc UnknownLibFunc = LibFunc(-1); 139 140 /// Cache for TLI::getLibFunc() result without prototype validation. 141 /// UnknownLibFunc if uninitialized. NotLibFunc if definitely not lib func. 142 /// Otherwise may be libfunc if prototype validation passes. 143 mutable LibFunc LibFuncCache = UnknownLibFunc; 144 145 void CheckLazyArguments() const { 146 if (hasLazyArguments()) 147 BuildLazyArguments(); 148 } 149 150 void BuildLazyArguments() const; 151 152 void clearArguments(); 153 154 void deleteBodyImpl(bool ShouldDrop); 155 156 /// Function ctor - If the (optional) Module argument is specified, the 157 /// function is automatically inserted into the end of the function list for 158 /// the module. 159 /// 160 Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, 161 const Twine &N = "", Module *M = nullptr); 162 163 public: 164 Function(const Function&) = delete; 165 void operator=(const Function&) = delete; 166 ~Function(); 167 168 // This is here to help easily convert from FunctionT * (Function * or 169 // MachineFunction *) in BlockFrequencyInfoImpl to Function * by calling 170 // FunctionT->getFunction(). 171 const Function &getFunction() const { return *this; } 172 173 static Function *Create(FunctionType *Ty, LinkageTypes Linkage, 174 unsigned AddrSpace, const Twine &N = "", 175 Module *M = nullptr) { 176 return new (AllocMarker) Function(Ty, Linkage, AddrSpace, N, M); 177 } 178 179 // TODO: remove this once all users have been updated to pass an AddrSpace 180 static Function *Create(FunctionType *Ty, LinkageTypes Linkage, 181 const Twine &N = "", Module *M = nullptr) { 182 return new (AllocMarker) 183 Function(Ty, Linkage, static_cast<unsigned>(-1), N, M); 184 } 185 186 /// Creates a new function and attaches it to a module. 187 /// 188 /// Places the function in the program address space as specified 189 /// by the module's data layout. 190 static Function *Create(FunctionType *Ty, LinkageTypes Linkage, 191 const Twine &N, Module &M); 192 193 /// Creates a function with some attributes recorded in llvm.module.flags 194 /// and the LLVMContext applied. 195 /// 196 /// Use this when synthesizing new functions that need attributes that would 197 /// have been set by command line options. 198 /// 199 /// This function should not be called from backends or the LTO pipeline. If 200 /// it is called from one of those places, some default attributes will not be 201 /// applied to the function. 202 static Function *createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, 203 unsigned AddrSpace, 204 const Twine &N = "", 205 Module *M = nullptr); 206 207 // Provide fast operand accessors. 208 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 209 210 /// Returns the number of non-debug IR instructions in this function. 211 /// This is equivalent to the sum of the sizes of each basic block contained 212 /// within this function. 213 unsigned getInstructionCount() const; 214 215 /// Returns the FunctionType for me. 216 FunctionType *getFunctionType() const { 217 return cast<FunctionType>(getValueType()); 218 } 219 220 /// Returns the type of the ret val. 221 Type *getReturnType() const { return getFunctionType()->getReturnType(); } 222 223 /// getContext - Return a reference to the LLVMContext associated with this 224 /// function. 225 LLVMContext &getContext() const; 226 227 /// Get the data layout of the module this function belongs to. 228 /// 229 /// Requires the function to have a parent module. 230 const DataLayout &getDataLayout() const; 231 232 /// isVarArg - Return true if this function takes a variable number of 233 /// arguments. 234 bool isVarArg() const { return getFunctionType()->isVarArg(); } 235 236 bool isMaterializable() const { 237 return getGlobalObjectSubClassData() & (1 << IsMaterializableBit); 238 } 239 void setIsMaterializable(bool V) { 240 unsigned Mask = 1 << IsMaterializableBit; 241 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) | 242 (V ? Mask : 0u)); 243 } 244 245 /// getIntrinsicID - This method returns the ID number of the specified 246 /// function, or Intrinsic::not_intrinsic if the function is not an 247 /// intrinsic, or if the pointer is null. This value is always defined to be 248 /// zero to allow easy checking for whether a function is intrinsic or not. 249 /// The particular intrinsic functions which correspond to this value are 250 /// defined in llvm/Intrinsics.h. 251 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; } 252 253 /// isIntrinsic - Returns true if the function's name starts with "llvm.". 254 /// It's possible for this function to return true while getIntrinsicID() 255 /// returns Intrinsic::not_intrinsic! 256 bool isIntrinsic() const { return HasLLVMReservedName; } 257 258 /// isTargetIntrinsic - Returns true if this function is an intrinsic and the 259 /// intrinsic is specific to a certain target. If this is not an intrinsic 260 /// or a generic intrinsic, false is returned. 261 bool isTargetIntrinsic() const; 262 263 /// Returns true if the function is one of the "Constrained Floating-Point 264 /// Intrinsics". Returns false if not, and returns false when 265 /// getIntrinsicID() returns Intrinsic::not_intrinsic. 266 bool isConstrainedFPIntrinsic() const; 267 268 /// Update internal caches that depend on the function name (such as the 269 /// intrinsic ID and libcall cache). 270 /// Note, this method does not need to be called directly, as it is called 271 /// from Value::setName() whenever the name of this function changes. 272 void updateAfterNameChange(); 273 274 /// getCallingConv()/setCallingConv(CC) - These method get and set the 275 /// calling convention of this function. The enum values for the known 276 /// calling conventions are defined in CallingConv.h. 277 CallingConv::ID getCallingConv() const { 278 return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) & 279 CallingConv::MaxID); 280 } 281 void setCallingConv(CallingConv::ID CC) { 282 auto ID = static_cast<unsigned>(CC); 283 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention"); 284 setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4)); 285 } 286 287 /// Does it have a kernel calling convention? 288 bool hasKernelCallingConv() const { 289 switch (getCallingConv()) { 290 default: 291 return false; 292 case CallingConv::PTX_Kernel: 293 case CallingConv::AMDGPU_KERNEL: 294 case CallingConv::SPIR_KERNEL: 295 return true; 296 } 297 } 298 299 enum ProfileCountType { PCT_Real, PCT_Synthetic }; 300 301 /// Class to represent profile counts. 302 /// 303 /// This class represents both real and synthetic profile counts. 304 class ProfileCount { 305 private: 306 uint64_t Count = 0; 307 ProfileCountType PCT = PCT_Real; 308 309 public: 310 ProfileCount(uint64_t Count, ProfileCountType PCT) 311 : Count(Count), PCT(PCT) {} 312 uint64_t getCount() const { return Count; } 313 ProfileCountType getType() const { return PCT; } 314 bool isSynthetic() const { return PCT == PCT_Synthetic; } 315 }; 316 317 /// Set the entry count for this function. 318 /// 319 /// Entry count is the number of times this function was executed based on 320 /// pgo data. \p Imports points to a set of GUIDs that needs to 321 /// be imported by the function for sample PGO, to enable the same inlines as 322 /// the profiled optimized binary. 323 void setEntryCount(ProfileCount Count, 324 const DenseSet<GlobalValue::GUID> *Imports = nullptr); 325 326 /// A convenience wrapper for setting entry count 327 void setEntryCount(uint64_t Count, ProfileCountType Type = PCT_Real, 328 const DenseSet<GlobalValue::GUID> *Imports = nullptr); 329 330 /// Get the entry count for this function. 331 /// 332 /// Entry count is the number of times the function was executed. 333 /// When AllowSynthetic is false, only pgo_data will be returned. 334 std::optional<ProfileCount> getEntryCount(bool AllowSynthetic = false) const; 335 336 /// Return true if the function is annotated with profile data. 337 /// 338 /// Presence of entry counts from a profile run implies the function has 339 /// profile annotations. If IncludeSynthetic is false, only return true 340 /// when the profile data is real. 341 bool hasProfileData(bool IncludeSynthetic = false) const { 342 return getEntryCount(IncludeSynthetic).has_value(); 343 } 344 345 /// Returns the set of GUIDs that needs to be imported to the function for 346 /// sample PGO, to enable the same inlines as the profiled optimized binary. 347 DenseSet<GlobalValue::GUID> getImportGUIDs() const; 348 349 /// Set the section prefix for this function. 350 void setSectionPrefix(StringRef Prefix); 351 352 /// Get the section prefix for this function. 353 std::optional<StringRef> getSectionPrefix() const; 354 355 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm 356 /// to use during code generation. 357 bool hasGC() const { 358 return getSubclassDataFromValue() & (1<<14); 359 } 360 const std::string &getGC() const; 361 void setGC(std::string Str); 362 void clearGC(); 363 364 /// Return the attribute list for this Function. 365 AttributeList getAttributes() const { return AttributeSets; } 366 367 /// Set the attribute list for this Function. 368 void setAttributes(AttributeList Attrs) { AttributeSets = Attrs; } 369 370 // TODO: remove non-AtIndex versions of these methods. 371 /// adds the attribute to the list of attributes. 372 void addAttributeAtIndex(unsigned i, Attribute Attr); 373 374 /// Add function attributes to this function. 375 void addFnAttr(Attribute::AttrKind Kind); 376 377 /// Add function attributes to this function. 378 void addFnAttr(StringRef Kind, StringRef Val = StringRef()); 379 380 /// Add function attributes to this function. 381 void addFnAttr(Attribute Attr); 382 383 /// Add function attributes to this function. 384 void addFnAttrs(const AttrBuilder &Attrs); 385 386 /// Add return value attributes to this function. 387 void addRetAttr(Attribute::AttrKind Kind); 388 389 /// Add return value attributes to this function. 390 void addRetAttr(Attribute Attr); 391 392 /// Add return value attributes to this function. 393 void addRetAttrs(const AttrBuilder &Attrs); 394 395 /// adds the attribute to the list of attributes for the given arg. 396 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind); 397 398 /// adds the attribute to the list of attributes for the given arg. 399 void addParamAttr(unsigned ArgNo, Attribute Attr); 400 401 /// adds the attributes to the list of attributes for the given arg. 402 void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs); 403 404 /// removes the attribute from the list of attributes. 405 void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind); 406 407 /// removes the attribute from the list of attributes. 408 void removeAttributeAtIndex(unsigned i, StringRef Kind); 409 410 /// Remove function attributes from this function. 411 void removeFnAttr(Attribute::AttrKind Kind); 412 413 /// Remove function attribute from this function. 414 void removeFnAttr(StringRef Kind); 415 416 void removeFnAttrs(const AttributeMask &Attrs); 417 418 /// removes the attribute from the return value list of attributes. 419 void removeRetAttr(Attribute::AttrKind Kind); 420 421 /// removes the attribute from the return value list of attributes. 422 void removeRetAttr(StringRef Kind); 423 424 /// removes the attributes from the return value list of attributes. 425 void removeRetAttrs(const AttributeMask &Attrs); 426 427 /// removes the attribute from the list of attributes. 428 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind); 429 430 /// removes the attribute from the list of attributes. 431 void removeParamAttr(unsigned ArgNo, StringRef Kind); 432 433 /// removes the attribute from the list of attributes. 434 void removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs); 435 436 /// Return true if the function has the attribute. 437 bool hasFnAttribute(Attribute::AttrKind Kind) const; 438 439 /// Return true if the function has the attribute. 440 bool hasFnAttribute(StringRef Kind) const; 441 442 /// check if an attribute is in the list of attributes for the return value. 443 bool hasRetAttribute(Attribute::AttrKind Kind) const; 444 445 /// check if an attributes is in the list of attributes. 446 bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const; 447 448 /// Check if an attribute is in the list of attributes. 449 bool hasParamAttribute(unsigned ArgNo, StringRef Kind) const; 450 451 /// gets the attribute from the list of attributes. 452 Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const; 453 454 /// gets the attribute from the list of attributes. 455 Attribute getAttributeAtIndex(unsigned i, StringRef Kind) const; 456 457 /// Check if attribute of the given kind is set at the given index. 458 bool hasAttributeAtIndex(unsigned Idx, Attribute::AttrKind Kind) const; 459 460 /// Return the attribute for the given attribute kind. 461 Attribute getFnAttribute(Attribute::AttrKind Kind) const; 462 463 /// Return the attribute for the given attribute kind. 464 Attribute getFnAttribute(StringRef Kind) const; 465 466 /// Return the attribute for the given attribute kind for the return value. 467 Attribute getRetAttribute(Attribute::AttrKind Kind) const; 468 469 /// For a string attribute \p Kind, parse attribute as an integer. 470 /// 471 /// \returns \p Default if attribute is not present. 472 /// 473 /// \returns \p Default if there is an error parsing the attribute integer, 474 /// and error is emitted to the LLVMContext 475 uint64_t getFnAttributeAsParsedInteger(StringRef Kind, 476 uint64_t Default = 0) const; 477 478 /// gets the specified attribute from the list of attributes. 479 Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const; 480 481 /// Return the stack alignment for the function. 482 MaybeAlign getFnStackAlign() const { 483 return AttributeSets.getFnStackAlignment(); 484 } 485 486 /// Returns true if the function has ssp, sspstrong, or sspreq fn attrs. 487 bool hasStackProtectorFnAttr() const; 488 489 /// adds the dereferenceable attribute to the list of attributes for 490 /// the given arg. 491 void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes); 492 493 /// adds the dereferenceable_or_null attribute to the list of 494 /// attributes for the given arg. 495 void addDereferenceableOrNullParamAttr(unsigned ArgNo, uint64_t Bytes); 496 497 /// adds the range attribute to the list of attributes for the return value. 498 void addRangeRetAttr(const ConstantRange &CR); 499 500 MaybeAlign getParamAlign(unsigned ArgNo) const { 501 return AttributeSets.getParamAlignment(ArgNo); 502 } 503 504 MaybeAlign getParamStackAlign(unsigned ArgNo) const { 505 return AttributeSets.getParamStackAlignment(ArgNo); 506 } 507 508 /// Extract the byval type for a parameter. 509 Type *getParamByValType(unsigned ArgNo) const { 510 return AttributeSets.getParamByValType(ArgNo); 511 } 512 513 /// Extract the sret type for a parameter. 514 Type *getParamStructRetType(unsigned ArgNo) const { 515 return AttributeSets.getParamStructRetType(ArgNo); 516 } 517 518 /// Extract the inalloca type for a parameter. 519 Type *getParamInAllocaType(unsigned ArgNo) const { 520 return AttributeSets.getParamInAllocaType(ArgNo); 521 } 522 523 /// Extract the byref type for a parameter. 524 Type *getParamByRefType(unsigned ArgNo) const { 525 return AttributeSets.getParamByRefType(ArgNo); 526 } 527 528 /// Extract the preallocated type for a parameter. 529 Type *getParamPreallocatedType(unsigned ArgNo) const { 530 return AttributeSets.getParamPreallocatedType(ArgNo); 531 } 532 533 /// Extract the number of dereferenceable bytes for a parameter. 534 /// @param ArgNo Index of an argument, with 0 being the first function arg. 535 uint64_t getParamDereferenceableBytes(unsigned ArgNo) const { 536 return AttributeSets.getParamDereferenceableBytes(ArgNo); 537 } 538 539 /// Extract the number of dereferenceable_or_null bytes for a 540 /// parameter. 541 /// @param ArgNo AttributeList ArgNo, referring to an argument. 542 uint64_t getParamDereferenceableOrNullBytes(unsigned ArgNo) const { 543 return AttributeSets.getParamDereferenceableOrNullBytes(ArgNo); 544 } 545 546 /// Extract the nofpclass attribute for a parameter. 547 FPClassTest getParamNoFPClass(unsigned ArgNo) const { 548 return AttributeSets.getParamNoFPClass(ArgNo); 549 } 550 551 /// Determine if the function is presplit coroutine. 552 bool isPresplitCoroutine() const { 553 return hasFnAttribute(Attribute::PresplitCoroutine); 554 } 555 void setPresplitCoroutine() { addFnAttr(Attribute::PresplitCoroutine); } 556 void setSplittedCoroutine() { removeFnAttr(Attribute::PresplitCoroutine); } 557 558 bool isCoroOnlyDestroyWhenComplete() const { 559 return hasFnAttribute(Attribute::CoroDestroyOnlyWhenComplete); 560 } 561 void setCoroDestroyOnlyWhenComplete() { 562 addFnAttr(Attribute::CoroDestroyOnlyWhenComplete); 563 } 564 565 MemoryEffects getMemoryEffects() const; 566 void setMemoryEffects(MemoryEffects ME); 567 568 /// Determine if the function does not access memory. 569 bool doesNotAccessMemory() const; 570 void setDoesNotAccessMemory(); 571 572 /// Determine if the function does not access or only reads memory. 573 bool onlyReadsMemory() const; 574 void setOnlyReadsMemory(); 575 576 /// Determine if the function does not access or only writes memory. 577 bool onlyWritesMemory() const; 578 void setOnlyWritesMemory(); 579 580 /// Determine if the call can access memmory only using pointers based 581 /// on its arguments. 582 bool onlyAccessesArgMemory() const; 583 void setOnlyAccessesArgMemory(); 584 585 /// Determine if the function may only access memory that is 586 /// inaccessible from the IR. 587 bool onlyAccessesInaccessibleMemory() const; 588 void setOnlyAccessesInaccessibleMemory(); 589 590 /// Determine if the function may only access memory that is 591 /// either inaccessible from the IR or pointed to by its arguments. 592 bool onlyAccessesInaccessibleMemOrArgMem() const; 593 void setOnlyAccessesInaccessibleMemOrArgMem(); 594 595 /// Determine if the function cannot return. 596 bool doesNotReturn() const { 597 return hasFnAttribute(Attribute::NoReturn); 598 } 599 void setDoesNotReturn() { 600 addFnAttr(Attribute::NoReturn); 601 } 602 603 /// Determine if the function should not perform indirect branch tracking. 604 bool doesNoCfCheck() const { return hasFnAttribute(Attribute::NoCfCheck); } 605 606 /// Determine if the function cannot unwind. 607 bool doesNotThrow() const { 608 return hasFnAttribute(Attribute::NoUnwind); 609 } 610 void setDoesNotThrow() { 611 addFnAttr(Attribute::NoUnwind); 612 } 613 614 /// Determine if the call cannot be duplicated. 615 bool cannotDuplicate() const { 616 return hasFnAttribute(Attribute::NoDuplicate); 617 } 618 void setCannotDuplicate() { 619 addFnAttr(Attribute::NoDuplicate); 620 } 621 622 /// Determine if the call is convergent. 623 bool isConvergent() const { 624 return hasFnAttribute(Attribute::Convergent); 625 } 626 void setConvergent() { 627 addFnAttr(Attribute::Convergent); 628 } 629 void setNotConvergent() { 630 removeFnAttr(Attribute::Convergent); 631 } 632 633 /// Determine if the call has sideeffects. 634 bool isSpeculatable() const { 635 return hasFnAttribute(Attribute::Speculatable); 636 } 637 void setSpeculatable() { 638 addFnAttr(Attribute::Speculatable); 639 } 640 641 /// Determine if the call might deallocate memory. 642 bool doesNotFreeMemory() const { 643 return onlyReadsMemory() || hasFnAttribute(Attribute::NoFree); 644 } 645 void setDoesNotFreeMemory() { 646 addFnAttr(Attribute::NoFree); 647 } 648 649 /// Determine if the call can synchroize with other threads 650 bool hasNoSync() const { 651 return hasFnAttribute(Attribute::NoSync); 652 } 653 void setNoSync() { 654 addFnAttr(Attribute::NoSync); 655 } 656 657 /// Determine if the function is known not to recurse, directly or 658 /// indirectly. 659 bool doesNotRecurse() const { 660 return hasFnAttribute(Attribute::NoRecurse); 661 } 662 void setDoesNotRecurse() { 663 addFnAttr(Attribute::NoRecurse); 664 } 665 666 /// Determine if the function is required to make forward progress. 667 bool mustProgress() const { 668 return hasFnAttribute(Attribute::MustProgress) || 669 hasFnAttribute(Attribute::WillReturn); 670 } 671 void setMustProgress() { addFnAttr(Attribute::MustProgress); } 672 673 /// Determine if the function will return. 674 bool willReturn() const { return hasFnAttribute(Attribute::WillReturn); } 675 void setWillReturn() { addFnAttr(Attribute::WillReturn); } 676 677 /// Get what kind of unwind table entry to generate for this function. 678 UWTableKind getUWTableKind() const { 679 return AttributeSets.getUWTableKind(); 680 } 681 682 /// True if the ABI mandates (or the user requested) that this 683 /// function be in a unwind table. 684 bool hasUWTable() const { 685 return getUWTableKind() != UWTableKind::None; 686 } 687 void setUWTableKind(UWTableKind K) { 688 if (K == UWTableKind::None) 689 removeFnAttr(Attribute::UWTable); 690 else 691 addFnAttr(Attribute::getWithUWTableKind(getContext(), K)); 692 } 693 /// True if this function needs an unwind table. 694 bool needsUnwindTableEntry() const { 695 return hasUWTable() || !doesNotThrow() || hasPersonalityFn(); 696 } 697 698 /// Determine if the function returns a structure through first 699 /// or second pointer argument. 700 bool hasStructRetAttr() const { 701 return AttributeSets.hasParamAttr(0, Attribute::StructRet) || 702 AttributeSets.hasParamAttr(1, Attribute::StructRet); 703 } 704 705 /// Determine if the parameter or return value is marked with NoAlias 706 /// attribute. 707 bool returnDoesNotAlias() const { 708 return AttributeSets.hasRetAttr(Attribute::NoAlias); 709 } 710 void setReturnDoesNotAlias() { addRetAttr(Attribute::NoAlias); } 711 712 /// Do not optimize this function (-O0). 713 bool hasOptNone() const { return hasFnAttribute(Attribute::OptimizeNone); } 714 715 /// Optimize this function for minimum size (-Oz). 716 bool hasMinSize() const { return hasFnAttribute(Attribute::MinSize); } 717 718 /// Optimize this function for size (-Os) or minimum size (-Oz). 719 bool hasOptSize() const { 720 return hasFnAttribute(Attribute::OptimizeForSize) || hasMinSize(); 721 } 722 723 /// Returns the denormal handling type for the default rounding mode of the 724 /// function. 725 DenormalMode getDenormalMode(const fltSemantics &FPType) const; 726 727 /// Return the representational value of "denormal-fp-math". Code interested 728 /// in the semantics of the function should use getDenormalMode instead. 729 DenormalMode getDenormalModeRaw() const; 730 731 /// Return the representational value of "denormal-fp-math-f32". Code 732 /// interested in the semantics of the function should use getDenormalMode 733 /// instead. 734 DenormalMode getDenormalModeF32Raw() const; 735 736 /// copyAttributesFrom - copy all additional attributes (those not needed to 737 /// create a Function) from the Function Src to this one. 738 void copyAttributesFrom(const Function *Src); 739 740 /// deleteBody - This method deletes the body of the function, and converts 741 /// the linkage to external. 742 /// 743 void deleteBody() { 744 deleteBodyImpl(/*ShouldDrop=*/false); 745 setLinkage(ExternalLinkage); 746 } 747 748 /// removeFromParent - This method unlinks 'this' from the containing module, 749 /// but does not delete it. 750 /// 751 void removeFromParent(); 752 753 /// eraseFromParent - This method unlinks 'this' from the containing module 754 /// and deletes it. 755 /// 756 void eraseFromParent(); 757 758 /// Steal arguments from another function. 759 /// 760 /// Drop this function's arguments and splice in the ones from \c Src. 761 /// Requires that this has no function body. 762 void stealArgumentListFrom(Function &Src); 763 764 /// Insert \p BB in the basic block list at \p Position. \Returns an iterator 765 /// to the newly inserted BB. 766 Function::iterator insert(Function::iterator Position, BasicBlock *BB) { 767 Function::iterator FIt = BasicBlocks.insert(Position, BB); 768 BB->setIsNewDbgInfoFormat(IsNewDbgInfoFormat); 769 return FIt; 770 } 771 772 /// Transfer all blocks from \p FromF to this function at \p ToIt. 773 void splice(Function::iterator ToIt, Function *FromF) { 774 splice(ToIt, FromF, FromF->begin(), FromF->end()); 775 } 776 777 /// Transfer one BasicBlock from \p FromF at \p FromIt to this function 778 /// at \p ToIt. 779 void splice(Function::iterator ToIt, Function *FromF, 780 Function::iterator FromIt) { 781 auto FromItNext = std::next(FromIt); 782 // Single-element splice is a noop if destination == source. 783 if (ToIt == FromIt || ToIt == FromItNext) 784 return; 785 splice(ToIt, FromF, FromIt, FromItNext); 786 } 787 788 /// Transfer a range of basic blocks that belong to \p FromF from \p 789 /// FromBeginIt to \p FromEndIt, to this function at \p ToIt. 790 void splice(Function::iterator ToIt, Function *FromF, 791 Function::iterator FromBeginIt, 792 Function::iterator FromEndIt); 793 794 /// Erases a range of BasicBlocks from \p FromIt to (not including) \p ToIt. 795 /// \Returns \p ToIt. 796 Function::iterator erase(Function::iterator FromIt, Function::iterator ToIt); 797 798 private: 799 // These need access to the underlying BB list. 800 friend void BasicBlock::removeFromParent(); 801 friend iplist<BasicBlock>::iterator BasicBlock::eraseFromParent(); 802 template <class BB_t, class BB_i_t, class BI_t, class II_t> 803 friend class InstIterator; 804 friend class llvm::SymbolTableListTraits<llvm::BasicBlock>; 805 friend class llvm::ilist_node_with_parent<llvm::BasicBlock, llvm::Function>; 806 807 /// Get the underlying elements of the Function... the basic block list is 808 /// empty for external functions. 809 /// 810 /// This is deliberately private because we have implemented an adequate set 811 /// of functions to modify the list, including Function::splice(), 812 /// Function::erase(), Function::insert() etc. 813 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; } 814 BasicBlockListType &getBasicBlockList() { return BasicBlocks; } 815 816 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) { 817 return &Function::BasicBlocks; 818 } 819 820 public: 821 const BasicBlock &getEntryBlock() const { return front(); } 822 BasicBlock &getEntryBlock() { return front(); } 823 824 //===--------------------------------------------------------------------===// 825 // Symbol Table Accessing functions... 826 827 /// getSymbolTable() - Return the symbol table if any, otherwise nullptr. 828 /// 829 inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); } 830 inline const ValueSymbolTable *getValueSymbolTable() const { 831 return SymTab.get(); 832 } 833 834 //===--------------------------------------------------------------------===// 835 // Block number functions 836 837 /// Return a value larger than the largest block number. Intended to allocate 838 /// a vector that is sufficiently large to hold all blocks indexed by their 839 /// number. 840 unsigned getMaxBlockNumber() const { return NextBlockNum; } 841 842 /// Renumber basic blocks into a dense value range starting from 0. Be aware 843 /// that other data structures and analyses (e.g., DominatorTree) may depend 844 /// on the value numbers and need to be updated or invalidated. 845 void renumberBlocks(); 846 847 /// Return the "epoch" of current block numbers. This will return a different 848 /// value after every renumbering. The intention is: if something (e.g., an 849 /// analysis) uses block numbers, it also stores the number epoch and then 850 /// can assert later on that the epoch didn't change (indicating that the 851 /// numbering is still valid). If the epoch changed, blocks might have been 852 /// assigned new numbers and previous uses of the numbers needs to be 853 /// invalidated. This is solely intended as a debugging feature. 854 unsigned getBlockNumberEpoch() const { return BlockNumEpoch; } 855 856 private: 857 /// Assert that all blocks have unique numbers within 0..NextBlockNum. This 858 /// has O(n) runtime complexity. 859 void validateBlockNumbers() const; 860 861 public: 862 //===--------------------------------------------------------------------===// 863 // BasicBlock iterator forwarding functions 864 // 865 iterator begin() { return BasicBlocks.begin(); } 866 const_iterator begin() const { return BasicBlocks.begin(); } 867 iterator end () { return BasicBlocks.end(); } 868 const_iterator end () const { return BasicBlocks.end(); } 869 870 size_t size() const { return BasicBlocks.size(); } 871 bool empty() const { return BasicBlocks.empty(); } 872 const BasicBlock &front() const { return BasicBlocks.front(); } 873 BasicBlock &front() { return BasicBlocks.front(); } 874 const BasicBlock &back() const { return BasicBlocks.back(); } 875 BasicBlock &back() { return BasicBlocks.back(); } 876 877 /// @name Function Argument Iteration 878 /// @{ 879 880 arg_iterator arg_begin() { 881 CheckLazyArguments(); 882 return Arguments; 883 } 884 const_arg_iterator arg_begin() const { 885 CheckLazyArguments(); 886 return Arguments; 887 } 888 889 arg_iterator arg_end() { 890 CheckLazyArguments(); 891 return Arguments + NumArgs; 892 } 893 const_arg_iterator arg_end() const { 894 CheckLazyArguments(); 895 return Arguments + NumArgs; 896 } 897 898 Argument* getArg(unsigned i) const { 899 assert (i < NumArgs && "getArg() out of range!"); 900 CheckLazyArguments(); 901 return Arguments + i; 902 } 903 904 iterator_range<arg_iterator> args() { 905 return make_range(arg_begin(), arg_end()); 906 } 907 iterator_range<const_arg_iterator> args() const { 908 return make_range(arg_begin(), arg_end()); 909 } 910 911 /// @} 912 913 size_t arg_size() const { return NumArgs; } 914 bool arg_empty() const { return arg_size() == 0; } 915 916 /// Check whether this function has a personality function. 917 bool hasPersonalityFn() const { 918 return getSubclassDataFromValue() & (1<<3); 919 } 920 921 /// Get the personality function associated with this function. 922 Constant *getPersonalityFn() const; 923 void setPersonalityFn(Constant *Fn); 924 925 /// Check whether this function has prefix data. 926 bool hasPrefixData() const { 927 return getSubclassDataFromValue() & (1<<1); 928 } 929 930 /// Get the prefix data associated with this function. 931 Constant *getPrefixData() const; 932 void setPrefixData(Constant *PrefixData); 933 934 /// Check whether this function has prologue data. 935 bool hasPrologueData() const { 936 return getSubclassDataFromValue() & (1<<2); 937 } 938 939 /// Get the prologue data associated with this function. 940 Constant *getPrologueData() const; 941 void setPrologueData(Constant *PrologueData); 942 943 /// Print the function to an output stream with an optional 944 /// AssemblyAnnotationWriter. 945 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr, 946 bool ShouldPreserveUseListOrder = false, 947 bool IsForDebug = false) const; 948 949 /// viewCFG - This function is meant for use from the debugger. You can just 950 /// say 'call F->viewCFG()' and a ghostview window should pop up from the 951 /// program, displaying the CFG of the current function with the code for each 952 /// basic block inside. This depends on there being a 'dot' and 'gv' program 953 /// in your path. 954 /// 955 void viewCFG() const; 956 957 /// viewCFG - This function is meant for use from the debugger. It works just 958 /// like viewCFG(), but generates the dot file with the given file name. 959 void viewCFG(const char *OutputFileName) const; 960 961 /// Extended form to print edge weights. 962 void viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI, 963 const BranchProbabilityInfo *BPI, 964 const char *OutputFileName = nullptr) const; 965 966 /// viewCFGOnly - This function is meant for use from the debugger. It works 967 /// just like viewCFG, but it does not include the contents of basic blocks 968 /// into the nodes, just the label. If you are only interested in the CFG 969 /// this can make the graph smaller. 970 /// 971 void viewCFGOnly() const; 972 973 /// viewCFG - This function is meant for use from the debugger. It works just 974 /// like viewCFGOnly(), but generates the dot file with the given file name. 975 void viewCFGOnly(const char *OutputFileName) const; 976 977 /// Extended form to print edge weights. 978 void viewCFGOnly(const BlockFrequencyInfo *BFI, 979 const BranchProbabilityInfo *BPI) const; 980 981 /// Methods for support type inquiry through isa, cast, and dyn_cast: 982 static bool classof(const Value *V) { 983 return V->getValueID() == Value::FunctionVal; 984 } 985 986 /// dropAllReferences() - This method causes all the subinstructions to "let 987 /// go" of all references that they are maintaining. This allows one to 988 /// 'delete' a whole module at a time, even though there may be circular 989 /// references... first all references are dropped, and all use counts go to 990 /// zero. Then everything is deleted for real. Note that no operations are 991 /// valid on an object that has "dropped all references", except operator 992 /// delete. 993 /// 994 /// Since no other object in the module can have references into the body of a 995 /// function, dropping all references deletes the entire body of the function, 996 /// including any contained basic blocks. 997 /// 998 void dropAllReferences() { 999 deleteBodyImpl(/*ShouldDrop=*/true); 1000 } 1001 1002 /// hasAddressTaken - returns true if there are any uses of this function 1003 /// other than direct calls or invokes to it, or blockaddress expressions. 1004 /// Optionally passes back an offending user for diagnostic purposes, 1005 /// ignores callback uses, assume like pointer annotation calls, references in 1006 /// llvm.used and llvm.compiler.used variables, operand bundle 1007 /// "clang.arc.attachedcall", and direct calls with a different call site 1008 /// signature (the function is implicitly casted). 1009 bool hasAddressTaken(const User ** = nullptr, bool IgnoreCallbackUses = false, 1010 bool IgnoreAssumeLikeCalls = true, 1011 bool IngoreLLVMUsed = false, 1012 bool IgnoreARCAttachedCall = false, 1013 bool IgnoreCastedDirectCall = false) const; 1014 1015 /// isDefTriviallyDead - Return true if it is trivially safe to remove 1016 /// this function definition from the module (because it isn't externally 1017 /// visible, does not have its address taken, and has no callers). To make 1018 /// this more accurate, call removeDeadConstantUsers first. 1019 bool isDefTriviallyDead() const; 1020 1021 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1022 /// setjmp or other function that gcc recognizes as "returning twice". 1023 bool callsFunctionThatReturnsTwice() const; 1024 1025 /// Set the attached subprogram. 1026 /// 1027 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg. 1028 void setSubprogram(DISubprogram *SP); 1029 1030 /// Get the attached subprogram. 1031 /// 1032 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result 1033 /// to \a DISubprogram. 1034 DISubprogram *getSubprogram() const; 1035 1036 /// Returns true if we should emit debug info for profiling. 1037 bool shouldEmitDebugInfoForProfiling() const; 1038 1039 /// Check if null pointer dereferencing is considered undefined behavior for 1040 /// the function. 1041 /// Return value: false => null pointer dereference is undefined. 1042 /// Return value: true => null pointer dereference is not undefined. 1043 bool nullPointerIsDefined() const; 1044 1045 private: 1046 void allocHungoffUselist(); 1047 template<int Idx> void setHungoffOperand(Constant *C); 1048 1049 /// Shadow Value::setValueSubclassData with a private forwarding method so 1050 /// that subclasses cannot accidentally use it. 1051 void setValueSubclassData(unsigned short D) { 1052 Value::setValueSubclassData(D); 1053 } 1054 void setValueSubclassDataBit(unsigned Bit, bool On); 1055 }; 1056 1057 /// Check whether null pointer dereferencing is considered undefined behavior 1058 /// for a given function or an address space. 1059 /// Null pointer access in non-zero address space is not considered undefined. 1060 /// Return value: false => null pointer dereference is undefined. 1061 /// Return value: true => null pointer dereference is not undefined. 1062 bool NullPointerIsDefined(const Function *F, unsigned AS = 0); 1063 1064 template <> struct OperandTraits<Function> : public HungoffOperandTraits {}; 1065 1066 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value) 1067 1068 } // end namespace llvm 1069 1070 #endif // LLVM_IR_FUNCTION_H 1071