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/DenseSet.h"
22 #include "llvm/ADT/ilist_node.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/ADT/StringRef.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/GlobalObject.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/OperandTraits.h"
32 #include "llvm/IR/SymbolTableListTraits.h"
33 #include "llvm/IR/Value.h"
34 #include "llvm/Support/Compiler.h"
43 template <typename T> class Optional;
44 class AssemblyAnnotationWriter;
49 class Function : public GlobalObject, public ilist_node<Function> {
51 typedef SymbolTableList<BasicBlock> BasicBlockListType;
53 // BasicBlock iterators...
54 typedef BasicBlockListType::iterator iterator;
55 typedef BasicBlockListType::const_iterator const_iterator;
57 typedef Argument *arg_iterator;
58 typedef const Argument *const_arg_iterator;
61 // Important things that make up a function!
62 BasicBlockListType BasicBlocks; ///< The basic blocks
63 mutable Argument *Arguments; ///< The formal arguments
65 std::unique_ptr<ValueSymbolTable>
66 SymTab; ///< Symbol table of args/instructions
67 AttributeList AttributeSets; ///< Parameter attributes
72 * bit 0 : HasLazyArguments
73 * bit 1 : HasPrefixData
74 * bit 2 : HasPrologueData
75 * bit 3 : HasPersonalityFn
76 * bits 4-13 : CallingConvention
78 * bits 15 : [reserved]
81 /// Bits from GlobalObject::GlobalObjectSubclassData.
83 /// Whether this function is materializable.
84 IsMaterializableBit = 0,
87 friend class SymbolTableListTraits<Function>;
89 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
90 /// built on demand, so that the list isn't allocated until the first client
91 /// needs it. The hasLazyArguments predicate returns true if the arg list
92 /// hasn't been set up yet.
94 bool hasLazyArguments() const {
95 return getSubclassDataFromValue() & (1<<0);
99 void CheckLazyArguments() const {
100 if (hasLazyArguments())
101 BuildLazyArguments();
104 void BuildLazyArguments() const;
106 void clearArguments();
108 /// Function ctor - If the (optional) Module argument is specified, the
109 /// function is automatically inserted into the end of the function list for
112 Function(FunctionType *Ty, LinkageTypes Linkage,
113 const Twine &N = "", Module *M = nullptr);
116 Function(const Function&) = delete;
117 void operator=(const Function&) = delete;
118 ~Function() override;
120 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
121 const Twine &N = "", Module *M = nullptr) {
122 return new Function(Ty, Linkage, N, M);
125 // Provide fast operand accessors.
126 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
127 /// Returns the FunctionType for me.
128 FunctionType *getFunctionType() const {
129 return cast<FunctionType>(getValueType());
131 /// Returns the type of the ret val.
132 Type *getReturnType() const { return getFunctionType()->getReturnType(); }
134 /// getContext - Return a reference to the LLVMContext associated with this
136 LLVMContext &getContext() const;
138 /// isVarArg - Return true if this function takes a variable number of
140 bool isVarArg() const { return getFunctionType()->isVarArg(); }
142 bool isMaterializable() const {
143 return getGlobalObjectSubClassData() & (1 << IsMaterializableBit);
145 void setIsMaterializable(bool V) {
146 unsigned Mask = 1 << IsMaterializableBit;
147 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
151 /// getIntrinsicID - This method returns the ID number of the specified
152 /// function, or Intrinsic::not_intrinsic if the function is not an
153 /// intrinsic, or if the pointer is null. This value is always defined to be
154 /// zero to allow easy checking for whether a function is intrinsic or not.
155 /// The particular intrinsic functions which correspond to this value are
156 /// defined in llvm/Intrinsics.h.
157 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
159 /// isIntrinsic - Returns true if the function's name starts with "llvm.".
160 /// It's possible for this function to return true while getIntrinsicID()
161 /// returns Intrinsic::not_intrinsic!
162 bool isIntrinsic() const { return HasLLVMReservedName; }
164 static Intrinsic::ID lookupIntrinsicID(StringRef Name);
166 /// \brief Recalculate the ID for this function if it is an Intrinsic defined
167 /// in llvm/Intrinsics.h. Sets the intrinsic ID to Intrinsic::not_intrinsic
168 /// if the name of this function does not match an intrinsic in that header.
169 /// Note, this method does not need to be called directly, as it is called
170 /// from Value::setName() whenever the name of this function changes.
171 void recalculateIntrinsicID();
173 /// getCallingConv()/setCallingConv(CC) - These method get and set the
174 /// calling convention of this function. The enum values for the known
175 /// calling conventions are defined in CallingConv.h.
176 CallingConv::ID getCallingConv() const {
177 return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) &
180 void setCallingConv(CallingConv::ID CC) {
181 auto ID = static_cast<unsigned>(CC);
182 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
183 setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4));
186 /// @brief Return the attribute list for this Function.
187 AttributeList getAttributes() const { return AttributeSets; }
189 /// @brief Set the attribute list for this Function.
190 void setAttributes(AttributeList Attrs) { AttributeSets = Attrs; }
192 /// @brief Add function attributes to this function.
193 void addFnAttr(Attribute::AttrKind Kind) {
194 addAttribute(AttributeList::FunctionIndex, Kind);
197 /// @brief Add function attributes to this function.
198 void addFnAttr(StringRef Kind, StringRef Val = StringRef()) {
199 addAttribute(AttributeList::FunctionIndex,
200 Attribute::get(getContext(), Kind, Val));
203 void addFnAttr(Attribute Attr) {
204 addAttribute(AttributeList::FunctionIndex, Attr);
207 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
208 addAttribute(ArgNo + AttributeList::FirstArgIndex, Kind);
211 /// @brief Remove function attributes from this function.
212 void removeFnAttr(Attribute::AttrKind Kind) {
213 removeAttribute(AttributeList::FunctionIndex, Kind);
216 /// @brief Remove function attribute from this function.
217 void removeFnAttr(StringRef Kind) {
218 setAttributes(getAttributes().removeAttribute(
219 getContext(), AttributeList::FunctionIndex, Kind));
222 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
223 removeAttribute(ArgNo + AttributeList::FirstArgIndex, Kind);
226 /// \brief Set the entry count for this function.
228 /// Entry count is the number of times this function was executed based on
229 /// pgo data. \p Imports points to a set of GUIDs that needs to be imported
230 /// by the function for sample PGO, to enable the same inlines as the
231 /// profiled optimized binary.
232 void setEntryCount(uint64_t Count,
233 const DenseSet<GlobalValue::GUID> *Imports = nullptr);
235 /// \brief Get the entry count for this function.
237 /// Entry count is the number of times the function was executed based on
239 Optional<uint64_t> getEntryCount() const;
241 /// Returns the set of GUIDs that needs to be imported to the function for
242 /// sample PGO, to enable the same inlines as the profiled optimized binary.
243 DenseSet<GlobalValue::GUID> getImportGUIDs() const;
245 /// Set the section prefix for this function.
246 void setSectionPrefix(StringRef Prefix);
248 /// Get the section prefix for this function.
249 Optional<StringRef> getSectionPrefix() const;
251 /// @brief Return true if the function has the attribute.
252 bool hasFnAttribute(Attribute::AttrKind Kind) const {
253 return AttributeSets.hasFnAttribute(Kind);
255 bool hasFnAttribute(StringRef Kind) const {
256 return AttributeSets.hasFnAttribute(Kind);
259 /// @brief Return the attribute for the given attribute kind.
260 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
261 return getAttribute(AttributeList::FunctionIndex, Kind);
263 Attribute getFnAttribute(StringRef Kind) const {
264 return getAttribute(AttributeList::FunctionIndex, Kind);
267 /// \brief Return the stack alignment for the function.
268 unsigned getFnStackAlignment() const {
269 if (!hasFnAttribute(Attribute::StackAlignment))
271 return AttributeSets.getStackAlignment(AttributeList::FunctionIndex);
274 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
275 /// to use during code generation.
277 return getSubclassDataFromValue() & (1<<14);
279 const std::string &getGC() const;
280 void setGC(std::string Str);
283 /// @brief adds the attribute to the list of attributes.
284 void addAttribute(unsigned i, Attribute::AttrKind Kind);
286 /// @brief adds the attribute to the list of attributes.
287 void addAttribute(unsigned i, Attribute Attr);
289 /// @brief adds the attributes to the list of attributes.
290 void addAttributes(unsigned i, const AttrBuilder &Attrs);
292 /// @brief removes the attribute from the list of attributes.
293 void removeAttribute(unsigned i, Attribute::AttrKind Kind);
295 /// @brief removes the attribute from the list of attributes.
296 void removeAttribute(unsigned i, StringRef Kind);
298 /// @brief removes the attributes from the list of attributes.
299 void removeAttributes(unsigned i, const AttrBuilder &Attrs);
301 /// @brief check if an attributes is in the list of attributes.
302 bool hasAttribute(unsigned i, Attribute::AttrKind Kind) const {
303 return getAttributes().hasAttribute(i, Kind);
306 /// @brief check if an attributes is in the list of attributes.
307 bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const {
308 return getAttributes().hasParamAttribute(ArgNo, Kind);
311 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
312 return AttributeSets.getAttribute(i, Kind);
315 Attribute getAttribute(unsigned i, StringRef Kind) const {
316 return AttributeSets.getAttribute(i, Kind);
319 /// @brief adds the dereferenceable attribute to the list of attributes.
320 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
322 /// @brief adds the dereferenceable_or_null attribute to the list of
324 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
326 /// @brief Extract the alignment for a call or parameter (0=unknown).
327 unsigned getParamAlignment(unsigned ArgNo) const {
328 return AttributeSets.getParamAlignment(ArgNo);
331 /// @brief Extract the number of dereferenceable bytes for a call or
332 /// parameter (0=unknown).
333 /// @param i AttributeList index, referring to a return value or argument.
334 uint64_t getDereferenceableBytes(unsigned i) const {
335 return AttributeSets.getDereferenceableBytes(i);
338 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
339 /// parameter (0=unknown).
340 /// @param i AttributeList index, referring to a return value or argument.
341 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
342 return AttributeSets.getDereferenceableOrNullBytes(i);
345 /// @brief Determine if the function does not access memory.
346 bool doesNotAccessMemory() const {
347 return hasFnAttribute(Attribute::ReadNone);
349 void setDoesNotAccessMemory() {
350 addFnAttr(Attribute::ReadNone);
353 /// @brief Determine if the function does not access or only reads memory.
354 bool onlyReadsMemory() const {
355 return doesNotAccessMemory() || hasFnAttribute(Attribute::ReadOnly);
357 void setOnlyReadsMemory() {
358 addFnAttr(Attribute::ReadOnly);
361 /// @brief Determine if the function does not access or only writes memory.
362 bool doesNotReadMemory() const {
363 return doesNotAccessMemory() || hasFnAttribute(Attribute::WriteOnly);
365 void setDoesNotReadMemory() {
366 addFnAttr(Attribute::WriteOnly);
369 /// @brief Determine if the call can access memmory only using pointers based
370 /// on its arguments.
371 bool onlyAccessesArgMemory() const {
372 return hasFnAttribute(Attribute::ArgMemOnly);
374 void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); }
376 /// @brief Determine if the function may only access memory that is
377 /// inaccessible from the IR.
378 bool onlyAccessesInaccessibleMemory() const {
379 return hasFnAttribute(Attribute::InaccessibleMemOnly);
381 void setOnlyAccessesInaccessibleMemory() {
382 addFnAttr(Attribute::InaccessibleMemOnly);
385 /// @brief Determine if the function may only access memory that is
386 /// either inaccessible from the IR or pointed to by its arguments.
387 bool onlyAccessesInaccessibleMemOrArgMem() const {
388 return hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly);
390 void setOnlyAccessesInaccessibleMemOrArgMem() {
391 addFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
394 /// @brief Determine if the function cannot return.
395 bool doesNotReturn() const {
396 return hasFnAttribute(Attribute::NoReturn);
398 void setDoesNotReturn() {
399 addFnAttr(Attribute::NoReturn);
402 /// @brief Determine if the function cannot unwind.
403 bool doesNotThrow() const {
404 return hasFnAttribute(Attribute::NoUnwind);
406 void setDoesNotThrow() {
407 addFnAttr(Attribute::NoUnwind);
410 /// @brief Determine if the call cannot be duplicated.
411 bool cannotDuplicate() const {
412 return hasFnAttribute(Attribute::NoDuplicate);
414 void setCannotDuplicate() {
415 addFnAttr(Attribute::NoDuplicate);
418 /// @brief Determine if the call is convergent.
419 bool isConvergent() const {
420 return hasFnAttribute(Attribute::Convergent);
422 void setConvergent() {
423 addFnAttr(Attribute::Convergent);
425 void setNotConvergent() {
426 removeFnAttr(Attribute::Convergent);
429 /// @brief Determine if the call has sideeffects.
430 bool isSpeculatable() const {
431 return hasFnAttribute(Attribute::Speculatable);
433 void setSpeculatable() {
434 addFnAttr(Attribute::Speculatable);
437 /// Determine if the function is known not to recurse, directly or
439 bool doesNotRecurse() const {
440 return hasFnAttribute(Attribute::NoRecurse);
442 void setDoesNotRecurse() {
443 addFnAttr(Attribute::NoRecurse);
446 /// @brief True if the ABI mandates (or the user requested) that this
447 /// function be in a unwind table.
448 bool hasUWTable() const {
449 return hasFnAttribute(Attribute::UWTable);
451 void setHasUWTable() {
452 addFnAttr(Attribute::UWTable);
455 /// @brief True if this function needs an unwind table.
456 bool needsUnwindTableEntry() const {
457 return hasUWTable() || !doesNotThrow();
460 /// @brief Determine if the function returns a structure through first
461 /// or second pointer argument.
462 bool hasStructRetAttr() const {
463 return AttributeSets.hasParamAttribute(0, Attribute::StructRet) ||
464 AttributeSets.hasParamAttribute(1, Attribute::StructRet);
467 /// @brief Determine if the parameter or return value is marked with NoAlias
469 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
470 bool returnDoesNotAlias() const {
471 return AttributeSets.hasAttribute(AttributeList::ReturnIndex,
474 void setReturnDoesNotAlias() {
475 addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
478 /// Optimize this function for minimum size (-Oz).
479 bool optForMinSize() const { return hasFnAttribute(Attribute::MinSize); }
481 /// Optimize this function for size (-Os) or minimum size (-Oz).
482 bool optForSize() const {
483 return hasFnAttribute(Attribute::OptimizeForSize) || optForMinSize();
486 /// copyAttributesFrom - copy all additional attributes (those not needed to
487 /// create a Function) from the Function Src to this one.
488 void copyAttributesFrom(const GlobalValue *Src) override;
490 /// deleteBody - This method deletes the body of the function, and converts
491 /// the linkage to external.
495 setLinkage(ExternalLinkage);
498 /// removeFromParent - This method unlinks 'this' from the containing module,
499 /// but does not delete it.
501 void removeFromParent() override;
503 /// eraseFromParent - This method unlinks 'this' from the containing module
506 void eraseFromParent() override;
508 /// Steal arguments from another function.
510 /// Drop this function's arguments and splice in the ones from \c Src.
511 /// Requires that this has no function body.
512 void stealArgumentListFrom(Function &Src);
514 /// Get the underlying elements of the Function... the basic block list is
515 /// empty for external functions.
517 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
518 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
520 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
521 return &Function::BasicBlocks;
524 const BasicBlock &getEntryBlock() const { return front(); }
525 BasicBlock &getEntryBlock() { return front(); }
527 //===--------------------------------------------------------------------===//
528 // Symbol Table Accessing functions...
530 /// getSymbolTable() - Return the symbol table if any, otherwise nullptr.
532 inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); }
533 inline const ValueSymbolTable *getValueSymbolTable() const {
537 //===--------------------------------------------------------------------===//
538 // BasicBlock iterator forwarding functions
540 iterator begin() { return BasicBlocks.begin(); }
541 const_iterator begin() const { return BasicBlocks.begin(); }
542 iterator end () { return BasicBlocks.end(); }
543 const_iterator end () const { return BasicBlocks.end(); }
545 size_t size() const { return BasicBlocks.size(); }
546 bool empty() const { return BasicBlocks.empty(); }
547 const BasicBlock &front() const { return BasicBlocks.front(); }
548 BasicBlock &front() { return BasicBlocks.front(); }
549 const BasicBlock &back() const { return BasicBlocks.back(); }
550 BasicBlock &back() { return BasicBlocks.back(); }
552 /// @name Function Argument Iteration
555 arg_iterator arg_begin() {
556 CheckLazyArguments();
559 const_arg_iterator arg_begin() const {
560 CheckLazyArguments();
564 arg_iterator arg_end() {
565 CheckLazyArguments();
566 return Arguments + NumArgs;
568 const_arg_iterator arg_end() const {
569 CheckLazyArguments();
570 return Arguments + NumArgs;
573 iterator_range<arg_iterator> args() {
574 return make_range(arg_begin(), arg_end());
576 iterator_range<const_arg_iterator> args() const {
577 return make_range(arg_begin(), arg_end());
582 size_t arg_size() const { return NumArgs; }
583 bool arg_empty() const { return arg_size() == 0; }
585 /// \brief Check whether this function has a personality function.
586 bool hasPersonalityFn() const {
587 return getSubclassDataFromValue() & (1<<3);
590 /// \brief Get the personality function associated with this function.
591 Constant *getPersonalityFn() const;
592 void setPersonalityFn(Constant *Fn);
594 /// \brief Check whether this function has prefix data.
595 bool hasPrefixData() const {
596 return getSubclassDataFromValue() & (1<<1);
599 /// \brief Get the prefix data associated with this function.
600 Constant *getPrefixData() const;
601 void setPrefixData(Constant *PrefixData);
603 /// \brief Check whether this function has prologue data.
604 bool hasPrologueData() const {
605 return getSubclassDataFromValue() & (1<<2);
608 /// \brief Get the prologue data associated with this function.
609 Constant *getPrologueData() const;
610 void setPrologueData(Constant *PrologueData);
612 /// Print the function to an output stream with an optional
613 /// AssemblyAnnotationWriter.
614 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
615 bool ShouldPreserveUseListOrder = false,
616 bool IsForDebug = false) const;
618 /// viewCFG - This function is meant for use from the debugger. You can just
619 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
620 /// program, displaying the CFG of the current function with the code for each
621 /// basic block inside. This depends on there being a 'dot' and 'gv' program
624 void viewCFG() const;
626 /// viewCFGOnly - This function is meant for use from the debugger. It works
627 /// just like viewCFG, but it does not include the contents of basic blocks
628 /// into the nodes, just the label. If you are only interested in the CFG
629 /// this can make the graph smaller.
631 void viewCFGOnly() const;
633 /// Methods for support type inquiry through isa, cast, and dyn_cast:
634 static inline bool classof(const Value *V) {
635 return V->getValueID() == Value::FunctionVal;
638 /// dropAllReferences() - This method causes all the subinstructions to "let
639 /// go" of all references that they are maintaining. This allows one to
640 /// 'delete' a whole module at a time, even though there may be circular
641 /// references... first all references are dropped, and all use counts go to
642 /// zero. Then everything is deleted for real. Note that no operations are
643 /// valid on an object that has "dropped all references", except operator
646 /// Since no other object in the module can have references into the body of a
647 /// function, dropping all references deletes the entire body of the function,
648 /// including any contained basic blocks.
650 void dropAllReferences();
652 /// hasAddressTaken - returns true if there are any uses of this function
653 /// other than direct calls or invokes to it, or blockaddress expressions.
654 /// Optionally passes back an offending user for diagnostic purposes.
656 bool hasAddressTaken(const User** = nullptr) const;
658 /// isDefTriviallyDead - Return true if it is trivially safe to remove
659 /// this function definition from the module (because it isn't externally
660 /// visible, does not have its address taken, and has no callers). To make
661 /// this more accurate, call removeDeadConstantUsers first.
662 bool isDefTriviallyDead() const;
664 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
665 /// setjmp or other function that gcc recognizes as "returning twice".
666 bool callsFunctionThatReturnsTwice() const;
668 /// \brief Set the attached subprogram.
670 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
671 void setSubprogram(DISubprogram *SP);
673 /// \brief Get the attached subprogram.
675 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
676 /// to \a DISubprogram.
677 DISubprogram *getSubprogram() const;
679 /// Returns true if we should emit debug info for profiling.
680 bool isDebugInfoForProfiling() const;
683 void allocHungoffUselist();
684 template<int Idx> void setHungoffOperand(Constant *C);
686 /// Shadow Value::setValueSubclassData with a private forwarding method so
687 /// that subclasses cannot accidentally use it.
688 void setValueSubclassData(unsigned short D) {
689 Value::setValueSubclassData(D);
691 void setValueSubclassDataBit(unsigned Bit, bool On);
695 struct OperandTraits<Function> : public HungoffOperandTraits<3> {};
697 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
699 } // end namespace llvm
701 #endif // LLVM_IR_FUNCTION_H