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