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/Casting.h" 36 #include "llvm/Support/Compiler.h" 37 #include <cassert> 38 #include <cstddef> 39 #include <cstdint> 40 #include <memory> 41 #include <string> 42 43 namespace llvm { 44 45 namespace Intrinsic { 46 typedef unsigned ID; 47 } 48 49 class AssemblyAnnotationWriter; 50 class Constant; 51 class DISubprogram; 52 class LLVMContext; 53 class Module; 54 template <typename T> class Optional; 55 class raw_ostream; 56 class Type; 57 class User; 58 class BranchProbabilityInfo; 59 class BlockFrequencyInfo; 60 61 class Function : public GlobalObject, public ilist_node<Function> { 62 public: 63 using BasicBlockListType = SymbolTableList<BasicBlock>; 64 65 // BasicBlock iterators... 66 using iterator = BasicBlockListType::iterator; 67 using const_iterator = BasicBlockListType::const_iterator; 68 69 using arg_iterator = Argument *; 70 using const_arg_iterator = const Argument *; 71 72 private: 73 // Important things that make up a function! 74 BasicBlockListType BasicBlocks; ///< The basic blocks 75 mutable Argument *Arguments = nullptr; ///< The formal arguments 76 size_t NumArgs; 77 std::unique_ptr<ValueSymbolTable> 78 SymTab; ///< Symbol table of args/instructions 79 AttributeList AttributeSets; ///< Parameter attributes 80 81 /* 82 * Value::SubclassData 83 * 84 * bit 0 : HasLazyArguments 85 * bit 1 : HasPrefixData 86 * bit 2 : HasPrologueData 87 * bit 3 : HasPersonalityFn 88 * bits 4-13 : CallingConvention 89 * bits 14 : HasGC 90 * bits 15 : [reserved] 91 */ 92 93 /// Bits from GlobalObject::GlobalObjectSubclassData. 94 enum { 95 /// Whether this function is materializable. 96 IsMaterializableBit = 0, 97 }; 98 99 friend class SymbolTableListTraits<Function>; 100 101 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is 102 /// built on demand, so that the list isn't allocated until the first client 103 /// needs it. The hasLazyArguments predicate returns true if the arg list 104 /// hasn't been set up yet. 105 public: hasLazyArguments()106 bool hasLazyArguments() const { 107 return getSubclassDataFromValue() & (1<<0); 108 } 109 110 private: CheckLazyArguments()111 void CheckLazyArguments() const { 112 if (hasLazyArguments()) 113 BuildLazyArguments(); 114 } 115 116 void BuildLazyArguments() const; 117 118 void clearArguments(); 119 120 /// Function ctor - If the (optional) Module argument is specified, the 121 /// function is automatically inserted into the end of the function list for 122 /// the module. 123 /// 124 Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, 125 const Twine &N = "", Module *M = nullptr); 126 127 public: 128 Function(const Function&) = delete; 129 void operator=(const Function&) = delete; 130 ~Function(); 131 132 // This is here to help easily convert from FunctionT * (Function * or 133 // MachineFunction *) in BlockFrequencyInfoImpl to Function * by calling 134 // FunctionT->getFunction(). getFunction()135 const Function &getFunction() const { return *this; } 136 137 static Function *Create(FunctionType *Ty, LinkageTypes Linkage, 138 unsigned AddrSpace, const Twine &N = "", 139 Module *M = nullptr) { 140 return new Function(Ty, Linkage, AddrSpace, N, M); 141 } 142 143 // TODO: remove this once all users have been updated to pass an AddrSpace 144 static Function *Create(FunctionType *Ty, LinkageTypes Linkage, 145 const Twine &N = "", Module *M = nullptr) { 146 return new Function(Ty, Linkage, static_cast<unsigned>(-1), N, M); 147 } 148 149 /// Creates a new function and attaches it to a module. 150 /// 151 /// Places the function in the program address space as specified 152 /// by the module's data layout. 153 static Function *Create(FunctionType *Ty, LinkageTypes Linkage, 154 const Twine &N, Module &M); 155 156 static Function *CreateBefore(Function &InsertBefore, FunctionType *Ty, 157 LinkageTypes Linkage, const Twine &N = ""); 158 159 // Provide fast operand accessors. 160 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 161 162 /// Returns the number of non-debug IR instructions in this function. 163 /// This is equivalent to the sum of the sizes of each basic block contained 164 /// within this function. 165 unsigned getInstructionCount() const; 166 167 /// Returns the FunctionType for me. getFunctionType()168 FunctionType *getFunctionType() const { 169 return cast<FunctionType>(getValueType()); 170 } 171 172 /// Returns the type of the ret val. getReturnType()173 Type *getReturnType() const { return getFunctionType()->getReturnType(); } 174 175 /// getContext - Return a reference to the LLVMContext associated with this 176 /// function. 177 LLVMContext &getContext() const; 178 179 /// isVarArg - Return true if this function takes a variable number of 180 /// arguments. isVarArg()181 bool isVarArg() const { return getFunctionType()->isVarArg(); } 182 isMaterializable()183 bool isMaterializable() const { 184 return getGlobalObjectSubClassData() & (1 << IsMaterializableBit); 185 } setIsMaterializable(bool V)186 void setIsMaterializable(bool V) { 187 unsigned Mask = 1 << IsMaterializableBit; 188 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) | 189 (V ? Mask : 0u)); 190 } 191 192 /// getIntrinsicID - This method returns the ID number of the specified 193 /// function, or Intrinsic::not_intrinsic if the function is not an 194 /// intrinsic, or if the pointer is null. This value is always defined to be 195 /// zero to allow easy checking for whether a function is intrinsic or not. 196 /// The particular intrinsic functions which correspond to this value are 197 /// defined in llvm/Intrinsics.h. getIntrinsicID()198 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; } 199 200 /// isIntrinsic - Returns true if the function's name starts with "llvm.". 201 /// It's possible for this function to return true while getIntrinsicID() 202 /// returns Intrinsic::not_intrinsic! isIntrinsic()203 bool isIntrinsic() const { return HasLLVMReservedName; } 204 205 /// Returns true if the function is one of the "Constrained Floating-Point 206 /// Intrinsics". Returns false if not, and returns false when 207 /// getIntrinsicID() returns Intrinsic::not_intrinsic. 208 bool isConstrainedFPIntrinsic() const; 209 210 static Intrinsic::ID lookupIntrinsicID(StringRef Name); 211 212 /// Recalculate the ID for this function if it is an Intrinsic defined 213 /// in llvm/Intrinsics.h. Sets the intrinsic ID to Intrinsic::not_intrinsic 214 /// if the name of this function does not match an intrinsic in that header. 215 /// Note, this method does not need to be called directly, as it is called 216 /// from Value::setName() whenever the name of this function changes. 217 void recalculateIntrinsicID(); 218 219 /// getCallingConv()/setCallingConv(CC) - These method get and set the 220 /// calling convention of this function. The enum values for the known 221 /// calling conventions are defined in CallingConv.h. getCallingConv()222 CallingConv::ID getCallingConv() const { 223 return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) & 224 CallingConv::MaxID); 225 } setCallingConv(CallingConv::ID CC)226 void setCallingConv(CallingConv::ID CC) { 227 auto ID = static_cast<unsigned>(CC); 228 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention"); 229 setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4)); 230 } 231 232 /// Return the attribute list for this Function. getAttributes()233 AttributeList getAttributes() const { return AttributeSets; } 234 235 /// Set the attribute list for this Function. setAttributes(AttributeList Attrs)236 void setAttributes(AttributeList Attrs) { AttributeSets = Attrs; } 237 238 /// Add function attributes to this function. addFnAttr(Attribute::AttrKind Kind)239 void addFnAttr(Attribute::AttrKind Kind) { 240 addAttribute(AttributeList::FunctionIndex, Kind); 241 } 242 243 /// Add function attributes to this function. 244 void addFnAttr(StringRef Kind, StringRef Val = StringRef()) { 245 addAttribute(AttributeList::FunctionIndex, 246 Attribute::get(getContext(), Kind, Val)); 247 } 248 249 /// Add function attributes to this function. addFnAttr(Attribute Attr)250 void addFnAttr(Attribute Attr) { 251 addAttribute(AttributeList::FunctionIndex, Attr); 252 } 253 254 /// Remove function attributes from this function. removeFnAttr(Attribute::AttrKind Kind)255 void removeFnAttr(Attribute::AttrKind Kind) { 256 removeAttribute(AttributeList::FunctionIndex, Kind); 257 } 258 259 /// Remove function attribute from this function. removeFnAttr(StringRef Kind)260 void removeFnAttr(StringRef Kind) { 261 setAttributes(getAttributes().removeAttribute( 262 getContext(), AttributeList::FunctionIndex, Kind)); 263 } 264 265 enum ProfileCountType { PCT_Invalid, PCT_Real, PCT_Synthetic }; 266 267 /// Class to represent profile counts. 268 /// 269 /// This class represents both real and synthetic profile counts. 270 class ProfileCount { 271 private: 272 uint64_t Count; 273 ProfileCountType PCT; 274 static ProfileCount Invalid; 275 276 public: ProfileCount()277 ProfileCount() : Count(-1), PCT(PCT_Invalid) {} ProfileCount(uint64_t Count,ProfileCountType PCT)278 ProfileCount(uint64_t Count, ProfileCountType PCT) 279 : Count(Count), PCT(PCT) {} hasValue()280 bool hasValue() const { return PCT != PCT_Invalid; } getCount()281 uint64_t getCount() const { return Count; } getType()282 ProfileCountType getType() const { return PCT; } isSynthetic()283 bool isSynthetic() const { return PCT == PCT_Synthetic; } 284 explicit operator bool() { return hasValue(); } 285 bool operator!() const { return !hasValue(); } 286 // Update the count retaining the same profile count type. setCount(uint64_t C)287 ProfileCount &setCount(uint64_t C) { 288 Count = C; 289 return *this; 290 } getInvalid()291 static ProfileCount getInvalid() { return ProfileCount(-1, PCT_Invalid); } 292 }; 293 294 /// Set the entry count for this function. 295 /// 296 /// Entry count is the number of times this function was executed based on 297 /// pgo data. \p Imports points to a set of GUIDs that needs to 298 /// be imported by the function for sample PGO, to enable the same inlines as 299 /// the profiled optimized binary. 300 void setEntryCount(ProfileCount Count, 301 const DenseSet<GlobalValue::GUID> *Imports = nullptr); 302 303 /// A convenience wrapper for setting entry count 304 void setEntryCount(uint64_t Count, ProfileCountType Type = PCT_Real, 305 const DenseSet<GlobalValue::GUID> *Imports = nullptr); 306 307 /// Get the entry count for this function. 308 /// 309 /// Entry count is the number of times the function was executed. 310 /// When AllowSynthetic is false, only pgo_data will be returned. 311 ProfileCount getEntryCount(bool AllowSynthetic = false) const; 312 313 /// Return true if the function is annotated with profile data. 314 /// 315 /// Presence of entry counts from a profile run implies the function has 316 /// profile annotations. If IncludeSynthetic is false, only return true 317 /// when the profile data is real. 318 bool hasProfileData(bool IncludeSynthetic = false) const { 319 return getEntryCount(IncludeSynthetic).hasValue(); 320 } 321 322 /// Returns the set of GUIDs that needs to be imported to the function for 323 /// sample PGO, to enable the same inlines as the profiled optimized binary. 324 DenseSet<GlobalValue::GUID> getImportGUIDs() const; 325 326 /// Set the section prefix for this function. 327 void setSectionPrefix(StringRef Prefix); 328 329 /// Get the section prefix for this function. 330 Optional<StringRef> getSectionPrefix() const; 331 332 /// Return true if the function has the attribute. hasFnAttribute(Attribute::AttrKind Kind)333 bool hasFnAttribute(Attribute::AttrKind Kind) const { 334 return AttributeSets.hasFnAttribute(Kind); 335 } 336 337 /// Return true if the function has the attribute. hasFnAttribute(StringRef Kind)338 bool hasFnAttribute(StringRef Kind) const { 339 return AttributeSets.hasFnAttribute(Kind); 340 } 341 342 /// Return the attribute for the given attribute kind. getFnAttribute(Attribute::AttrKind Kind)343 Attribute getFnAttribute(Attribute::AttrKind Kind) const { 344 return getAttribute(AttributeList::FunctionIndex, Kind); 345 } 346 347 /// Return the attribute for the given attribute kind. getFnAttribute(StringRef Kind)348 Attribute getFnAttribute(StringRef Kind) const { 349 return getAttribute(AttributeList::FunctionIndex, Kind); 350 } 351 352 /// Return the stack alignment for the function. getFnStackAlignment()353 unsigned getFnStackAlignment() const { 354 if (!hasFnAttribute(Attribute::StackAlignment)) 355 return 0; 356 if (const auto MA = 357 AttributeSets.getStackAlignment(AttributeList::FunctionIndex)) 358 return MA->value(); 359 return 0; 360 } 361 362 /// Return the stack alignment for the function. getFnStackAlign()363 MaybeAlign getFnStackAlign() const { 364 if (!hasFnAttribute(Attribute::StackAlignment)) 365 return None; 366 return AttributeSets.getStackAlignment(AttributeList::FunctionIndex); 367 } 368 369 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm 370 /// to use during code generation. hasGC()371 bool hasGC() const { 372 return getSubclassDataFromValue() & (1<<14); 373 } 374 const std::string &getGC() const; 375 void setGC(std::string Str); 376 void clearGC(); 377 378 /// adds the attribute to the list of attributes. 379 void addAttribute(unsigned i, Attribute::AttrKind Kind); 380 381 /// adds the attribute to the list of attributes. 382 void addAttribute(unsigned i, Attribute Attr); 383 384 /// adds the attributes to the list of attributes. 385 void addAttributes(unsigned i, const AttrBuilder &Attrs); 386 387 /// adds the attribute to the list of attributes for the given arg. 388 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind); 389 390 /// adds the attribute to the list of attributes for the given arg. 391 void addParamAttr(unsigned ArgNo, Attribute Attr); 392 393 /// adds the attributes to the list of attributes for the given arg. 394 void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs); 395 396 /// removes the attribute from the list of attributes. 397 void removeAttribute(unsigned i, Attribute::AttrKind Kind); 398 399 /// removes the attribute from the list of attributes. 400 void removeAttribute(unsigned i, StringRef Kind); 401 402 /// removes the attributes from the list of attributes. 403 void removeAttributes(unsigned i, const AttrBuilder &Attrs); 404 405 /// removes the attribute from the list of attributes. 406 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind); 407 408 /// removes the attribute from the list of attributes. 409 void removeParamAttr(unsigned ArgNo, StringRef Kind); 410 411 /// removes the attribute from the list of attributes. 412 void removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs); 413 414 /// check if an attributes is in the list of attributes. hasAttribute(unsigned i,Attribute::AttrKind Kind)415 bool hasAttribute(unsigned i, Attribute::AttrKind Kind) const { 416 return getAttributes().hasAttribute(i, Kind); 417 } 418 419 /// check if an attributes is in the list of attributes. hasParamAttribute(unsigned ArgNo,Attribute::AttrKind Kind)420 bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const { 421 return getAttributes().hasParamAttribute(ArgNo, Kind); 422 } 423 424 /// gets the specified attribute from the list of attributes. getParamAttribute(unsigned ArgNo,Attribute::AttrKind Kind)425 Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const { 426 return getAttributes().getParamAttr(ArgNo, Kind); 427 } 428 429 /// gets the attribute from the list of attributes. getAttribute(unsigned i,Attribute::AttrKind Kind)430 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const { 431 return AttributeSets.getAttribute(i, Kind); 432 } 433 434 /// gets the attribute from the list of attributes. getAttribute(unsigned i,StringRef Kind)435 Attribute getAttribute(unsigned i, StringRef Kind) const { 436 return AttributeSets.getAttribute(i, Kind); 437 } 438 439 /// adds the dereferenceable attribute to the list of attributes. 440 void addDereferenceableAttr(unsigned i, uint64_t Bytes); 441 442 /// adds the dereferenceable attribute to the list of attributes for 443 /// the given arg. 444 void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes); 445 446 /// adds the dereferenceable_or_null attribute to the list of 447 /// attributes. 448 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes); 449 450 /// adds the dereferenceable_or_null attribute to the list of 451 /// attributes for the given arg. 452 void addDereferenceableOrNullParamAttr(unsigned ArgNo, uint64_t Bytes); 453 454 /// Extract the alignment for a call or parameter (0=unknown). 455 /// FIXME: Remove this function once transition to Align is over. 456 /// Use getParamAlign() instead. getParamAlignment(unsigned ArgNo)457 unsigned getParamAlignment(unsigned ArgNo) const { 458 if (const auto MA = getParamAlign(ArgNo)) 459 return MA->value(); 460 return 0; 461 } 462 getParamAlign(unsigned ArgNo)463 MaybeAlign getParamAlign(unsigned ArgNo) const { 464 return AttributeSets.getParamAlignment(ArgNo); 465 } 466 467 /// Extract the byval type for a parameter. getParamByValType(unsigned ArgNo)468 Type *getParamByValType(unsigned ArgNo) const { 469 Type *Ty = AttributeSets.getParamByValType(ArgNo); 470 return Ty ? Ty : (arg_begin() + ArgNo)->getType()->getPointerElementType(); 471 } 472 473 /// Extract the number of dereferenceable bytes for a call or 474 /// parameter (0=unknown). 475 /// @param i AttributeList index, referring to a return value or argument. getDereferenceableBytes(unsigned i)476 uint64_t getDereferenceableBytes(unsigned i) const { 477 return AttributeSets.getDereferenceableBytes(i); 478 } 479 480 /// Extract the number of dereferenceable bytes for a parameter. 481 /// @param ArgNo Index of an argument, with 0 being the first function arg. getParamDereferenceableBytes(unsigned ArgNo)482 uint64_t getParamDereferenceableBytes(unsigned ArgNo) const { 483 return AttributeSets.getParamDereferenceableBytes(ArgNo); 484 } 485 486 /// Extract the number of dereferenceable_or_null bytes for a call or 487 /// parameter (0=unknown). 488 /// @param i AttributeList index, referring to a return value or argument. getDereferenceableOrNullBytes(unsigned i)489 uint64_t getDereferenceableOrNullBytes(unsigned i) const { 490 return AttributeSets.getDereferenceableOrNullBytes(i); 491 } 492 493 /// Extract the number of dereferenceable_or_null bytes for a 494 /// parameter. 495 /// @param ArgNo AttributeList ArgNo, referring to an argument. getParamDereferenceableOrNullBytes(unsigned ArgNo)496 uint64_t getParamDereferenceableOrNullBytes(unsigned ArgNo) const { 497 return AttributeSets.getParamDereferenceableOrNullBytes(ArgNo); 498 } 499 500 /// Determine if the function has additional side-effects. hasSideEffects()501 bool hasSideEffects() const { 502 return hasFnAttribute(Attribute::HasSideEffects); 503 } setHasSideEffects()504 void setHasSideEffects() { 505 addFnAttr(Attribute::HasSideEffects); 506 } 507 508 /// Determine if the function does not access memory. doesNotAccessMemory()509 bool doesNotAccessMemory() const { 510 return hasFnAttribute(Attribute::ReadNone); 511 } setDoesNotAccessMemory()512 void setDoesNotAccessMemory() { 513 addFnAttr(Attribute::ReadNone); 514 } 515 516 /// Determine if the function does not access or only reads memory. onlyReadsMemory()517 bool onlyReadsMemory() const { 518 return doesNotAccessMemory() || hasFnAttribute(Attribute::ReadOnly); 519 } setOnlyReadsMemory()520 void setOnlyReadsMemory() { 521 addFnAttr(Attribute::ReadOnly); 522 } 523 524 /// Determine if the function does not access or only writes memory. doesNotReadMemory()525 bool doesNotReadMemory() const { 526 return doesNotAccessMemory() || hasFnAttribute(Attribute::WriteOnly); 527 } setDoesNotReadMemory()528 void setDoesNotReadMemory() { 529 addFnAttr(Attribute::WriteOnly); 530 } 531 532 /// Determine if the call can access memmory only using pointers based 533 /// on its arguments. onlyAccessesArgMemory()534 bool onlyAccessesArgMemory() const { 535 return hasFnAttribute(Attribute::ArgMemOnly); 536 } setOnlyAccessesArgMemory()537 void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); } 538 539 /// Determine if the function may only access memory that is 540 /// inaccessible from the IR. onlyAccessesInaccessibleMemory()541 bool onlyAccessesInaccessibleMemory() const { 542 return hasFnAttribute(Attribute::InaccessibleMemOnly); 543 } setOnlyAccessesInaccessibleMemory()544 void setOnlyAccessesInaccessibleMemory() { 545 addFnAttr(Attribute::InaccessibleMemOnly); 546 } 547 548 /// Determine if the function may only access memory that is 549 /// either inaccessible from the IR or pointed to by its arguments. onlyAccessesInaccessibleMemOrArgMem()550 bool onlyAccessesInaccessibleMemOrArgMem() const { 551 return hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly); 552 } setOnlyAccessesInaccessibleMemOrArgMem()553 void setOnlyAccessesInaccessibleMemOrArgMem() { 554 addFnAttr(Attribute::InaccessibleMemOrArgMemOnly); 555 } 556 557 /// Determine if the function cannot return. doesNotReturn()558 bool doesNotReturn() const { 559 return hasFnAttribute(Attribute::NoReturn); 560 } setDoesNotReturn()561 void setDoesNotReturn() { 562 addFnAttr(Attribute::NoReturn); 563 } 564 565 /// Determine if the function should not perform indirect branch tracking. doesNoCfCheck()566 bool doesNoCfCheck() const { return hasFnAttribute(Attribute::NoCfCheck); } 567 568 /// Determine if the function cannot unwind. doesNotThrow()569 bool doesNotThrow() const { 570 return hasFnAttribute(Attribute::NoUnwind); 571 } setDoesNotThrow()572 void setDoesNotThrow() { 573 addFnAttr(Attribute::NoUnwind); 574 } 575 576 /// Determine if the call cannot be duplicated. cannotDuplicate()577 bool cannotDuplicate() const { 578 return hasFnAttribute(Attribute::NoDuplicate); 579 } setCannotDuplicate()580 void setCannotDuplicate() { 581 addFnAttr(Attribute::NoDuplicate); 582 } 583 584 /// Determine if the call is convergent. isConvergent()585 bool isConvergent() const { 586 return hasFnAttribute(Attribute::Convergent); 587 } setConvergent()588 void setConvergent() { 589 addFnAttr(Attribute::Convergent); 590 } setNotConvergent()591 void setNotConvergent() { 592 removeFnAttr(Attribute::Convergent); 593 } 594 595 /// Determine if the call has sideeffects. isSpeculatable()596 bool isSpeculatable() const { 597 return hasFnAttribute(Attribute::Speculatable); 598 } setSpeculatable()599 void setSpeculatable() { 600 addFnAttr(Attribute::Speculatable); 601 } 602 603 /// Determine if the call might deallocate memory. doesNotFreeMemory()604 bool doesNotFreeMemory() const { 605 return onlyReadsMemory() || hasFnAttribute(Attribute::NoFree); 606 } setDoesNotFreeMemory()607 void setDoesNotFreeMemory() { 608 addFnAttr(Attribute::NoFree); 609 } 610 611 /// Determine if the function is known not to recurse, directly or 612 /// indirectly. doesNotRecurse()613 bool doesNotRecurse() const { 614 return hasFnAttribute(Attribute::NoRecurse); 615 } setDoesNotRecurse()616 void setDoesNotRecurse() { 617 addFnAttr(Attribute::NoRecurse); 618 } 619 620 /// True if the ABI mandates (or the user requested) that this 621 /// function be in a unwind table. hasUWTable()622 bool hasUWTable() const { 623 return hasFnAttribute(Attribute::UWTable); 624 } setHasUWTable()625 void setHasUWTable() { 626 addFnAttr(Attribute::UWTable); 627 } 628 629 /// True if this function needs an unwind table. needsUnwindTableEntry()630 bool needsUnwindTableEntry() const { 631 return hasUWTable() || !doesNotThrow() || hasPersonalityFn(); 632 } 633 634 /// Determine if the function returns a structure through first 635 /// or second pointer argument. hasStructRetAttr()636 bool hasStructRetAttr() const { 637 return AttributeSets.hasParamAttribute(0, Attribute::StructRet) || 638 AttributeSets.hasParamAttribute(1, Attribute::StructRet); 639 } 640 641 /// Determine if the parameter or return value is marked with NoAlias 642 /// attribute. returnDoesNotAlias()643 bool returnDoesNotAlias() const { 644 return AttributeSets.hasAttribute(AttributeList::ReturnIndex, 645 Attribute::NoAlias); 646 } setReturnDoesNotAlias()647 void setReturnDoesNotAlias() { 648 addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias); 649 } 650 651 /// Do not optimize this function (-O0). hasOptNone()652 bool hasOptNone() const { return hasFnAttribute(Attribute::OptimizeNone); } 653 654 /// Optimize this function for minimum size (-Oz). hasMinSize()655 bool hasMinSize() const { return hasFnAttribute(Attribute::MinSize); } 656 657 /// Optimize this function for size (-Os) or minimum size (-Oz). hasOptSize()658 bool hasOptSize() const { 659 return hasFnAttribute(Attribute::OptimizeForSize) || hasMinSize(); 660 } 661 662 /// copyAttributesFrom - copy all additional attributes (those not needed to 663 /// create a Function) from the Function Src to this one. 664 void copyAttributesFrom(const Function *Src); 665 666 /// deleteBody - This method deletes the body of the function, and converts 667 /// the linkage to external. 668 /// deleteBody()669 void deleteBody() { 670 dropAllReferences(); 671 setLinkage(ExternalLinkage); 672 } 673 674 /// removeFromParent - This method unlinks 'this' from the containing module, 675 /// but does not delete it. 676 /// 677 void removeFromParent(); 678 679 /// eraseFromParent - This method unlinks 'this' from the containing module 680 /// and deletes it. 681 /// 682 void eraseFromParent(); 683 684 /// Steal arguments from another function. 685 /// 686 /// Drop this function's arguments and splice in the ones from \c Src. 687 /// Requires that this has no function body. 688 void stealArgumentListFrom(Function &Src); 689 690 /// Get the underlying elements of the Function... the basic block list is 691 /// empty for external functions. 692 /// getBasicBlockList()693 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; } getBasicBlockList()694 BasicBlockListType &getBasicBlockList() { return BasicBlocks; } 695 getSublistAccess(BasicBlock *)696 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) { 697 return &Function::BasicBlocks; 698 } 699 getEntryBlock()700 const BasicBlock &getEntryBlock() const { return front(); } getEntryBlock()701 BasicBlock &getEntryBlock() { return front(); } 702 703 //===--------------------------------------------------------------------===// 704 // Symbol Table Accessing functions... 705 706 /// getSymbolTable() - Return the symbol table if any, otherwise nullptr. 707 /// getValueSymbolTable()708 inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); } getValueSymbolTable()709 inline const ValueSymbolTable *getValueSymbolTable() const { 710 return SymTab.get(); 711 } 712 713 //===--------------------------------------------------------------------===// 714 // BasicBlock iterator forwarding functions 715 // begin()716 iterator begin() { return BasicBlocks.begin(); } begin()717 const_iterator begin() const { return BasicBlocks.begin(); } end()718 iterator end () { return BasicBlocks.end(); } end()719 const_iterator end () const { return BasicBlocks.end(); } 720 size()721 size_t size() const { return BasicBlocks.size(); } empty()722 bool empty() const { return BasicBlocks.empty(); } front()723 const BasicBlock &front() const { return BasicBlocks.front(); } front()724 BasicBlock &front() { return BasicBlocks.front(); } back()725 const BasicBlock &back() const { return BasicBlocks.back(); } back()726 BasicBlock &back() { return BasicBlocks.back(); } 727 728 /// @name Function Argument Iteration 729 /// @{ 730 arg_begin()731 arg_iterator arg_begin() { 732 CheckLazyArguments(); 733 return Arguments; 734 } arg_begin()735 const_arg_iterator arg_begin() const { 736 CheckLazyArguments(); 737 return Arguments; 738 } 739 arg_end()740 arg_iterator arg_end() { 741 CheckLazyArguments(); 742 return Arguments + NumArgs; 743 } arg_end()744 const_arg_iterator arg_end() const { 745 CheckLazyArguments(); 746 return Arguments + NumArgs; 747 } 748 getArg(unsigned i)749 Argument* getArg(unsigned i) const { 750 assert (i < NumArgs && "getArg() out of range!"); 751 CheckLazyArguments(); 752 return Arguments + i; 753 } 754 args()755 iterator_range<arg_iterator> args() { 756 return make_range(arg_begin(), arg_end()); 757 } args()758 iterator_range<const_arg_iterator> args() const { 759 return make_range(arg_begin(), arg_end()); 760 } 761 762 /// @} 763 arg_size()764 size_t arg_size() const { return NumArgs; } arg_empty()765 bool arg_empty() const { return arg_size() == 0; } 766 767 /// Check whether this function has a personality function. hasPersonalityFn()768 bool hasPersonalityFn() const { 769 return getSubclassDataFromValue() & (1<<3); 770 } 771 772 /// Get the personality function associated with this function. 773 Constant *getPersonalityFn() const; 774 void setPersonalityFn(Constant *Fn); 775 776 /// Check whether this function has prefix data. hasPrefixData()777 bool hasPrefixData() const { 778 return getSubclassDataFromValue() & (1<<1); 779 } 780 781 /// Get the prefix data associated with this function. 782 Constant *getPrefixData() const; 783 void setPrefixData(Constant *PrefixData); 784 785 /// Check whether this function has prologue data. hasPrologueData()786 bool hasPrologueData() const { 787 return getSubclassDataFromValue() & (1<<2); 788 } 789 790 /// Get the prologue data associated with this function. 791 Constant *getPrologueData() const; 792 void setPrologueData(Constant *PrologueData); 793 794 /// Print the function to an output stream with an optional 795 /// AssemblyAnnotationWriter. 796 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr, 797 bool ShouldPreserveUseListOrder = false, 798 bool IsForDebug = false) const; 799 800 /// viewCFG - This function is meant for use from the debugger. You can just 801 /// say 'call F->viewCFG()' and a ghostview window should pop up from the 802 /// program, displaying the CFG of the current function with the code for each 803 /// basic block inside. This depends on there being a 'dot' and 'gv' program 804 /// in your path. 805 /// 806 void viewCFG() const; 807 808 /// Extended form to print edge weights. 809 void viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI, 810 const BranchProbabilityInfo *BPI) const; 811 812 /// viewCFGOnly - This function is meant for use from the debugger. It works 813 /// just like viewCFG, but it does not include the contents of basic blocks 814 /// into the nodes, just the label. If you are only interested in the CFG 815 /// this can make the graph smaller. 816 /// 817 void viewCFGOnly() const; 818 819 /// Extended form to print edge weights. 820 void viewCFGOnly(const BlockFrequencyInfo *BFI, 821 const BranchProbabilityInfo *BPI) const; 822 823 /// Methods for support type inquiry through isa, cast, and dyn_cast: classof(const Value * V)824 static bool classof(const Value *V) { 825 return V->getValueID() == Value::FunctionVal; 826 } 827 828 /// dropAllReferences() - This method causes all the subinstructions to "let 829 /// go" of all references that they are maintaining. This allows one to 830 /// 'delete' a whole module at a time, even though there may be circular 831 /// references... first all references are dropped, and all use counts go to 832 /// zero. Then everything is deleted for real. Note that no operations are 833 /// valid on an object that has "dropped all references", except operator 834 /// delete. 835 /// 836 /// Since no other object in the module can have references into the body of a 837 /// function, dropping all references deletes the entire body of the function, 838 /// including any contained basic blocks. 839 /// 840 void dropAllReferences(); 841 842 /// hasAddressTaken - returns true if there are any uses of this function 843 /// other than direct calls or invokes to it, or blockaddress expressions. 844 /// Optionally passes back an offending user for diagnostic purposes and 845 /// ignores callback uses. 846 /// 847 bool hasAddressTaken(const User ** = nullptr, 848 bool IgnoreCallbackUses = false) const; 849 850 /// isDefTriviallyDead - Return true if it is trivially safe to remove 851 /// this function definition from the module (because it isn't externally 852 /// visible, does not have its address taken, and has no callers). To make 853 /// this more accurate, call removeDeadConstantUsers first. 854 bool isDefTriviallyDead() const; 855 856 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 857 /// setjmp or other function that gcc recognizes as "returning twice". 858 bool callsFunctionThatReturnsTwice() const; 859 860 /// Set the attached subprogram. 861 /// 862 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg. 863 void setSubprogram(DISubprogram *SP); 864 865 /// Get the attached subprogram. 866 /// 867 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result 868 /// to \a DISubprogram. 869 DISubprogram *getSubprogram() const; 870 871 /// Returns true if we should emit debug info for profiling. 872 bool isDebugInfoForProfiling() const; 873 874 /// Check if null pointer dereferencing is considered undefined behavior for 875 /// the function. 876 /// Return value: false => null pointer dereference is undefined. 877 /// Return value: true => null pointer dereference is not undefined. 878 bool nullPointerIsDefined() const; 879 880 private: 881 void allocHungoffUselist(); 882 template<int Idx> void setHungoffOperand(Constant *C); 883 884 /// Shadow Value::setValueSubclassData with a private forwarding method so 885 /// that subclasses cannot accidentally use it. setValueSubclassData(unsigned short D)886 void setValueSubclassData(unsigned short D) { 887 Value::setValueSubclassData(D); 888 } 889 void setValueSubclassDataBit(unsigned Bit, bool On); 890 }; 891 892 /// Check whether null pointer dereferencing is considered undefined behavior 893 /// for a given function or an address space. 894 /// Null pointer access in non-zero address space is not considered undefined. 895 /// Return value: false => null pointer dereference is undefined. 896 /// Return value: true => null pointer dereference is not undefined. 897 bool NullPointerIsDefined(const Function *F, unsigned AS = 0); 898 899 template <> 900 struct OperandTraits<Function> : public HungoffOperandTraits<3> {}; 901 902 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value) 903 904 } // end namespace llvm 905 906 #endif // LLVM_IR_FUNCTION_H 907