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/Support/Compiler.h"
34 template<> struct ilist_traits<Argument>
35 : public SymbolTableListTraits<Argument, Function> {
37 Argument *createSentinel() const {
38 return static_cast<Argument*>(&Sentinel);
40 static void destroySentinel(Argument*) {}
42 Argument *provideInitialHead() const { return createSentinel(); }
43 Argument *ensureHead(Argument*) const { return createSentinel(); }
44 static void noteHead(Argument*, Argument*) {}
46 static ValueSymbolTable *getSymTab(Function *ItemParent);
48 mutable ilist_half_node<Argument> Sentinel;
51 class Function : public GlobalObject, public ilist_node<Function> {
53 typedef iplist<Argument> ArgumentListType;
54 typedef iplist<BasicBlock> BasicBlockListType;
56 // BasicBlock iterators...
57 typedef BasicBlockListType::iterator iterator;
58 typedef BasicBlockListType::const_iterator const_iterator;
60 typedef ArgumentListType::iterator arg_iterator;
61 typedef ArgumentListType::const_iterator const_arg_iterator;
64 // Important things that make up a function!
65 BasicBlockListType BasicBlocks; ///< The basic blocks
66 mutable ArgumentListType ArgumentList; ///< The formal arguments
67 ValueSymbolTable *SymTab; ///< Symbol table of args/instructions
68 AttributeSet AttributeSets; ///< Parameter attributes
74 * bit 0 : HasLazyArguments
75 * bit 1 : HasPrefixData
76 * bit 2 : HasPrologueData
77 * bit 3-6: CallingConvention
80 /// Bits from GlobalObject::GlobalObjectSubclassData.
82 /// Whether this function is materializable.
83 IsMaterializableBit = 1 << 0,
84 HasMetadataHashEntryBit = 1 << 1
86 void setGlobalObjectBit(unsigned Mask, bool Value) {
87 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
91 friend class SymbolTableListTraits<Function, Module>;
93 void setParent(Module *parent);
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 bool hasLazyArguments() const {
100 return getSubclassDataFromValue() & (1<<0);
102 void CheckLazyArguments() const {
103 if (hasLazyArguments())
104 BuildLazyArguments();
106 void BuildLazyArguments() const;
108 Function(const Function&) = delete;
109 void operator=(const Function&) = delete;
111 /// Do the actual lookup of an intrinsic ID when the query could not be
112 /// answered from the cache.
113 unsigned lookupIntrinsicID() const LLVM_READONLY;
115 /// Function ctor - If the (optional) Module argument is specified, the
116 /// function is automatically inserted into the end of the function list for
119 Function(FunctionType *Ty, LinkageTypes Linkage,
120 const Twine &N = "", Module *M = nullptr);
123 static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
124 const Twine &N = "", Module *M = nullptr) {
125 return new(0) Function(Ty, Linkage, N, M);
128 ~Function() override;
130 Type *getReturnType() const; // Return the type of the ret val
131 FunctionType *getFunctionType() const; // Return the FunctionType for me
133 /// getContext - Return a pointer to the LLVMContext associated with this
134 /// function, or NULL if this function is not bound to a context yet.
135 LLVMContext &getContext() const;
137 /// isVarArg - Return true if this function takes a variable number of
139 bool isVarArg() const;
141 bool isMaterializable() const;
142 void setIsMaterializable(bool V);
144 /// getIntrinsicID - This method returns the ID number of the specified
145 /// function, or Intrinsic::not_intrinsic if the function is not an
146 /// intrinsic, or if the pointer is null. This value is always defined to be
147 /// zero to allow easy checking for whether a function is intrinsic or not.
148 /// The particular intrinsic functions which correspond to this value are
149 /// defined in llvm/Intrinsics.h. Results are cached in the LLVM context,
150 /// subsequent requests for the same ID return results much faster from the
153 unsigned getIntrinsicID() const LLVM_READONLY;
154 bool isIntrinsic() const { return getName().startswith("llvm."); }
156 /// getCallingConv()/setCallingConv(CC) - These method get and set the
157 /// calling convention of this function. The enum values for the known
158 /// calling conventions are defined in CallingConv.h.
159 CallingConv::ID getCallingConv() const {
160 return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 3);
162 void setCallingConv(CallingConv::ID CC) {
163 setValueSubclassData((getSubclassDataFromValue() & 7) |
164 (static_cast<unsigned>(CC) << 3));
167 /// @brief Return the attribute list for this Function.
168 AttributeSet getAttributes() const { return AttributeSets; }
170 /// @brief Set the attribute list for this Function.
171 void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
173 /// @brief Add function attributes to this function.
174 void addFnAttr(Attribute::AttrKind N) {
175 setAttributes(AttributeSets.addAttribute(getContext(),
176 AttributeSet::FunctionIndex, N));
179 /// @brief Remove function attributes from this function.
180 void removeFnAttr(Attribute::AttrKind N) {
181 setAttributes(AttributeSets.removeAttribute(
182 getContext(), AttributeSet::FunctionIndex, N));
185 /// @brief Add function attributes to this function.
186 void addFnAttr(StringRef Kind) {
188 AttributeSets.addAttribute(getContext(),
189 AttributeSet::FunctionIndex, Kind));
191 void addFnAttr(StringRef Kind, StringRef Value) {
193 AttributeSets.addAttribute(getContext(),
194 AttributeSet::FunctionIndex, Kind, Value));
197 /// @brief Return true if the function has the attribute.
198 bool hasFnAttribute(Attribute::AttrKind Kind) const {
199 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
201 bool hasFnAttribute(StringRef Kind) const {
202 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
205 /// @brief Return the attribute for the given attribute kind.
206 Attribute getFnAttribute(Attribute::AttrKind Kind) const {
207 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
209 Attribute getFnAttribute(StringRef Kind) const {
210 return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
213 /// \brief Return the stack alignment for the function.
214 unsigned getFnStackAlignment() const {
215 return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
218 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
219 /// to use during code generation.
221 const char *getGC() const;
222 void setGC(const char *Str);
225 /// @brief adds the attribute to the list of attributes.
226 void addAttribute(unsigned i, Attribute::AttrKind attr);
228 /// @brief adds the attributes to the list of attributes.
229 void addAttributes(unsigned i, AttributeSet attrs);
231 /// @brief removes the attributes from the list of attributes.
232 void removeAttributes(unsigned i, AttributeSet attr);
234 /// @brief adds the dereferenceable attribute to the list of attributes.
235 void addDereferenceableAttr(unsigned i, uint64_t Bytes);
237 /// @brief adds the dereferenceable_or_null attribute to the list of
239 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
241 /// @brief Extract the alignment for a call or parameter (0=unknown).
242 unsigned getParamAlignment(unsigned i) const {
243 return AttributeSets.getParamAlignment(i);
246 /// @brief Extract the number of dereferenceable bytes for a call or
247 /// parameter (0=unknown).
248 uint64_t getDereferenceableBytes(unsigned i) const {
249 return AttributeSets.getDereferenceableBytes(i);
252 /// @brief Extract the number of dereferenceable_or_null bytes for a call or
253 /// parameter (0=unknown).
254 uint64_t getDereferenceableOrNullBytes(unsigned i) const {
255 return AttributeSets.getDereferenceableOrNullBytes(i);
258 /// @brief Determine if the function does not access memory.
259 bool doesNotAccessMemory() const {
260 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
261 Attribute::ReadNone);
263 void setDoesNotAccessMemory() {
264 addFnAttr(Attribute::ReadNone);
267 /// @brief Determine if the function does not access or only reads memory.
268 bool onlyReadsMemory() const {
269 return doesNotAccessMemory() ||
270 AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
271 Attribute::ReadOnly);
273 void setOnlyReadsMemory() {
274 addFnAttr(Attribute::ReadOnly);
277 /// @brief Determine if the function cannot return.
278 bool doesNotReturn() const {
279 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
280 Attribute::NoReturn);
282 void setDoesNotReturn() {
283 addFnAttr(Attribute::NoReturn);
286 /// @brief Determine if the function cannot unwind.
287 bool doesNotThrow() const {
288 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
289 Attribute::NoUnwind);
291 void setDoesNotThrow() {
292 addFnAttr(Attribute::NoUnwind);
295 /// @brief Determine if the call cannot be duplicated.
296 bool cannotDuplicate() const {
297 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
298 Attribute::NoDuplicate);
300 void setCannotDuplicate() {
301 addFnAttr(Attribute::NoDuplicate);
304 /// @brief True if the ABI mandates (or the user requested) that this
305 /// function be in a unwind table.
306 bool hasUWTable() const {
307 return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
310 void setHasUWTable() {
311 addFnAttr(Attribute::UWTable);
314 /// @brief True if this function needs an unwind table.
315 bool needsUnwindTableEntry() const {
316 return hasUWTable() || !doesNotThrow();
319 /// @brief Determine if the function returns a structure through first
320 /// pointer argument.
321 bool hasStructRetAttr() const {
322 return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
323 AttributeSets.hasAttribute(2, Attribute::StructRet);
326 /// @brief Determine if the parameter does not alias other parameters.
327 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
328 bool doesNotAlias(unsigned n) const {
329 return AttributeSets.hasAttribute(n, Attribute::NoAlias);
331 void setDoesNotAlias(unsigned n) {
332 addAttribute(n, Attribute::NoAlias);
335 /// @brief Determine if the parameter can be captured.
336 /// @param n The parameter to check. 1 is the first parameter, 0 is the return
337 bool doesNotCapture(unsigned n) const {
338 return AttributeSets.hasAttribute(n, Attribute::NoCapture);
340 void setDoesNotCapture(unsigned n) {
341 addAttribute(n, Attribute::NoCapture);
344 bool doesNotAccessMemory(unsigned n) const {
345 return AttributeSets.hasAttribute(n, Attribute::ReadNone);
347 void setDoesNotAccessMemory(unsigned n) {
348 addAttribute(n, Attribute::ReadNone);
351 bool onlyReadsMemory(unsigned n) const {
352 return doesNotAccessMemory(n) ||
353 AttributeSets.hasAttribute(n, Attribute::ReadOnly);
355 void setOnlyReadsMemory(unsigned n) {
356 addAttribute(n, Attribute::ReadOnly);
359 /// copyAttributesFrom - copy all additional attributes (those not needed to
360 /// create a Function) from the Function Src to this one.
361 void copyAttributesFrom(const GlobalValue *Src) override;
363 /// deleteBody - This method deletes the body of the function, and converts
364 /// the linkage to external.
368 setLinkage(ExternalLinkage);
371 /// removeFromParent - This method unlinks 'this' from the containing module,
372 /// but does not delete it.
374 void removeFromParent() override;
376 /// eraseFromParent - This method unlinks 'this' from the containing module
379 void eraseFromParent() override;
382 /// Get the underlying elements of the Function... the basic block list is
383 /// empty for external functions.
385 const ArgumentListType &getArgumentList() const {
386 CheckLazyArguments();
389 ArgumentListType &getArgumentList() {
390 CheckLazyArguments();
393 static iplist<Argument> Function::*getSublistAccess(Argument*) {
394 return &Function::ArgumentList;
397 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
398 BasicBlockListType &getBasicBlockList() { return BasicBlocks; }
399 static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
400 return &Function::BasicBlocks;
403 const BasicBlock &getEntryBlock() const { return front(); }
404 BasicBlock &getEntryBlock() { return front(); }
406 //===--------------------------------------------------------------------===//
407 // Symbol Table Accessing functions...
409 /// getSymbolTable() - Return the symbol table...
411 inline ValueSymbolTable &getValueSymbolTable() { return *SymTab; }
412 inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
415 //===--------------------------------------------------------------------===//
416 // BasicBlock iterator forwarding functions
418 iterator begin() { return BasicBlocks.begin(); }
419 const_iterator begin() const { return BasicBlocks.begin(); }
420 iterator end () { return BasicBlocks.end(); }
421 const_iterator end () const { return BasicBlocks.end(); }
423 size_t size() const { return BasicBlocks.size(); }
424 bool empty() const { return BasicBlocks.empty(); }
425 const BasicBlock &front() const { return BasicBlocks.front(); }
426 BasicBlock &front() { return BasicBlocks.front(); }
427 const BasicBlock &back() const { return BasicBlocks.back(); }
428 BasicBlock &back() { return BasicBlocks.back(); }
430 /// @name Function Argument Iteration
433 arg_iterator arg_begin() {
434 CheckLazyArguments();
435 return ArgumentList.begin();
437 const_arg_iterator arg_begin() const {
438 CheckLazyArguments();
439 return ArgumentList.begin();
441 arg_iterator arg_end() {
442 CheckLazyArguments();
443 return ArgumentList.end();
445 const_arg_iterator arg_end() const {
446 CheckLazyArguments();
447 return ArgumentList.end();
450 iterator_range<arg_iterator> args() {
451 return iterator_range<arg_iterator>(arg_begin(), arg_end());
454 iterator_range<const_arg_iterator> args() const {
455 return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
460 size_t arg_size() const;
461 bool arg_empty() const;
463 bool hasPrefixData() const {
464 return getSubclassDataFromValue() & (1<<1);
467 Constant *getPrefixData() const;
468 void setPrefixData(Constant *PrefixData);
470 bool hasPrologueData() const {
471 return getSubclassDataFromValue() & (1<<2);
474 Constant *getPrologueData() const;
475 void setPrologueData(Constant *PrologueData);
477 /// Print the function to an output stream with an optional
478 /// AssemblyAnnotationWriter.
479 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr) const;
481 /// viewCFG - This function is meant for use from the debugger. You can just
482 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
483 /// program, displaying the CFG of the current function with the code for each
484 /// basic block inside. This depends on there being a 'dot' and 'gv' program
487 void viewCFG() const;
489 /// viewCFGOnly - This function is meant for use from the debugger. It works
490 /// just like viewCFG, but it does not include the contents of basic blocks
491 /// into the nodes, just the label. If you are only interested in the CFG
492 /// this can make the graph smaller.
494 void viewCFGOnly() const;
496 /// Methods for support type inquiry through isa, cast, and dyn_cast:
497 static inline bool classof(const Value *V) {
498 return V->getValueID() == Value::FunctionVal;
501 /// dropAllReferences() - This method causes all the subinstructions to "let
502 /// go" of all references that they are maintaining. This allows one to
503 /// 'delete' a whole module at a time, even though there may be circular
504 /// references... first all references are dropped, and all use counts go to
505 /// zero. Then everything is deleted for real. Note that no operations are
506 /// valid on an object that has "dropped all references", except operator
509 /// Since no other object in the module can have references into the body of a
510 /// function, dropping all references deletes the entire body of the function,
511 /// including any contained basic blocks.
513 void dropAllReferences();
515 /// hasAddressTaken - returns true if there are any uses of this function
516 /// other than direct calls or invokes to it, or blockaddress expressions.
517 /// Optionally passes back an offending user for diagnostic purposes.
519 bool hasAddressTaken(const User** = nullptr) const;
521 /// isDefTriviallyDead - Return true if it is trivially safe to remove
522 /// this function definition from the module (because it isn't externally
523 /// visible, does not have its address taken, and has no callers). To make
524 /// this more accurate, call removeDeadConstantUsers first.
525 bool isDefTriviallyDead() const;
527 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
528 /// setjmp or other function that gcc recognizes as "returning twice".
529 bool callsFunctionThatReturnsTwice() const;
531 /// \brief Check if this has any metadata.
532 bool hasMetadata() const { return hasMetadataHashEntry(); }
534 /// \brief Get the current metadata attachment, if any.
536 /// Returns \c nullptr if such an attachment is missing.
538 MDNode *getMetadata(unsigned KindID) const;
539 MDNode *getMetadata(StringRef Kind) const;
542 /// \brief Set a particular kind of metadata attachment.
544 /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
545 /// replacing it if it already exists.
547 void setMetadata(unsigned KindID, MDNode *MD);
548 void setMetadata(StringRef Kind, MDNode *MD);
551 /// \brief Get all current metadata attachments.
553 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
555 /// \brief Drop metadata not in the given list.
557 /// Drop all metadata from \c this not included in \c KnownIDs.
558 void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
561 // Shadow Value::setValueSubclassData with a private forwarding method so that
562 // subclasses cannot accidentally use it.
563 void setValueSubclassData(unsigned short D) {
564 Value::setValueSubclassData(D);
567 bool hasMetadataHashEntry() const {
568 return getGlobalObjectSubClassData() & HasMetadataHashEntryBit;
570 void setHasMetadataHashEntry(bool HasEntry) {
571 setGlobalObjectBit(HasMetadataHashEntryBit, HasEntry);
574 void clearMetadata();
577 inline ValueSymbolTable *
578 ilist_traits<BasicBlock>::getSymTab(Function *F) {
579 return F ? &F->getValueSymbolTable() : nullptr;
582 inline ValueSymbolTable *
583 ilist_traits<Argument>::getSymTab(Function *F) {
584 return F ? &F->getValueSymbolTable() : nullptr;
587 } // End llvm namespace