LLVM  mainline
Function.h
Go to the documentation of this file.
00001 //===-- llvm/Function.h - Class to represent a single function --*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the declaration of the Function class, which represents a
00011 // single function/procedure in LLVM.
00012 //
00013 // A function basically consists of a list of basic blocks, a list of arguments,
00014 // and a symbol table.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #ifndef LLVM_IR_FUNCTION_H
00019 #define LLVM_IR_FUNCTION_H
00020 
00021 #include "llvm/ADT/iterator_range.h"
00022 #include "llvm/ADT/Optional.h"
00023 #include "llvm/IR/Argument.h"
00024 #include "llvm/IR/Attributes.h"
00025 #include "llvm/IR/BasicBlock.h"
00026 #include "llvm/IR/CallingConv.h"
00027 #include "llvm/IR/GlobalObject.h"
00028 #include "llvm/Support/Compiler.h"
00029 
00030 namespace llvm {
00031 
00032 class FunctionType;
00033 class LLVMContext;
00034 
00035 template<> struct ilist_traits<Argument>
00036   : public SymbolTableListTraits<Argument, Function> {
00037 
00038   Argument *createSentinel() const {
00039     return static_cast<Argument*>(&Sentinel);
00040   }
00041   static void destroySentinel(Argument*) {}
00042 
00043   Argument *provideInitialHead() const { return createSentinel(); }
00044   Argument *ensureHead(Argument*) const { return createSentinel(); }
00045   static void noteHead(Argument*, Argument*) {}
00046 
00047   static ValueSymbolTable *getSymTab(Function *ItemParent);
00048 private:
00049   mutable ilist_half_node<Argument> Sentinel;
00050 };
00051 
00052 class Function : public GlobalObject, public ilist_node<Function> {
00053 public:
00054   typedef iplist<Argument> ArgumentListType;
00055   typedef iplist<BasicBlock> BasicBlockListType;
00056 
00057   // BasicBlock iterators...
00058   typedef BasicBlockListType::iterator iterator;
00059   typedef BasicBlockListType::const_iterator const_iterator;
00060 
00061   typedef ArgumentListType::iterator arg_iterator;
00062   typedef ArgumentListType::const_iterator const_arg_iterator;
00063 
00064 private:
00065   // Important things that make up a function!
00066   BasicBlockListType  BasicBlocks;        ///< The basic blocks
00067   mutable ArgumentListType ArgumentList;  ///< The formal arguments
00068   ValueSymbolTable *SymTab;               ///< Symbol table of args/instructions
00069   AttributeSet AttributeSets;             ///< Parameter attributes
00070   FunctionType *Ty;
00071 
00072   /*
00073    * Value::SubclassData
00074    *
00075    * bit 0  : HasLazyArguments
00076    * bit 1  : HasPrefixData
00077    * bit 2  : HasPrologueData
00078    * bit 3-6: CallingConvention
00079    */
00080 
00081   /// Bits from GlobalObject::GlobalObjectSubclassData.
00082   enum {
00083     /// Whether this function is materializable.
00084     IsMaterializableBit = 1 << 0,
00085     HasMetadataHashEntryBit = 1 << 1
00086   };
00087   void setGlobalObjectBit(unsigned Mask, bool Value) {
00088     setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
00089                                 (Value ? Mask : 0u));
00090   }
00091 
00092   friend class SymbolTableListTraits<Function, Module>;
00093 
00094   void setParent(Module *parent);
00095 
00096   /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
00097   /// built on demand, so that the list isn't allocated until the first client
00098   /// needs it.  The hasLazyArguments predicate returns true if the arg list
00099   /// hasn't been set up yet.
00100   bool hasLazyArguments() const {
00101     return getSubclassDataFromValue() & (1<<0);
00102   }
00103   void CheckLazyArguments() const {
00104     if (hasLazyArguments())
00105       BuildLazyArguments();
00106   }
00107   void BuildLazyArguments() const;
00108 
00109   Function(const Function&) = delete;
00110   void operator=(const Function&) = delete;
00111 
00112   /// Function ctor - If the (optional) Module argument is specified, the
00113   /// function is automatically inserted into the end of the function list for
00114   /// the module.
00115   ///
00116   Function(FunctionType *Ty, LinkageTypes Linkage,
00117            const Twine &N = "", Module *M = nullptr);
00118 
00119 public:
00120   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
00121                           const Twine &N = "", Module *M = nullptr) {
00122     return new(0) Function(Ty, Linkage, N, M);
00123   }
00124 
00125   ~Function() override;
00126 
00127   Type *getReturnType() const;           // Return the type of the ret val
00128   FunctionType *getFunctionType() const; // Return the FunctionType for me
00129 
00130   /// getContext - Return a reference to the LLVMContext associated with this
00131   /// function.
00132   LLVMContext &getContext() const;
00133 
00134   /// isVarArg - Return true if this function takes a variable number of
00135   /// arguments.
00136   bool isVarArg() const;
00137 
00138   bool isMaterializable() const;
00139   void setIsMaterializable(bool V);
00140 
00141   /// getIntrinsicID - This method returns the ID number of the specified
00142   /// function, or Intrinsic::not_intrinsic if the function is not an
00143   /// intrinsic, or if the pointer is null.  This value is always defined to be
00144   /// zero to allow easy checking for whether a function is intrinsic or not.
00145   /// The particular intrinsic functions which correspond to this value are
00146   /// defined in llvm/Intrinsics.h.
00147   Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
00148   bool isIntrinsic() const { return getName().startswith("llvm."); }
00149 
00150   /// \brief Recalculate the ID for this function if it is an Intrinsic defined
00151   /// in llvm/Intrinsics.h.  Sets the intrinsic ID to Intrinsic::not_intrinsic
00152   /// if the name of this function does not match an intrinsic in that header.
00153   /// Note, this method does not need to be called directly, as it is called
00154   /// from Value::setName() whenever the name of this function changes.
00155   void recalculateIntrinsicID();
00156 
00157   /// getCallingConv()/setCallingConv(CC) - These method get and set the
00158   /// calling convention of this function.  The enum values for the known
00159   /// calling conventions are defined in CallingConv.h.
00160   CallingConv::ID getCallingConv() const {
00161     return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 3);
00162   }
00163   void setCallingConv(CallingConv::ID CC) {
00164     setValueSubclassData((getSubclassDataFromValue() & 7) |
00165                          (static_cast<unsigned>(CC) << 3));
00166   }
00167 
00168   /// @brief Return the attribute list for this Function.
00169   AttributeSet getAttributes() const { return AttributeSets; }
00170 
00171   /// @brief Set the attribute list for this Function.
00172   void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
00173 
00174   /// @brief Add function attributes to this function.
00175   void addFnAttr(Attribute::AttrKind N) {
00176     setAttributes(AttributeSets.addAttribute(getContext(),
00177                                              AttributeSet::FunctionIndex, N));
00178   }
00179 
00180   /// @brief Remove function attributes from this function.
00181   void removeFnAttr(Attribute::AttrKind N) {
00182     setAttributes(AttributeSets.removeAttribute(
00183         getContext(), AttributeSet::FunctionIndex, N));
00184   }
00185 
00186   /// @brief Add function attributes to this function.
00187   void addFnAttr(StringRef Kind) {
00188     setAttributes(
00189       AttributeSets.addAttribute(getContext(),
00190                                  AttributeSet::FunctionIndex, Kind));
00191   }
00192   void addFnAttr(StringRef Kind, StringRef Value) {
00193     setAttributes(
00194       AttributeSets.addAttribute(getContext(),
00195                                  AttributeSet::FunctionIndex, Kind, Value));
00196   }
00197 
00198   /// Set the entry count for this function.
00199   void setEntryCount(uint64_t Count);
00200 
00201   /// Get the entry count for this function.
00202   Optional<uint64_t> getEntryCount() const;
00203 
00204   /// @brief Return true if the function has the attribute.
00205   bool hasFnAttribute(Attribute::AttrKind Kind) const {
00206     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
00207   }
00208   bool hasFnAttribute(StringRef Kind) const {
00209     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
00210   }
00211 
00212   /// @brief Return the attribute for the given attribute kind.
00213   Attribute getFnAttribute(Attribute::AttrKind Kind) const {
00214     return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
00215   }
00216   Attribute getFnAttribute(StringRef Kind) const {
00217     return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
00218   }
00219 
00220   /// \brief Return the stack alignment for the function.
00221   unsigned getFnStackAlignment() const {
00222     return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
00223   }
00224 
00225   /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
00226   ///                             to use during code generation.
00227   bool hasGC() const;
00228   const char *getGC() const;
00229   void setGC(const char *Str);
00230   void clearGC();
00231 
00232   /// @brief adds the attribute to the list of attributes.
00233   void addAttribute(unsigned i, Attribute::AttrKind attr);
00234 
00235   /// @brief adds the attributes to the list of attributes.
00236   void addAttributes(unsigned i, AttributeSet attrs);
00237 
00238   /// @brief removes the attributes from the list of attributes.
00239   void removeAttributes(unsigned i, AttributeSet attr);
00240 
00241   /// @brief adds the dereferenceable attribute to the list of attributes.
00242   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
00243 
00244   /// @brief adds the dereferenceable_or_null attribute to the list of
00245   /// attributes.
00246   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
00247 
00248   /// @brief Extract the alignment for a call or parameter (0=unknown).
00249   unsigned getParamAlignment(unsigned i) const {
00250     return AttributeSets.getParamAlignment(i);
00251   }
00252 
00253   /// @brief Extract the number of dereferenceable bytes for a call or
00254   /// parameter (0=unknown).
00255   uint64_t getDereferenceableBytes(unsigned i) const {
00256     return AttributeSets.getDereferenceableBytes(i);
00257   }
00258   
00259   /// @brief Extract the number of dereferenceable_or_null bytes for a call or
00260   /// parameter (0=unknown).
00261   uint64_t getDereferenceableOrNullBytes(unsigned i) const {
00262     return AttributeSets.getDereferenceableOrNullBytes(i);
00263   }
00264   
00265   /// @brief Determine if the function does not access memory.
00266   bool doesNotAccessMemory() const {
00267     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00268                                       Attribute::ReadNone);
00269   }
00270   void setDoesNotAccessMemory() {
00271     addFnAttr(Attribute::ReadNone);
00272   }
00273 
00274   /// @brief Determine if the function does not access or only reads memory.
00275   bool onlyReadsMemory() const {
00276     return doesNotAccessMemory() ||
00277       AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00278                                  Attribute::ReadOnly);
00279   }
00280   void setOnlyReadsMemory() {
00281     addFnAttr(Attribute::ReadOnly);
00282   }
00283 
00284   /// @brief Determine if the function cannot return.
00285   bool doesNotReturn() const {
00286     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00287                                       Attribute::NoReturn);
00288   }
00289   void setDoesNotReturn() {
00290     addFnAttr(Attribute::NoReturn);
00291   }
00292 
00293   /// @brief Determine if the function cannot unwind.
00294   bool doesNotThrow() const {
00295     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00296                                       Attribute::NoUnwind);
00297   }
00298   void setDoesNotThrow() {
00299     addFnAttr(Attribute::NoUnwind);
00300   }
00301 
00302   /// @brief Determine if the call cannot be duplicated.
00303   bool cannotDuplicate() const {
00304     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00305                                       Attribute::NoDuplicate);
00306   }
00307   void setCannotDuplicate() {
00308     addFnAttr(Attribute::NoDuplicate);
00309   }
00310 
00311   /// @brief Determine if the call is convergent.
00312   bool isConvergent() const {
00313     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00314                                       Attribute::Convergent);
00315   }
00316   void setConvergent() {
00317     addFnAttr(Attribute::Convergent);
00318   }
00319 
00320 
00321   /// @brief True if the ABI mandates (or the user requested) that this
00322   /// function be in a unwind table.
00323   bool hasUWTable() const {
00324     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
00325                                       Attribute::UWTable);
00326   }
00327   void setHasUWTable() {
00328     addFnAttr(Attribute::UWTable);
00329   }
00330 
00331   /// @brief True if this function needs an unwind table.
00332   bool needsUnwindTableEntry() const {
00333     return hasUWTable() || !doesNotThrow();
00334   }
00335 
00336   /// @brief Determine if the function returns a structure through first
00337   /// pointer argument.
00338   bool hasStructRetAttr() const {
00339     return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
00340            AttributeSets.hasAttribute(2, Attribute::StructRet);
00341   }
00342 
00343   /// @brief Determine if the parameter does not alias other parameters.
00344   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
00345   bool doesNotAlias(unsigned n) const {
00346     return AttributeSets.hasAttribute(n, Attribute::NoAlias);
00347   }
00348   void setDoesNotAlias(unsigned n) {
00349     addAttribute(n, Attribute::NoAlias);
00350   }
00351 
00352   /// @brief Determine if the parameter can be captured.
00353   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
00354   bool doesNotCapture(unsigned n) const {
00355     return AttributeSets.hasAttribute(n, Attribute::NoCapture);
00356   }
00357   void setDoesNotCapture(unsigned n) {
00358     addAttribute(n, Attribute::NoCapture);
00359   }
00360 
00361   bool doesNotAccessMemory(unsigned n) const {
00362     return AttributeSets.hasAttribute(n, Attribute::ReadNone);
00363   }
00364   void setDoesNotAccessMemory(unsigned n) {
00365     addAttribute(n, Attribute::ReadNone);
00366   }
00367 
00368   bool onlyReadsMemory(unsigned n) const {
00369     return doesNotAccessMemory(n) ||
00370       AttributeSets.hasAttribute(n, Attribute::ReadOnly);
00371   }
00372   void setOnlyReadsMemory(unsigned n) {
00373     addAttribute(n, Attribute::ReadOnly);
00374   }
00375 
00376   /// copyAttributesFrom - copy all additional attributes (those not needed to
00377   /// create a Function) from the Function Src to this one.
00378   void copyAttributesFrom(const GlobalValue *Src) override;
00379 
00380   /// deleteBody - This method deletes the body of the function, and converts
00381   /// the linkage to external.
00382   ///
00383   void deleteBody() {
00384     dropAllReferences();
00385     setLinkage(ExternalLinkage);
00386   }
00387 
00388   /// removeFromParent - This method unlinks 'this' from the containing module,
00389   /// but does not delete it.
00390   ///
00391   void removeFromParent() override;
00392 
00393   /// eraseFromParent - This method unlinks 'this' from the containing module
00394   /// and deletes it.
00395   ///
00396   void eraseFromParent() override;
00397 
00398 
00399   /// Get the underlying elements of the Function... the basic block list is
00400   /// empty for external functions.
00401   ///
00402   const ArgumentListType &getArgumentList() const {
00403     CheckLazyArguments();
00404     return ArgumentList;
00405   }
00406   ArgumentListType &getArgumentList() {
00407     CheckLazyArguments();
00408     return ArgumentList;
00409   }
00410   static iplist<Argument> Function::*getSublistAccess(Argument*) {
00411     return &Function::ArgumentList;
00412   }
00413 
00414   const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
00415         BasicBlockListType &getBasicBlockList()       { return BasicBlocks; }
00416   static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
00417     return &Function::BasicBlocks;
00418   }
00419 
00420   const BasicBlock       &getEntryBlock() const   { return front(); }
00421         BasicBlock       &getEntryBlock()         { return front(); }
00422 
00423   //===--------------------------------------------------------------------===//
00424   // Symbol Table Accessing functions...
00425 
00426   /// getSymbolTable() - Return the symbol table...
00427   ///
00428   inline       ValueSymbolTable &getValueSymbolTable()       { return *SymTab; }
00429   inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
00430 
00431 
00432   //===--------------------------------------------------------------------===//
00433   // BasicBlock iterator forwarding functions
00434   //
00435   iterator                begin()       { return BasicBlocks.begin(); }
00436   const_iterator          begin() const { return BasicBlocks.begin(); }
00437   iterator                end  ()       { return BasicBlocks.end();   }
00438   const_iterator          end  () const { return BasicBlocks.end();   }
00439 
00440   size_t                   size() const { return BasicBlocks.size();  }
00441   bool                    empty() const { return BasicBlocks.empty(); }
00442   const BasicBlock       &front() const { return BasicBlocks.front(); }
00443         BasicBlock       &front()       { return BasicBlocks.front(); }
00444   const BasicBlock        &back() const { return BasicBlocks.back();  }
00445         BasicBlock        &back()       { return BasicBlocks.back();  }
00446 
00447 /// @name Function Argument Iteration
00448 /// @{
00449 
00450   arg_iterator arg_begin() {
00451     CheckLazyArguments();
00452     return ArgumentList.begin();
00453   }
00454   const_arg_iterator arg_begin() const {
00455     CheckLazyArguments();
00456     return ArgumentList.begin();
00457   }
00458   arg_iterator arg_end() {
00459     CheckLazyArguments();
00460     return ArgumentList.end();
00461   }
00462   const_arg_iterator arg_end() const {
00463     CheckLazyArguments();
00464     return ArgumentList.end();
00465   }
00466 
00467   iterator_range<arg_iterator> args() {
00468     return iterator_range<arg_iterator>(arg_begin(), arg_end());
00469   }
00470 
00471   iterator_range<const_arg_iterator> args() const {
00472     return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
00473   }
00474 
00475 /// @}
00476 
00477   size_t arg_size() const;
00478   bool arg_empty() const;
00479 
00480   bool hasPrefixData() const {
00481     return getSubclassDataFromValue() & (1<<1);
00482   }
00483 
00484   Constant *getPrefixData() const;
00485   void setPrefixData(Constant *PrefixData);
00486 
00487   bool hasPrologueData() const {
00488     return getSubclassDataFromValue() & (1<<2);
00489   }
00490 
00491   Constant *getPrologueData() const;
00492   void setPrologueData(Constant *PrologueData);
00493 
00494   /// Print the function to an output stream with an optional
00495   /// AssemblyAnnotationWriter.
00496   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr) const;
00497 
00498   /// viewCFG - This function is meant for use from the debugger.  You can just
00499   /// say 'call F->viewCFG()' and a ghostview window should pop up from the
00500   /// program, displaying the CFG of the current function with the code for each
00501   /// basic block inside.  This depends on there being a 'dot' and 'gv' program
00502   /// in your path.
00503   ///
00504   void viewCFG() const;
00505 
00506   /// viewCFGOnly - This function is meant for use from the debugger.  It works
00507   /// just like viewCFG, but it does not include the contents of basic blocks
00508   /// into the nodes, just the label.  If you are only interested in the CFG
00509   /// this can make the graph smaller.
00510   ///
00511   void viewCFGOnly() const;
00512 
00513   /// Methods for support type inquiry through isa, cast, and dyn_cast:
00514   static inline bool classof(const Value *V) {
00515     return V->getValueID() == Value::FunctionVal;
00516   }
00517 
00518   /// dropAllReferences() - This method causes all the subinstructions to "let
00519   /// go" of all references that they are maintaining.  This allows one to
00520   /// 'delete' a whole module at a time, even though there may be circular
00521   /// references... first all references are dropped, and all use counts go to
00522   /// zero.  Then everything is deleted for real.  Note that no operations are
00523   /// valid on an object that has "dropped all references", except operator
00524   /// delete.
00525   ///
00526   /// Since no other object in the module can have references into the body of a
00527   /// function, dropping all references deletes the entire body of the function,
00528   /// including any contained basic blocks.
00529   ///
00530   void dropAllReferences();
00531 
00532   /// hasAddressTaken - returns true if there are any uses of this function
00533   /// other than direct calls or invokes to it, or blockaddress expressions.
00534   /// Optionally passes back an offending user for diagnostic purposes.
00535   ///
00536   bool hasAddressTaken(const User** = nullptr) const;
00537 
00538   /// isDefTriviallyDead - Return true if it is trivially safe to remove
00539   /// this function definition from the module (because it isn't externally
00540   /// visible, does not have its address taken, and has no callers).  To make
00541   /// this more accurate, call removeDeadConstantUsers first.
00542   bool isDefTriviallyDead() const;
00543 
00544   /// callsFunctionThatReturnsTwice - Return true if the function has a call to
00545   /// setjmp or other function that gcc recognizes as "returning twice".
00546   bool callsFunctionThatReturnsTwice() const;
00547 
00548   /// \brief Check if this has any metadata.
00549   bool hasMetadata() const { return hasMetadataHashEntry(); }
00550 
00551   /// \brief Get the current metadata attachment, if any.
00552   ///
00553   /// Returns \c nullptr if such an attachment is missing.
00554   /// @{
00555   MDNode *getMetadata(unsigned KindID) const;
00556   MDNode *getMetadata(StringRef Kind) const;
00557   /// @}
00558 
00559   /// \brief Set a particular kind of metadata attachment.
00560   ///
00561   /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
00562   /// replacing it if it already exists.
00563   /// @{
00564   void setMetadata(unsigned KindID, MDNode *MD);
00565   void setMetadata(StringRef Kind, MDNode *MD);
00566   /// @}
00567 
00568   /// \brief Get all current metadata attachments.
00569   void
00570   getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
00571 
00572   /// \brief Drop metadata not in the given list.
00573   ///
00574   /// Drop all metadata from \c this not included in \c KnownIDs.
00575   void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
00576 
00577 private:
00578   // Shadow Value::setValueSubclassData with a private forwarding method so that
00579   // subclasses cannot accidentally use it.
00580   void setValueSubclassData(unsigned short D) {
00581     Value::setValueSubclassData(D);
00582   }
00583 
00584   bool hasMetadataHashEntry() const {
00585     return getGlobalObjectSubClassData() & HasMetadataHashEntryBit;
00586   }
00587   void setHasMetadataHashEntry(bool HasEntry) {
00588     setGlobalObjectBit(HasMetadataHashEntryBit, HasEntry);
00589   }
00590 
00591   void clearMetadata();
00592 };
00593 
00594 inline ValueSymbolTable *
00595 ilist_traits<BasicBlock>::getSymTab(Function *F) {
00596   return F ? &F->getValueSymbolTable() : nullptr;
00597 }
00598 
00599 inline ValueSymbolTable *
00600 ilist_traits<Argument>::getSymTab(Function *F) {
00601   return F ? &F->getValueSymbolTable() : nullptr;
00602 }
00603 
00604 } // End llvm namespace
00605 
00606 #endif