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/IR/Argument.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/GlobalObject.h"
27 #include "llvm/IR/OperandTraits.h"
28 #include "llvm/Support/Compiler.h"
32 template <typename T> class Optional;
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
63 * bit 0 : HasLazyArguments
64 * bit 1 : HasPrefixData
65 * bit 2 : HasPrologueData
66 * bit 3 : HasPersonalityFn
67 * bits 4-13 : CallingConvention
69 * bits 15 : [reserved]
72 /// Bits from GlobalObject::GlobalObjectSubclassData.
74 /// Whether this function is materializable.
75 IsMaterializableBit = 0,
78 friend class SymbolTableListTraits<Function>;
80 void setParent(Module *parent);
82 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
83 /// built on demand, so that the list isn't allocated until the first client
84 /// needs it. The hasLazyArguments predicate returns true if the arg list
85 /// hasn't been set up yet.
87 bool hasLazyArguments() const {
88 return getSubclassDataFromValue() & (1<<0);
92 void CheckLazyArguments() const {
93 if (hasLazyArguments())
96 void BuildLazyArguments() const;
98 Function(const Function&) = delete;
99 void operator=(const Function&) = delete;
101 /// Function ctor - If the (optional) Module argument is specified, the
102 /// function is automatically inserted into the end of the function list for
105 Function(FunctionType *Ty, LinkageTypes Linkage,
106 const Twine &N = "", Module *M = nullptr);
109 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
110 const Twine &N = "", Module *M = nullptr) {
111 return new Function(Ty, Linkage, N, M);
114 ~Function() override;
116 /// \brief Provide fast operand accessors
117 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
119 Type *getReturnType() const; // Return the type of the ret val
120 FunctionType *getFunctionType() const; // Return the FunctionType for me
122 /// getContext - Return a reference to the LLVMContext associated with this
124 LLVMContext &getContext() const;
126 /// isVarArg - Return true if this function takes a variable number of
128 bool isVarArg() const;
130 bool isMaterializable() const;
131 void setIsMaterializable(bool V);
133 /// getIntrinsicID - This method returns the ID number of the specified
134 /// function, or Intrinsic::not_intrinsic if the function is not an
135 /// intrinsic, or if the pointer is null. This value is always defined to be
136 /// zero to allow easy checking for whether a function is intrinsic or not.
137 /// The particular intrinsic functions which correspond to this value are
138 /// defined in llvm/Intrinsics.h.
139 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
140 bool isIntrinsic() const { return getName().startswith("llvm."); }
142 /// \brief Recalculate the ID for this function if it is an Intrinsic defined
143 /// in llvm/Intrinsics.h. Sets the intrinsic ID to Intrinsic::not_intrinsic
144 /// if the name of this function does not match an intrinsic in that header.
145 /// Note, this method does not need to be called directly, as it is called
146 /// from Value::setName() whenever the name of this function changes.
147 void recalculateIntrinsicID();
149 /// getCallingConv()/setCallingConv(CC) - These method get and set the
150 /// calling convention of this function. The enum values for the known
151 /// calling conventions are defined in CallingConv.h.
152 CallingConv::ID getCallingConv() const {
153 return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) &
156 void setCallingConv(CallingConv::ID CC) {
157 auto ID = static_cast<unsigned>(CC);
158 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
159 setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4));
162 /// @brief Return the attribute list for this Function.
163 AttributeSet getAttributes() const { return AttributeSets; }
165 /// @brief Set the attribute list for this Function.
166 void setAttributes(AttributeSet Attrs) { AttributeSets = Attrs; }
168 /// @brief Add function attributes to this function.
169 void addFnAttr(Attribute::AttrKind N) {
170 setAttributes(AttributeSets.addAttribute(getContext(),
171 AttributeSet::FunctionIndex, N));
174 /// @brief Remove function attributes from this function.
175 void removeFnAttr(Attribute::AttrKind Kind) {
176 setAttributes(AttributeSets.removeAttribute(
177 getContext(), AttributeSet::FunctionIndex, Kind));
180 /// @brief Add function attributes to this function.
181 void addFnAttr(StringRef Kind) {
183 AttributeSets.addAttribute(getContext(),
184 AttributeSet::FunctionIndex, Kind));
186 void addFnAttr(StringRef Kind, StringRef Value) {
188 AttributeSets.addAttribute(getContext(),
189 AttributeSet::FunctionIndex, Kind, Value));
192 /// Set the entry count for this function.
193 void setEntryCount(uint64_t Count);
195 /// Get the entry count for this function.
196 Optional<uint64_t> getEntryCount() const;
198 /// @brief Return true if the function has the attribute.
199 bool hasFnAttribute(Attribute::AttrKind Kind) const {
200 return AttributeSets.hasFnAttribute(Kind);
202 bool hasFnAttribute(StringRef Kind) const {
203 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
206 /// @brief Return the attribute for the given attribute kind.
207 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
208 return getAttribute(AttributeSet::FunctionIndex, Kind);
210 Attribute getFnAttribute(StringRef Kind) const {
211 return getAttribute(AttributeSet::FunctionIndex, Kind);
214 /// \brief Return the stack alignment for the function.
215 unsigned getFnStackAlignment() const {
216 if (!hasFnAttribute(Attribute::StackAlignment))
218 return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
221 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
222 /// to use during code generation.
224 return getSubclassDataFromValue() & (1<<14);
226 const std::string &getGC() const;
227 void setGC(std::string Str);
230 /// @brief adds the attribute to the list of attributes.
231 void addAttribute(unsigned i, Attribute::AttrKind Kind);
233 /// @brief adds the attribute to the list of attributes.
234 void addAttribute(unsigned i, Attribute Attr);
236 /// @brief adds the attributes to the list of attributes.
237 void addAttributes(unsigned i, AttributeSet Attrs);
239 /// @brief removes the attribute from the list of attributes.
240 void removeAttribute(unsigned i, Attribute::AttrKind Kind);
242 /// @brief removes the attribute from the list of attributes.
243 void removeAttribute(unsigned i, StringRef Kind);
245 /// @brief removes the attributes from the list of attributes.
246 void removeAttributes(unsigned i, AttributeSet Attrs);
248 /// @brief check if an attributes is in the list of attributes.
249 bool hasAttribute(unsigned i, Attribute::AttrKind Kind) const {
250 return getAttributes().hasAttribute(i, Kind);
253 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
254 return AttributeSets.getAttribute(i, Kind);
257 Attribute getAttribute(unsigned i, StringRef Kind) const {
258 return AttributeSets.getAttribute(i, Kind);
261 /// @brief adds the dereferenceable attribute to the list of attributes.
262 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
264 /// @brief adds the dereferenceable_or_null attribute to the list of
266 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
268 /// @brief Extract the alignment for a call or parameter (0=unknown).
269 unsigned getParamAlignment(unsigned i) const {
270 return AttributeSets.getParamAlignment(i);
273 /// @brief Extract the number of dereferenceable bytes for a call or
274 /// parameter (0=unknown).
275 uint64_t getDereferenceableBytes(unsigned i) const {
276 return AttributeSets.getDereferenceableBytes(i);
279 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
280 /// parameter (0=unknown).
281 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
282 return AttributeSets.getDereferenceableOrNullBytes(i);
285 /// @brief Determine if the function does not access memory.
286 bool doesNotAccessMemory() const {
287 return hasFnAttribute(Attribute::ReadNone);
289 void setDoesNotAccessMemory() {
290 addFnAttr(Attribute::ReadNone);
293 /// @brief Determine if the function does not access or only reads memory.
294 bool onlyReadsMemory() const {
295 return doesNotAccessMemory() || hasFnAttribute(Attribute::ReadOnly);
297 void setOnlyReadsMemory() {
298 addFnAttr(Attribute::ReadOnly);
301 /// @brief Determine if the function does not access or only writes memory.
302 bool doesNotReadMemory() const {
303 return doesNotAccessMemory() || hasFnAttribute(Attribute::WriteOnly);
305 void setDoesNotReadMemory() {
306 addFnAttr(Attribute::WriteOnly);
309 /// @brief Determine if the call can access memmory only using pointers based
310 /// on its arguments.
311 bool onlyAccessesArgMemory() const {
312 return hasFnAttribute(Attribute::ArgMemOnly);
314 void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); }
316 /// @brief Determine if the function may only access memory that is
317 /// inaccessible from the IR.
318 bool onlyAccessesInaccessibleMemory() const {
319 return hasFnAttribute(Attribute::InaccessibleMemOnly);
321 void setOnlyAccessesInaccessibleMemory() {
322 addFnAttr(Attribute::InaccessibleMemOnly);
325 /// @brief Determine if the function may only access memory that is
326 // either inaccessible from the IR or pointed to by its arguments.
327 bool onlyAccessesInaccessibleMemOrArgMem() const {
328 return hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly);
330 void setOnlyAccessesInaccessibleMemOrArgMem() {
331 addFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
334 /// @brief Determine if the function cannot return.
335 bool doesNotReturn() const {
336 return hasFnAttribute(Attribute::NoReturn);
338 void setDoesNotReturn() {
339 addFnAttr(Attribute::NoReturn);
342 /// @brief Determine if the function cannot unwind.
343 bool doesNotThrow() const {
344 return hasFnAttribute(Attribute::NoUnwind);
346 void setDoesNotThrow() {
347 addFnAttr(Attribute::NoUnwind);
350 /// @brief Determine if the call cannot be duplicated.
351 bool cannotDuplicate() const {
352 return hasFnAttribute(Attribute::NoDuplicate);
354 void setCannotDuplicate() {
355 addFnAttr(Attribute::NoDuplicate);
358 /// @brief Determine if the call is convergent.
359 bool isConvergent() const {
360 return hasFnAttribute(Attribute::Convergent);
362 void setConvergent() {
363 addFnAttr(Attribute::Convergent);
365 void setNotConvergent() {
366 removeFnAttr(Attribute::Convergent);
369 /// Determine if the function is known not to recurse, directly or
371 bool doesNotRecurse() const {
372 return hasFnAttribute(Attribute::NoRecurse);
374 void setDoesNotRecurse() {
375 addFnAttr(Attribute::NoRecurse);
378 /// @brief True if the ABI mandates (or the user requested) that this
379 /// function be in a unwind table.
380 bool hasUWTable() const {
381 return hasFnAttribute(Attribute::UWTable);
383 void setHasUWTable() {
384 addFnAttr(Attribute::UWTable);
387 /// @brief True if this function needs an unwind table.
388 bool needsUnwindTableEntry() const {
389 return hasUWTable() || !doesNotThrow();
392 /// @brief Determine if the function returns a structure through first
393 /// pointer argument.
394 bool hasStructRetAttr() const {
395 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
396 AttributeSets.hasAttribute(2, Attribute::StructRet);
399 /// @brief Determine if the parameter or return value is marked with NoAlias
401 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
402 bool doesNotAlias(unsigned n) const {
403 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
405 void setDoesNotAlias(unsigned n) {
406 addAttribute(n, Attribute::NoAlias);
409 /// @brief Determine if the parameter can be captured.
410 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
411 bool doesNotCapture(unsigned n) const {
412 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
414 void setDoesNotCapture(unsigned n) {
415 addAttribute(n, Attribute::NoCapture);
418 bool doesNotAccessMemory(unsigned n) const {
419 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
421 void setDoesNotAccessMemory(unsigned n) {
422 addAttribute(n, Attribute::ReadNone);
425 bool onlyReadsMemory(unsigned n) const {
426 return doesNotAccessMemory(n) ||
427 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
429 void setOnlyReadsMemory(unsigned n) {
430 addAttribute(n, Attribute::ReadOnly);
433 /// Optimize this function for minimum size (-Oz).
434 bool optForMinSize() const { return hasFnAttribute(Attribute::MinSize); };
436 /// Optimize this function for size (-Os) or minimum size (-Oz).
437 bool optForSize() const {
438 return hasFnAttribute(Attribute::OptimizeForSize) || optForMinSize();
441 /// copyAttributesFrom - copy all additional attributes (those not needed to
442 /// create a Function) from the Function Src to this one.
443 void copyAttributesFrom(const GlobalValue *Src) override;
445 /// deleteBody - This method deletes the body of the function, and converts
446 /// the linkage to external.
450 setLinkage(ExternalLinkage);
453 /// removeFromParent - This method unlinks 'this' from the containing module,
454 /// but does not delete it.
456 void removeFromParent() override;
458 /// eraseFromParent - This method unlinks 'this' from the containing module
461 void eraseFromParent() override;
463 /// Steal arguments from another function.
465 /// Drop this function's arguments and splice in the ones from \c Src.
466 /// Requires that this has no function body.
467 void stealArgumentListFrom(Function &Src);
469 /// Get the underlying elements of the Function... the basic block list is
470 /// empty for external functions.
472 const ArgumentListType &getArgumentList() const {
473 CheckLazyArguments();
476 ArgumentListType &getArgumentList() {
477 CheckLazyArguments();
480 static ArgumentListType Function::*getSublistAccess(Argument*) {
481 return &Function::ArgumentList;
484 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
485 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
486 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
487 return &Function::BasicBlocks;
490 const BasicBlock &getEntryBlock() const { return front(); }
491 BasicBlock &getEntryBlock() { return front(); }
493 //===--------------------------------------------------------------------===//
494 // Symbol Table Accessing functions...
496 /// getSymbolTable() - Return the symbol table...
498 inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
499 inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
501 //===--------------------------------------------------------------------===//
502 // BasicBlock iterator forwarding functions
504 iterator begin() { return BasicBlocks.begin(); }
505 const_iterator begin() const { return BasicBlocks.begin(); }
506 iterator end () { return BasicBlocks.end(); }
507 const_iterator end () const { return BasicBlocks.end(); }
509 size_t size() const { return BasicBlocks.size(); }
510 bool empty() const { return BasicBlocks.empty(); }
511 const BasicBlock &front() const { return BasicBlocks.front(); }
512 BasicBlock &front() { return BasicBlocks.front(); }
513 const BasicBlock &back() const { return BasicBlocks.back(); }
514 BasicBlock &back() { return BasicBlocks.back(); }
516 /// @name Function Argument Iteration
519 arg_iterator arg_begin() {
520 CheckLazyArguments();
521 return ArgumentList.begin();
523 const_arg_iterator arg_begin() const {
524 CheckLazyArguments();
525 return ArgumentList.begin();
527 arg_iterator arg_end() {
528 CheckLazyArguments();
529 return ArgumentList.end();
531 const_arg_iterator arg_end() const {
532 CheckLazyArguments();
533 return ArgumentList.end();
536 iterator_range<arg_iterator> args() {
537 return make_range(arg_begin(), arg_end());
540 iterator_range<const_arg_iterator> args() const {
541 return make_range(arg_begin(), arg_end());
546 size_t arg_size() const;
547 bool arg_empty() const;
549 /// \brief Check whether this function has a personality function.
550 bool hasPersonalityFn() const {
551 return getSubclassDataFromValue() & (1<<3);
554 /// \brief Get the personality function associated with this function.
555 Constant *getPersonalityFn() const;
556 void setPersonalityFn(Constant *Fn);
558 /// \brief Check whether this function has prefix data.
559 bool hasPrefixData() const {
560 return getSubclassDataFromValue() & (1<<1);
563 /// \brief Get the prefix data associated with this function.
564 Constant *getPrefixData() const;
565 void setPrefixData(Constant *PrefixData);
567 /// \brief Check whether this function has prologue data.
568 bool hasPrologueData() const {
569 return getSubclassDataFromValue() & (1<<2);
572 /// \brief Get the prologue data associated with this function.
573 Constant *getPrologueData() const;
574 void setPrologueData(Constant *PrologueData);
576 /// Print the function to an output stream with an optional
577 /// AssemblyAnnotationWriter.
578 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
579 bool ShouldPreserveUseListOrder = false,
580 bool IsForDebug = false) const;
582 /// viewCFG - This function is meant for use from the debugger. You can just
583 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
584 /// program, displaying the CFG of the current function with the code for each
585 /// basic block inside. This depends on there being a 'dot' and 'gv' program
588 void viewCFG() const;
590 /// viewCFGOnly - This function is meant for use from the debugger. It works
591 /// just like viewCFG, but it does not include the contents of basic blocks
592 /// into the nodes, just the label. If you are only interested in the CFG
593 /// this can make the graph smaller.
595 void viewCFGOnly() const;
597 /// Methods for support type inquiry through isa, cast, and dyn_cast:
598 static inline bool classof(const Value *V) {
599 return V->getValueID() == Value::FunctionVal;
602 /// dropAllReferences() - This method causes all the subinstructions to "let
603 /// go" of all references that they are maintaining. This allows one to
604 /// 'delete' a whole module at a time, even though there may be circular
605 /// references... first all references are dropped, and all use counts go to
606 /// zero. Then everything is deleted for real. Note that no operations are
607 /// valid on an object that has "dropped all references", except operator
610 /// Since no other object in the module can have references into the body of a
611 /// function, dropping all references deletes the entire body of the function,
612 /// including any contained basic blocks.
614 void dropAllReferences();
616 /// hasAddressTaken - returns true if there are any uses of this function
617 /// other than direct calls or invokes to it, or blockaddress expressions.
618 /// Optionally passes back an offending user for diagnostic purposes.
620 bool hasAddressTaken(const User** = nullptr) const;
622 /// isDefTriviallyDead - Return true if it is trivially safe to remove
623 /// this function definition from the module (because it isn't externally
624 /// visible, does not have its address taken, and has no callers). To make
625 /// this more accurate, call removeDeadConstantUsers first.
626 bool isDefTriviallyDead() const;
628 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
629 /// setjmp or other function that gcc recognizes as "returning twice".
630 bool callsFunctionThatReturnsTwice() const;
632 /// \brief Set the attached subprogram.
634 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
635 void setSubprogram(DISubprogram *SP);
637 /// \brief Get the attached subprogram.
639 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
640 /// to \a DISubprogram.
641 DISubprogram *getSubprogram() const;
644 void allocHungoffUselist();
645 template<int Idx> void setHungoffOperand(Constant *C);
647 // Shadow Value::setValueSubclassData with a private forwarding method so that
648 // subclasses cannot accidentally use it.
649 void setValueSubclassData(unsigned short D) {
650 Value::setValueSubclassData(D);
652 void setValueSubclassDataBit(unsigned Bit, bool On);
656 struct OperandTraits<Function> : public HungoffOperandTraits<3> {};
658 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
660 } // End llvm namespace