Function.h 33 KB

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