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-6: CallingConvention
70 /// Bits from GlobalObject::GlobalObjectSubclassData.
72 /// Whether this function is materializable.
73 IsMaterializableBit = 1 << 0,
74 HasMetadataHashEntryBit = 1 << 1
76 void setGlobalObjectBit(unsigned Mask, bool Value) {
77 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
81 friend class SymbolTableListTraits<Function>;
83 void setParent(Module *parent);
85 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
86 /// built on demand, so that the list isn't allocated until the first client
87 /// needs it. The hasLazyArguments predicate returns true if the arg list
88 /// hasn't been set up yet.
89 bool hasLazyArguments() const {
90 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(1) Function(Ty, Linkage, N, M);
114 ~Function() override;
116 /// \brief Provide fast operand accessors
117 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
119 /// \brief Get the personality function associated with this function.
120 bool hasPersonalityFn() const { return getNumOperands() != 0; }
121 Constant *getPersonalityFn() const {
122 assert(hasPersonalityFn());
123 return cast<Constant>(Op<0>());
125 void setPersonalityFn(Constant *C);
127 Type *getReturnType() const; // Return the type of the ret val
128 FunctionType *getFunctionType() const; // Return the FunctionType for me
130 /// getContext - Return a reference to the LLVMContext associated with this
132 LLVMContext &getContext() const;
134 /// isVarArg - Return true if this function takes a variable number of
136 bool isVarArg() const;
138 bool isMaterializable() const;
139 void setIsMaterializable(bool V);
141 /// getIntrinsicID - This method returns the ID number of the specified
142 /// function, or Intrinsic::not_intrinsic if the function is not an
143 /// intrinsic, or if the pointer is null. This value is always defined to be
144 /// zero to allow easy checking for whether a function is intrinsic or not.
145 /// The particular intrinsic functions which correspond to this value are
146 /// defined in llvm/Intrinsics.h.
147 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
148 bool isIntrinsic() const { return getName().startswith("llvm."); }
150 /// \brief Recalculate the ID for this function if it is an Intrinsic defined
151 /// in llvm/Intrinsics.h. Sets the intrinsic ID to Intrinsic::not_intrinsic
152 /// if the name of this function does not match an intrinsic in that header.
153 /// Note, this method does not need to be called directly, as it is called
154 /// from Value::setName() whenever the name of this function changes.
155 void recalculateIntrinsicID();
157 /// getCallingConv()/setCallingConv(CC) - These method get and set the
158 /// calling convention of this function. The enum values for the known
159 /// calling conventions are defined in CallingConv.h.
160 CallingConv::ID getCallingConv() const {
161 return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 3);
163 void setCallingConv(CallingConv::ID CC) {
164 setValueSubclassData((getSubclassDataFromValue() & 7) |
165 (static_cast<unsigned>(CC) << 3));
168 /// @brief Return the attribute list for this Function.
169 AttributeSet getAttributes() const { return AttributeSets; }
171 /// @brief Set the attribute list for this Function.
172 void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
174 /// @brief Add function attributes to this function.
175 void addFnAttr(Attribute::AttrKind N) {
176 setAttributes(AttributeSets.addAttribute(getContext(),
177 AttributeSet::FunctionIndex, N));
180 /// @brief Remove function attributes from this function.
181 void removeFnAttr(Attribute::AttrKind N) {
182 setAttributes(AttributeSets.removeAttribute(
183 getContext(), AttributeSet::FunctionIndex, N));
186 /// @brief Add function attributes to this function.
187 void addFnAttr(StringRef Kind) {
189 AttributeSets.addAttribute(getContext(),
190 AttributeSet::FunctionIndex, Kind));
192 void addFnAttr(StringRef Kind, StringRef Value) {
194 AttributeSets.addAttribute(getContext(),
195 AttributeSet::FunctionIndex, Kind, Value));
198 /// Set the entry count for this function.
199 void setEntryCount(uint64_t Count);
201 /// Get the entry count for this function.
202 Optional<uint64_t> getEntryCount() const;
204 /// @brief Return true if the function has the attribute.
205 bool hasFnAttribute(Attribute::AttrKind Kind) const {
206 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
208 bool hasFnAttribute(StringRef Kind) const {
209 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
212 /// @brief Return the attribute for the given attribute kind.
213 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
214 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
216 Attribute getFnAttribute(StringRef Kind) const {
217 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
220 /// \brief Return the stack alignment for the function.
221 unsigned getFnStackAlignment() const {
222 return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
225 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
226 /// to use during code generation.
228 const char *getGC() const;
229 void setGC(const char *Str);
232 /// @brief adds the attribute to the list of attributes.
233 void addAttribute(unsigned i, Attribute::AttrKind attr);
235 /// @brief adds the attributes to the list of attributes.
236 void addAttributes(unsigned i, AttributeSet attrs);
238 /// @brief removes the attributes from the list of attributes.
239 void removeAttributes(unsigned i, AttributeSet attr);
241 /// @brief adds the dereferenceable attribute to the list of attributes.
242 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
244 /// @brief adds the dereferenceable_or_null attribute to the list of
246 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
248 /// @brief Extract the alignment for a call or parameter (0=unknown).
249 unsigned getParamAlignment(unsigned i) const {
250 return AttributeSets.getParamAlignment(i);
253 /// @brief Extract the number of dereferenceable bytes for a call or
254 /// parameter (0=unknown).
255 uint64_t getDereferenceableBytes(unsigned i) const {
256 return AttributeSets.getDereferenceableBytes(i);
259 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
260 /// parameter (0=unknown).
261 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
262 return AttributeSets.getDereferenceableOrNullBytes(i);
265 /// @brief Determine if the function does not access memory.
266 bool doesNotAccessMemory() const {
267 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
268 Attribute::ReadNone);
270 void setDoesNotAccessMemory() {
271 addFnAttr(Attribute::ReadNone);
274 /// @brief Determine if the function does not access or only reads memory.
275 bool onlyReadsMemory() const {
276 return doesNotAccessMemory() ||
277 AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
278 Attribute::ReadOnly);
280 void setOnlyReadsMemory() {
281 addFnAttr(Attribute::ReadOnly);
284 /// @brief Determine if the call can access memmory only using pointers based
285 /// on its arguments.
286 bool onlyAccessesArgMemory() const {
287 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
288 Attribute::ArgMemOnly);
290 void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); }
292 /// @brief Determine if the function cannot return.
293 bool doesNotReturn() const {
294 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
295 Attribute::NoReturn);
297 void setDoesNotReturn() {
298 addFnAttr(Attribute::NoReturn);
301 /// @brief Determine if the function cannot unwind.
302 bool doesNotThrow() const {
303 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
304 Attribute::NoUnwind);
306 void setDoesNotThrow() {
307 addFnAttr(Attribute::NoUnwind);
310 /// @brief Determine if the call cannot be duplicated.
311 bool cannotDuplicate() const {
312 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
313 Attribute::NoDuplicate);
315 void setCannotDuplicate() {
316 addFnAttr(Attribute::NoDuplicate);
319 /// @brief Determine if the call is convergent.
320 bool isConvergent() const {
321 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
322 Attribute::Convergent);
324 void setConvergent() {
325 addFnAttr(Attribute::Convergent);
329 /// @brief True if the ABI mandates (or the user requested) that this
330 /// function be in a unwind table.
331 bool hasUWTable() const {
332 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
335 void setHasUWTable() {
336 addFnAttr(Attribute::UWTable);
339 /// @brief True if this function needs an unwind table.
340 bool needsUnwindTableEntry() const {
341 return hasUWTable() || !doesNotThrow();
344 /// @brief Determine if the function returns a structure through first
345 /// pointer argument.
346 bool hasStructRetAttr() const {
347 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
348 AttributeSets.hasAttribute(2, Attribute::StructRet);
351 /// @brief Determine if the parameter does not alias other parameters.
352 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
353 bool doesNotAlias(unsigned n) const {
354 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
356 void setDoesNotAlias(unsigned n) {
357 addAttribute(n, Attribute::NoAlias);
360 /// @brief Determine if the parameter can be captured.
361 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
362 bool doesNotCapture(unsigned n) const {
363 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
365 void setDoesNotCapture(unsigned n) {
366 addAttribute(n, Attribute::NoCapture);
369 bool doesNotAccessMemory(unsigned n) const {
370 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
372 void setDoesNotAccessMemory(unsigned n) {
373 addAttribute(n, Attribute::ReadNone);
376 bool onlyReadsMemory(unsigned n) const {
377 return doesNotAccessMemory(n) ||
378 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
380 void setOnlyReadsMemory(unsigned n) {
381 addAttribute(n, Attribute::ReadOnly);
384 /// Optimize this function for minimum size (-Oz).
385 bool optForMinSize() const { return hasFnAttribute(Attribute::MinSize); };
387 /// Optimize this function for size (-Os) or minimum size (-Oz).
388 bool optForSize() const {
389 return hasFnAttribute(Attribute::OptimizeForSize) || optForMinSize();
392 /// copyAttributesFrom - copy all additional attributes (those not needed to
393 /// create a Function) from the Function Src to this one.
394 void copyAttributesFrom(const GlobalValue *Src) override;
396 /// deleteBody - This method deletes the body of the function, and converts
397 /// the linkage to external.
401 setLinkage(ExternalLinkage);
404 /// removeFromParent - This method unlinks 'this' from the containing module,
405 /// but does not delete it.
407 void removeFromParent() override;
409 /// eraseFromParent - This method unlinks 'this' from the containing module
412 void eraseFromParent() override;
414 /// Get the underlying elements of the Function... the basic block list is
415 /// empty for external functions.
417 const ArgumentListType &getArgumentList() const {
418 CheckLazyArguments();
421 ArgumentListType &getArgumentList() {
422 CheckLazyArguments();
425 static ArgumentListType Function::*getSublistAccess(Argument*) {
426 return &Function::ArgumentList;
429 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
430 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
431 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
432 return &Function::BasicBlocks;
435 const BasicBlock &getEntryBlock() const { return front(); }
436 BasicBlock &getEntryBlock() { return front(); }
438 //===--------------------------------------------------------------------===//
439 // Symbol Table Accessing functions...
441 /// getSymbolTable() - Return the symbol table...
443 inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
444 inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
446 //===--------------------------------------------------------------------===//
447 // BasicBlock iterator forwarding functions
449 iterator begin() { return BasicBlocks.begin(); }
450 const_iterator begin() const { return BasicBlocks.begin(); }
451 iterator end () { return BasicBlocks.end(); }
452 const_iterator end () const { return BasicBlocks.end(); }
454 size_t size() const { return BasicBlocks.size(); }
455 bool empty() const { return BasicBlocks.empty(); }
456 const BasicBlock &front() const { return BasicBlocks.front(); }
457 BasicBlock &front() { return BasicBlocks.front(); }
458 const BasicBlock &back() const { return BasicBlocks.back(); }
459 BasicBlock &back() { return BasicBlocks.back(); }
461 /// @name Function Argument Iteration
464 arg_iterator arg_begin() {
465 CheckLazyArguments();
466 return ArgumentList.begin();
468 const_arg_iterator arg_begin() const {
469 CheckLazyArguments();
470 return ArgumentList.begin();
472 arg_iterator arg_end() {
473 CheckLazyArguments();
474 return ArgumentList.end();
476 const_arg_iterator arg_end() const {
477 CheckLazyArguments();
478 return ArgumentList.end();
481 iterator_range<arg_iterator> args() {
482 return iterator_range<arg_iterator>(arg_begin(), arg_end());
485 iterator_range<const_arg_iterator> args() const {
486 return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
491 size_t arg_size() const;
492 bool arg_empty() const;
494 bool hasPrefixData() const {
495 return getSubclassDataFromValue() & (1<<1);
498 Constant *getPrefixData() const;
499 void setPrefixData(Constant *PrefixData);
501 bool hasPrologueData() const {
502 return getSubclassDataFromValue() & (1<<2);
505 Constant *getPrologueData() const;
506 void setPrologueData(Constant *PrologueData);
508 /// viewCFG - This function is meant for use from the debugger. You can just
509 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
510 /// program, displaying the CFG of the current function with the code for each
511 /// basic block inside. This depends on there being a 'dot' and 'gv' program
514 void viewCFG() const;
516 /// viewCFGOnly - This function is meant for use from the debugger. It works
517 /// just like viewCFG, but it does not include the contents of basic blocks
518 /// into the nodes, just the label. If you are only interested in the CFG
519 /// this can make the graph smaller.
521 void viewCFGOnly() const;
523 /// Methods for support type inquiry through isa, cast, and dyn_cast:
524 static inline bool classof(const Value *V) {
525 return V->getValueID() == Value::FunctionVal;
528 /// dropAllReferences() - This method causes all the subinstructions to "let
529 /// go" of all references that they are maintaining. This allows one to
530 /// 'delete' a whole module at a time, even though there may be circular
531 /// references... first all references are dropped, and all use counts go to
532 /// zero. Then everything is deleted for real. Note that no operations are
533 /// valid on an object that has "dropped all references", except operator
536 /// Since no other object in the module can have references into the body of a
537 /// function, dropping all references deletes the entire body of the function,
538 /// including any contained basic blocks.
540 void dropAllReferences();
542 /// hasAddressTaken - returns true if there are any uses of this function
543 /// other than direct calls or invokes to it, or blockaddress expressions.
544 /// Optionally passes back an offending user for diagnostic purposes.
546 bool hasAddressTaken(const User** = nullptr) const;
548 /// isDefTriviallyDead - Return true if it is trivially safe to remove
549 /// this function definition from the module (because it isn't externally
550 /// visible, does not have its address taken, and has no callers). To make
551 /// this more accurate, call removeDeadConstantUsers first.
552 bool isDefTriviallyDead() const;
554 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
555 /// setjmp or other function that gcc recognizes as "returning twice".
556 bool callsFunctionThatReturnsTwice() const;
558 /// \brief Check if this has any metadata.
559 bool hasMetadata() const { return hasMetadataHashEntry(); }
561 /// \brief Get the current metadata attachment, if any.
563 /// Returns \c nullptr if such an attachment is missing.
565 MDNode *getMetadata(unsigned KindID) const;
566 MDNode *getMetadata(StringRef Kind) const;
569 /// \brief Set a particular kind of metadata attachment.
571 /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
572 /// replacing it if it already exists.
574 void setMetadata(unsigned KindID, MDNode *MD);
575 void setMetadata(StringRef Kind, MDNode *MD);
578 /// \brief Get all current metadata attachments.
580 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
582 /// \brief Drop metadata not in the given list.
584 /// Drop all metadata from \c this not included in \c KnownIDs.
585 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
587 /// \brief Set the attached subprogram.
589 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
590 void setSubprogram(DISubprogram *SP);
592 /// \brief Get the attached subprogram.
594 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
595 /// to \a DISubprogram.
596 DISubprogram *getSubprogram() const;
599 // Shadow Value::setValueSubclassData with a private forwarding method so that
600 // subclasses cannot accidentally use it.
601 void setValueSubclassData(unsigned short D) {
602 Value::setValueSubclassData(D);
605 bool hasMetadataHashEntry() const {
606 return getGlobalObjectSubClassData() & HasMetadataHashEntryBit;
608 void setHasMetadataHashEntry(bool HasEntry) {
609 setGlobalObjectBit(HasMetadataHashEntryBit, HasEntry);
612 void clearMetadata();
616 struct OperandTraits<Function> : public OptionalOperandTraits<Function> {};
618 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
620 } // End llvm namespace