1 //===-- llvm/Function.h - Class to represent a single function --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the declaration of the Function class, which represents a
11 // single function/procedure in LLVM.
13 // A function basically consists of a list of basic blocks, a list of arguments,
14 // and a symbol table.
16 //===----------------------------------------------------------------------===//
18 #ifndef LLVM_IR_FUNCTION_H
19 #define LLVM_IR_FUNCTION_H
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/IR/Argument.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/CallingConv.h"
27 #include "llvm/IR/GlobalObject.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/Support/Compiler.h"
38 struct SymbolTableListSentinelTraits<Argument>
39 : public ilist_half_embedded_sentinel_traits<Argument> {};
41 class Function : public GlobalObject, public ilist_node<Function> {
43 typedef SymbolTableList<Argument> ArgumentListType;
44 typedef SymbolTableList<BasicBlock> BasicBlockListType;
46 // BasicBlock iterators...
47 typedef BasicBlockListType::iterator iterator;
48 typedef BasicBlockListType::const_iterator const_iterator;
50 typedef ArgumentListType::iterator arg_iterator;
51 typedef ArgumentListType::const_iterator const_arg_iterator;
54 // Important things that make up a function!
55 BasicBlockListType BasicBlocks; ///< The basic blocks
56 mutable ArgumentListType ArgumentList; ///< The formal arguments
57 ValueSymbolTable *SymTab; ///< Symbol table of args/instructions
58 AttributeSet AttributeSets; ///< Parameter attributes
64 * bit 0 : HasLazyArguments
65 * bit 1 : HasPrefixData
66 * bit 2 : HasPrologueData
67 * bit 3 : HasPersonalityFn
68 * bits 4-13 : CallingConvention
70 * bits 15 : [reserved]
73 /// Bits from GlobalObject::GlobalObjectSubclassData.
75 /// Whether this function is materializable.
76 IsMaterializableBit = 1 << 0,
77 HasMetadataHashEntryBit = 1 << 1
79 void setGlobalObjectBit(unsigned Mask, bool Value) {
80 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
84 friend class SymbolTableListTraits<Function>;
86 void setParent(Module *parent);
88 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
89 /// built on demand, so that the list isn't allocated until the first client
90 /// needs it. The hasLazyArguments predicate returns true if the arg list
91 /// hasn't been set up yet.
92 bool hasLazyArguments() const {
93 return getSubclassDataFromValue() & (1<<0);
95 void CheckLazyArguments() const {
96 if (hasLazyArguments())
99 void BuildLazyArguments() const;
101 Function(const Function&) = delete;
102 void operator=(const Function&) = delete;
104 /// Function ctor - If the (optional) Module argument is specified, the
105 /// function is automatically inserted into the end of the function list for
108 Function(FunctionType *Ty, LinkageTypes Linkage,
109 const Twine &N = "", Module *M = nullptr);
112 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
113 const Twine &N = "", Module *M = nullptr) {
114 return new Function(Ty, Linkage, N, M);
117 ~Function() override;
119 /// \brief Provide fast operand accessors
120 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
122 Type *getReturnType() const; // Return the type of the ret val
123 FunctionType *getFunctionType() const; // Return the FunctionType for me
125 /// getContext - Return a reference to the LLVMContext associated with this
127 LLVMContext &getContext() const;
129 /// isVarArg - Return true if this function takes a variable number of
131 bool isVarArg() const;
133 bool isMaterializable() const;
134 void setIsMaterializable(bool V);
136 /// getIntrinsicID - This method returns the ID number of the specified
137 /// function, or Intrinsic::not_intrinsic if the function is not an
138 /// intrinsic, or if the pointer is null. This value is always defined to be
139 /// zero to allow easy checking for whether a function is intrinsic or not.
140 /// The particular intrinsic functions which correspond to this value are
141 /// defined in llvm/Intrinsics.h.
142 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
143 bool isIntrinsic() const { return getName().startswith("llvm."); }
145 /// \brief Recalculate the ID for this function if it is an Intrinsic defined
146 /// in llvm/Intrinsics.h. Sets the intrinsic ID to Intrinsic::not_intrinsic
147 /// if the name of this function does not match an intrinsic in that header.
148 /// Note, this method does not need to be called directly, as it is called
149 /// from Value::setName() whenever the name of this function changes.
150 void recalculateIntrinsicID();
152 /// getCallingConv()/setCallingConv(CC) - These method get and set the
153 /// calling convention of this function. The enum values for the known
154 /// calling conventions are defined in CallingConv.h.
155 CallingConv::ID getCallingConv() const {
156 return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) &
159 void setCallingConv(CallingConv::ID CC) {
160 auto ID = static_cast<unsigned>(CC);
161 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
162 setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4));
165 /// @brief Return the attribute list for this Function.
166 AttributeSet getAttributes() const { return AttributeSets; }
168 /// @brief Set the attribute list for this Function.
169 void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
171 /// @brief Add function attributes to this function.
172 void addFnAttr(Attribute::AttrKind N) {
173 setAttributes(AttributeSets.addAttribute(getContext(),
174 AttributeSet::FunctionIndex, N));
177 /// @brief Remove function attributes from this function.
178 void removeFnAttr(Attribute::AttrKind N) {
179 setAttributes(AttributeSets.removeAttribute(
180 getContext(), AttributeSet::FunctionIndex, N));
183 /// @brief Add function attributes to this function.
184 void addFnAttr(StringRef Kind) {
186 AttributeSets.addAttribute(getContext(),
187 AttributeSet::FunctionIndex, Kind));
189 void addFnAttr(StringRef Kind, StringRef Value) {
191 AttributeSets.addAttribute(getContext(),
192 AttributeSet::FunctionIndex, Kind, Value));
195 /// Set the entry count for this function.
196 void setEntryCount(uint64_t Count);
198 /// Get the entry count for this function.
199 Optional<uint64_t> getEntryCount() const;
201 /// @brief Return true if the function has the attribute.
202 bool hasFnAttribute(Attribute::AttrKind Kind) const {
203 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
205 bool hasFnAttribute(StringRef Kind) const {
206 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
209 /// @brief Return the attribute for the given attribute kind.
210 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
211 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
213 Attribute getFnAttribute(StringRef Kind) const {
214 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
217 /// \brief Return the stack alignment for the function.
218 unsigned getFnStackAlignment() const {
219 return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
222 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
223 /// to use during code generation.
225 return getSubclassDataFromValue() & (1<<14);
227 const std::string &getGC() const;
228 void setGC(const std::string Str);
231 /// @brief adds the attribute to the list of attributes.
232 void addAttribute(unsigned i, Attribute::AttrKind attr);
234 /// @brief adds the attributes to the list of attributes.
235 void addAttributes(unsigned i, AttributeSet attrs);
237 /// @brief removes the attributes from the list of attributes.
238 void removeAttributes(unsigned i, AttributeSet attr);
240 /// @brief adds the dereferenceable attribute to the list of attributes.
241 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
243 /// @brief adds the dereferenceable_or_null attribute to the list of
245 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
247 /// @brief Extract the alignment for a call or parameter (0=unknown).
248 unsigned getParamAlignment(unsigned i) const {
249 return AttributeSets.getParamAlignment(i);
252 /// @brief Extract the number of dereferenceable bytes for a call or
253 /// parameter (0=unknown).
254 uint64_t getDereferenceableBytes(unsigned i) const {
255 return AttributeSets.getDereferenceableBytes(i);
258 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
259 /// parameter (0=unknown).
260 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
261 return AttributeSets.getDereferenceableOrNullBytes(i);
264 /// @brief Determine if the function does not access memory.
265 bool doesNotAccessMemory() const {
266 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
267 Attribute::ReadNone);
269 void setDoesNotAccessMemory() {
270 addFnAttr(Attribute::ReadNone);
273 /// @brief Determine if the function does not access or only reads memory.
274 bool onlyReadsMemory() const {
275 return doesNotAccessMemory() ||
276 AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
277 Attribute::ReadOnly);
279 void setOnlyReadsMemory() {
280 addFnAttr(Attribute::ReadOnly);
283 /// @brief Determine if the call can access memmory only using pointers based
284 /// on its arguments.
285 bool onlyAccessesArgMemory() const {
286 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
287 Attribute::ArgMemOnly);
289 void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); }
291 /// @brief Determine if the function may only access memory that is
292 /// inaccessible from the IR.
293 bool onlyAccessesInaccessibleMemory() const {
294 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
295 Attribute::InaccessibleMemOnly);
297 void setOnlyAccessesInaccessibleMemory() {
298 addFnAttr(Attribute::InaccessibleMemOnly);
301 /// @brief Determine if the function may only access memory that is
302 // either inaccessible from the IR or pointed to by its arguments.
303 bool onlyAccessesInaccessibleMemOrArgMem() const {
304 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
305 Attribute::InaccessibleMemOrArgMemOnly);
307 void setOnlyAccessesInaccessibleMemOrArgMem() {
308 addFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
311 /// @brief Determine if the function cannot return.
312 bool doesNotReturn() const {
313 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
314 Attribute::NoReturn);
316 void setDoesNotReturn() {
317 addFnAttr(Attribute::NoReturn);
320 /// @brief Determine if the function cannot unwind.
321 bool doesNotThrow() const {
322 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
323 Attribute::NoUnwind);
325 void setDoesNotThrow() {
326 addFnAttr(Attribute::NoUnwind);
329 /// @brief Determine if the call cannot be duplicated.
330 bool cannotDuplicate() const {
331 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
332 Attribute::NoDuplicate);
334 void setCannotDuplicate() {
335 addFnAttr(Attribute::NoDuplicate);
338 /// @brief Determine if the call is convergent.
339 bool isConvergent() const {
340 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
341 Attribute::Convergent);
343 void setConvergent() {
344 addFnAttr(Attribute::Convergent);
347 /// Determine if the function is known not to recurse, directly or
349 bool doesNotRecurse() const {
350 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
351 Attribute::NoRecurse);
353 void setDoesNotRecurse() {
354 addFnAttr(Attribute::NoRecurse);
357 /// @brief True if the ABI mandates (or the user requested) that this
358 /// function be in a unwind table.
359 bool hasUWTable() const {
360 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
363 void setHasUWTable() {
364 addFnAttr(Attribute::UWTable);
367 /// @brief True if this function needs an unwind table.
368 bool needsUnwindTableEntry() const {
369 return hasUWTable() || !doesNotThrow();
372 /// @brief Determine if the function returns a structure through first
373 /// pointer argument.
374 bool hasStructRetAttr() const {
375 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
376 AttributeSets.hasAttribute(2, Attribute::StructRet);
379 /// @brief Determine if the parameter or return value is marked with NoAlias
381 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
382 bool doesNotAlias(unsigned n) const {
383 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
385 void setDoesNotAlias(unsigned n) {
386 addAttribute(n, Attribute::NoAlias);
389 /// @brief Determine if the parameter can be captured.
390 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
391 bool doesNotCapture(unsigned n) const {
392 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
394 void setDoesNotCapture(unsigned n) {
395 addAttribute(n, Attribute::NoCapture);
398 bool doesNotAccessMemory(unsigned n) const {
399 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
401 void setDoesNotAccessMemory(unsigned n) {
402 addAttribute(n, Attribute::ReadNone);
405 bool onlyReadsMemory(unsigned n) const {
406 return doesNotAccessMemory(n) ||
407 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
409 void setOnlyReadsMemory(unsigned n) {
410 addAttribute(n, Attribute::ReadOnly);
413 /// Optimize this function for minimum size (-Oz).
414 bool optForMinSize() const { return hasFnAttribute(Attribute::MinSize); };
416 /// Optimize this function for size (-Os) or minimum size (-Oz).
417 bool optForSize() const {
418 return hasFnAttribute(Attribute::OptimizeForSize) || optForMinSize();
421 /// copyAttributesFrom - copy all additional attributes (those not needed to
422 /// create a Function) from the Function Src to this one.
423 void copyAttributesFrom(const GlobalValue *Src) override;
425 /// deleteBody - This method deletes the body of the function, and converts
426 /// the linkage to external.
430 setLinkage(ExternalLinkage);
433 /// removeFromParent - This method unlinks 'this' from the containing module,
434 /// but does not delete it.
436 void removeFromParent() override;
438 /// eraseFromParent - This method unlinks 'this' from the containing module
441 void eraseFromParent() override;
443 /// Get the underlying elements of the Function... the basic block list is
444 /// empty for external functions.
446 const ArgumentListType &getArgumentList() const {
447 CheckLazyArguments();
450 ArgumentListType &getArgumentList() {
451 CheckLazyArguments();
454 static ArgumentListType Function::*getSublistAccess(Argument*) {
455 return &Function::ArgumentList;
458 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
459 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
460 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
461 return &Function::BasicBlocks;
464 const BasicBlock &getEntryBlock() const { return front(); }
465 BasicBlock &getEntryBlock() { return front(); }
467 //===--------------------------------------------------------------------===//
468 // Symbol Table Accessing functions...
470 /// getSymbolTable() - Return the symbol table...
472 inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
473 inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
475 //===--------------------------------------------------------------------===//
476 // BasicBlock iterator forwarding functions
478 iterator begin() { return BasicBlocks.begin(); }
479 const_iterator begin() const { return BasicBlocks.begin(); }
480 iterator end () { return BasicBlocks.end(); }
481 const_iterator end () const { return BasicBlocks.end(); }
483 size_t size() const { return BasicBlocks.size(); }
484 bool empty() const { return BasicBlocks.empty(); }
485 const BasicBlock &front() const { return BasicBlocks.front(); }
486 BasicBlock &front() { return BasicBlocks.front(); }
487 const BasicBlock &back() const { return BasicBlocks.back(); }
488 BasicBlock &back() { return BasicBlocks.back(); }
490 /// @name Function Argument Iteration
493 arg_iterator arg_begin() {
494 CheckLazyArguments();
495 return ArgumentList.begin();
497 const_arg_iterator arg_begin() const {
498 CheckLazyArguments();
499 return ArgumentList.begin();
501 arg_iterator arg_end() {
502 CheckLazyArguments();
503 return ArgumentList.end();
505 const_arg_iterator arg_end() const {
506 CheckLazyArguments();
507 return ArgumentList.end();
510 iterator_range<arg_iterator> args() {
511 return make_range(arg_begin(), arg_end());
514 iterator_range<const_arg_iterator> args() const {
515 return make_range(arg_begin(), arg_end());
520 size_t arg_size() const;
521 bool arg_empty() const;
523 /// \brief Check whether this function has a personality function.
524 bool hasPersonalityFn() const {
525 return getSubclassDataFromValue() & (1<<3);
528 /// \brief Get the personality function associated with this function.
529 Constant *getPersonalityFn() const;
530 void setPersonalityFn(Constant *Fn);
532 /// \brief Check whether this function has prefix data.
533 bool hasPrefixData() const {
534 return getSubclassDataFromValue() & (1<<1);
537 /// \brief Get the prefix data associated with this function.
538 Constant *getPrefixData() const;
539 void setPrefixData(Constant *PrefixData);
541 /// \brief Check whether this function has prologue data.
542 bool hasPrologueData() const {
543 return getSubclassDataFromValue() & (1<<2);
546 /// \brief Get the prologue data associated with this function.
547 Constant *getPrologueData() const;
548 void setPrologueData(Constant *PrologueData);
550 /// viewCFG - This function is meant for use from the debugger. You can just
551 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
552 /// program, displaying the CFG of the current function with the code for each
553 /// basic block inside. This depends on there being a 'dot' and 'gv' program
556 void viewCFG() const;
558 /// viewCFGOnly - This function is meant for use from the debugger. It works
559 /// just like viewCFG, but it does not include the contents of basic blocks
560 /// into the nodes, just the label. If you are only interested in the CFG
561 /// this can make the graph smaller.
563 void viewCFGOnly() const;
565 /// Methods for support type inquiry through isa, cast, and dyn_cast:
566 static inline bool classof(const Value *V) {
567 return V->getValueID() == Value::FunctionVal;
570 /// dropAllReferences() - This method causes all the subinstructions to "let
571 /// go" of all references that they are maintaining. This allows one to
572 /// 'delete' a whole module at a time, even though there may be circular
573 /// references... first all references are dropped, and all use counts go to
574 /// zero. Then everything is deleted for real. Note that no operations are
575 /// valid on an object that has "dropped all references", except operator
578 /// Since no other object in the module can have references into the body of a
579 /// function, dropping all references deletes the entire body of the function,
580 /// including any contained basic blocks.
582 void dropAllReferences();
584 /// hasAddressTaken - returns true if there are any uses of this function
585 /// other than direct calls or invokes to it, or blockaddress expressions.
586 /// Optionally passes back an offending user for diagnostic purposes.
588 bool hasAddressTaken(const User** = nullptr) const;
590 /// isDefTriviallyDead - Return true if it is trivially safe to remove
591 /// this function definition from the module (because it isn't externally
592 /// visible, does not have its address taken, and has no callers). To make
593 /// this more accurate, call removeDeadConstantUsers first.
594 bool isDefTriviallyDead() const;
596 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
597 /// setjmp or other function that gcc recognizes as "returning twice".
598 bool callsFunctionThatReturnsTwice() const;
600 /// \brief Check if this has any metadata.
601 bool hasMetadata() const { return hasMetadataHashEntry(); }
603 /// \brief Get the current metadata attachment, if any.
605 /// Returns \c nullptr if such an attachment is missing.
607 MDNode *getMetadata(unsigned KindID) const;
608 MDNode *getMetadata(StringRef Kind) const;
611 /// \brief Set a particular kind of metadata attachment.
613 /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
614 /// replacing it if it already exists.
616 void setMetadata(unsigned KindID, MDNode *MD);
617 void setMetadata(StringRef Kind, MDNode *MD);
620 /// \brief Get all current metadata attachments.
622 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
624 /// \brief Drop metadata not in the given list.
626 /// Drop all metadata from \c this not included in \c KnownIDs.
627 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
629 /// \brief Set the attached subprogram.
631 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
632 void setSubprogram(DISubprogram *SP);
634 /// \brief Get the attached subprogram.
636 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
637 /// to \a DISubprogram.
638 DISubprogram *getSubprogram() const;
641 void allocHungoffUselist();
642 template<int Idx> void setHungoffOperand(Constant *C);
644 // Shadow Value::setValueSubclassData with a private forwarding method so that
645 // subclasses cannot accidentally use it.
646 void setValueSubclassData(unsigned short D) {
647 Value::setValueSubclassData(D);
649 void setValueSubclassDataBit(unsigned Bit, bool On);
651 bool hasMetadataHashEntry() const {
652 return getGlobalObjectSubClassData() & HasMetadataHashEntryBit;
654 void setHasMetadataHashEntry(bool HasEntry) {
655 setGlobalObjectBit(HasMetadataHashEntryBit, HasEntry);
658 void clearMetadata();
662 struct OperandTraits<Function> : public HungoffOperandTraits<3> {};
664 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
666 } // End llvm namespace