Move the personality function from LandingPadInst to Function
[oota-llvm.git] / include / llvm / IR / Function.h
1 //===-- llvm/Function.h - Class to represent a single function --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the declaration of the Function class, which represents a
11 // single function/procedure in LLVM.
12 //
13 // A function basically consists of a list of basic blocks, a list of arguments,
14 // and a symbol table.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #ifndef LLVM_IR_FUNCTION_H
19 #define LLVM_IR_FUNCTION_H
20
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"
30
31 namespace llvm {
32
33 class FunctionType;
34 class LLVMContext;
35
36 template<> struct ilist_traits<Argument>
37   : public SymbolTableListTraits<Argument, Function> {
38
39   Argument *createSentinel() const {
40     return static_cast<Argument*>(&Sentinel);
41   }
42   static void destroySentinel(Argument*) {}
43
44   Argument *provideInitialHead() const { return createSentinel(); }
45   Argument *ensureHead(Argument*) const { return createSentinel(); }
46   static void noteHead(Argument*, Argument*) {}
47
48   static ValueSymbolTable *getSymTab(Function *ItemParent);
49 private:
50   mutable ilist_half_node<Argument> Sentinel;
51 };
52
53 class Function : public GlobalObject, public ilist_node<Function> {
54 public:
55   typedef iplist<Argument> ArgumentListType;
56   typedef iplist<BasicBlock> BasicBlockListType;
57
58   // BasicBlock iterators...
59   typedef BasicBlockListType::iterator iterator;
60   typedef BasicBlockListType::const_iterator const_iterator;
61
62   typedef ArgumentListType::iterator arg_iterator;
63   typedef ArgumentListType::const_iterator const_arg_iterator;
64
65 private:
66   // Important things that make up a function!
67   BasicBlockListType  BasicBlocks;        ///< The basic blocks
68   mutable ArgumentListType ArgumentList;  ///< The formal arguments
69   ValueSymbolTable *SymTab;               ///< Symbol table of args/instructions
70   AttributeSet AttributeSets;             ///< Parameter attributes
71   FunctionType *Ty;
72
73   /*
74    * Value::SubclassData
75    *
76    * bit 0  : HasLazyArguments
77    * bit 1  : HasPrefixData
78    * bit 2  : HasPrologueData
79    * bit 3-6: CallingConvention
80    */
81
82   /// Bits from GlobalObject::GlobalObjectSubclassData.
83   enum {
84     /// Whether this function is materializable.
85     IsMaterializableBit = 1 << 0,
86     HasMetadataHashEntryBit = 1 << 1
87   };
88   void setGlobalObjectBit(unsigned Mask, bool Value) {
89     setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
90                                 (Value ? Mask : 0u));
91   }
92
93   friend class SymbolTableListTraits<Function, Module>;
94
95   void setParent(Module *parent);
96
97   /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
98   /// built on demand, so that the list isn't allocated until the first client
99   /// needs it.  The hasLazyArguments predicate returns true if the arg list
100   /// hasn't been set up yet.
101   bool hasLazyArguments() const {
102     return getSubclassDataFromValue() & (1<<0);
103   }
104   void CheckLazyArguments() const {
105     if (hasLazyArguments())
106       BuildLazyArguments();
107   }
108   void BuildLazyArguments() const;
109
110   Function(const Function&) = delete;
111   void operator=(const Function&) = delete;
112
113   /// Function ctor - If the (optional) Module argument is specified, the
114   /// function is automatically inserted into the end of the function list for
115   /// the module.
116   ///
117   Function(FunctionType *Ty, LinkageTypes Linkage,
118            const Twine &N = "", Module *M = nullptr);
119
120 public:
121   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
122                           const Twine &N = "", Module *M = nullptr) {
123     return new(1) Function(Ty, Linkage, N, M);
124   }
125
126   ~Function() override;
127
128   /// \brief Provide fast operand accessors
129   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
130
131   /// \brief Get the personality function associated with this function.
132   bool hasPersonalityFn() const { return getNumOperands() != 0; }
133   Constant *getPersonalityFn() const {
134     assert(hasPersonalityFn());
135     return cast<Constant>(Op<0>());
136   }
137   void setPersonalityFn(Constant *C);
138
139   Type *getReturnType() const;           // Return the type of the ret val
140   FunctionType *getFunctionType() const; // Return the FunctionType for me
141
142   /// getContext - Return a reference to the LLVMContext associated with this
143   /// function.
144   LLVMContext &getContext() const;
145
146   /// isVarArg - Return true if this function takes a variable number of
147   /// arguments.
148   bool isVarArg() const;
149
150   bool isMaterializable() const;
151   void setIsMaterializable(bool V);
152
153   /// getIntrinsicID - This method returns the ID number of the specified
154   /// function, or Intrinsic::not_intrinsic if the function is not an
155   /// intrinsic, or if the pointer is null.  This value is always defined to be
156   /// zero to allow easy checking for whether a function is intrinsic or not.
157   /// The particular intrinsic functions which correspond to this value are
158   /// defined in llvm/Intrinsics.h.
159   Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
160   bool isIntrinsic() const { return getName().startswith("llvm."); }
161
162   /// \brief Recalculate the ID for this function if it is an Intrinsic defined
163   /// in llvm/Intrinsics.h.  Sets the intrinsic ID to Intrinsic::not_intrinsic
164   /// if the name of this function does not match an intrinsic in that header.
165   /// Note, this method does not need to be called directly, as it is called
166   /// from Value::setName() whenever the name of this function changes.
167   void recalculateIntrinsicID();
168
169   /// getCallingConv()/setCallingConv(CC) - These method get and set the
170   /// calling convention of this function.  The enum values for the known
171   /// calling conventions are defined in CallingConv.h.
172   CallingConv::ID getCallingConv() const {
173     return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 3);
174   }
175   void setCallingConv(CallingConv::ID CC) {
176     setValueSubclassData((getSubclassDataFromValue() & 7) |
177                          (static_cast<unsigned>(CC) << 3));
178   }
179
180   /// @brief Return the attribute list for this Function.
181   AttributeSet getAttributes() const { return AttributeSets; }
182
183   /// @brief Set the attribute list for this Function.
184   void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
185
186   /// @brief Add function attributes to this function.
187   void addFnAttr(Attribute::AttrKind N) {
188     setAttributes(AttributeSets.addAttribute(getContext(),
189                                              AttributeSet::FunctionIndex, N));
190   }
191
192   /// @brief Remove function attributes from this function.
193   void removeFnAttr(Attribute::AttrKind N) {
194     setAttributes(AttributeSets.removeAttribute(
195         getContext(), AttributeSet::FunctionIndex, N));
196   }
197
198   /// @brief Add function attributes to this function.
199   void addFnAttr(StringRef Kind) {
200     setAttributes(
201       AttributeSets.addAttribute(getContext(),
202                                  AttributeSet::FunctionIndex, Kind));
203   }
204   void addFnAttr(StringRef Kind, StringRef Value) {
205     setAttributes(
206       AttributeSets.addAttribute(getContext(),
207                                  AttributeSet::FunctionIndex, Kind, Value));
208   }
209
210   /// Set the entry count for this function.
211   void setEntryCount(uint64_t Count);
212
213   /// Get the entry count for this function.
214   Optional<uint64_t> getEntryCount() const;
215
216   /// @brief Return true if the function has the attribute.
217   bool hasFnAttribute(Attribute::AttrKind Kind) const {
218     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
219   }
220   bool hasFnAttribute(StringRef Kind) const {
221     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
222   }
223
224   /// @brief Return the attribute for the given attribute kind.
225   Attribute getFnAttribute(Attribute::AttrKind Kind) const {
226     return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
227   }
228   Attribute getFnAttribute(StringRef Kind) const {
229     return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
230   }
231
232   /// \brief Return the stack alignment for the function.
233   unsigned getFnStackAlignment() const {
234     return AttributeSets.getStackAlignment(AttributeSet::FunctionIndex);
235   }
236
237   /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
238   ///                             to use during code generation.
239   bool hasGC() const;
240   const char *getGC() const;
241   void setGC(const char *Str);
242   void clearGC();
243
244   /// @brief adds the attribute to the list of attributes.
245   void addAttribute(unsigned i, Attribute::AttrKind attr);
246
247   /// @brief adds the attributes to the list of attributes.
248   void addAttributes(unsigned i, AttributeSet attrs);
249
250   /// @brief removes the attributes from the list of attributes.
251   void removeAttributes(unsigned i, AttributeSet attr);
252
253   /// @brief adds the dereferenceable attribute to the list of attributes.
254   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
255
256   /// @brief adds the dereferenceable_or_null attribute to the list of
257   /// attributes.
258   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
259
260   /// @brief Extract the alignment for a call or parameter (0=unknown).
261   unsigned getParamAlignment(unsigned i) const {
262     return AttributeSets.getParamAlignment(i);
263   }
264
265   /// @brief Extract the number of dereferenceable bytes for a call or
266   /// parameter (0=unknown).
267   uint64_t getDereferenceableBytes(unsigned i) const {
268     return AttributeSets.getDereferenceableBytes(i);
269   }
270   
271   /// @brief Extract the number of dereferenceable_or_null bytes for a call or
272   /// parameter (0=unknown).
273   uint64_t getDereferenceableOrNullBytes(unsigned i) const {
274     return AttributeSets.getDereferenceableOrNullBytes(i);
275   }
276   
277   /// @brief Determine if the function does not access memory.
278   bool doesNotAccessMemory() const {
279     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
280                                       Attribute::ReadNone);
281   }
282   void setDoesNotAccessMemory() {
283     addFnAttr(Attribute::ReadNone);
284   }
285
286   /// @brief Determine if the function does not access or only reads memory.
287   bool onlyReadsMemory() const {
288     return doesNotAccessMemory() ||
289       AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
290                                  Attribute::ReadOnly);
291   }
292   void setOnlyReadsMemory() {
293     addFnAttr(Attribute::ReadOnly);
294   }
295
296   /// @brief Determine if the function cannot return.
297   bool doesNotReturn() const {
298     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
299                                       Attribute::NoReturn);
300   }
301   void setDoesNotReturn() {
302     addFnAttr(Attribute::NoReturn);
303   }
304
305   /// @brief Determine if the function cannot unwind.
306   bool doesNotThrow() const {
307     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
308                                       Attribute::NoUnwind);
309   }
310   void setDoesNotThrow() {
311     addFnAttr(Attribute::NoUnwind);
312   }
313
314   /// @brief Determine if the call cannot be duplicated.
315   bool cannotDuplicate() const {
316     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
317                                       Attribute::NoDuplicate);
318   }
319   void setCannotDuplicate() {
320     addFnAttr(Attribute::NoDuplicate);
321   }
322
323   /// @brief Determine if the call is convergent.
324   bool isConvergent() const {
325     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
326                                       Attribute::Convergent);
327   }
328   void setConvergent() {
329     addFnAttr(Attribute::Convergent);
330   }
331
332
333   /// @brief True if the ABI mandates (or the user requested) that this
334   /// function be in a unwind table.
335   bool hasUWTable() const {
336     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
337                                       Attribute::UWTable);
338   }
339   void setHasUWTable() {
340     addFnAttr(Attribute::UWTable);
341   }
342
343   /// @brief True if this function needs an unwind table.
344   bool needsUnwindTableEntry() const {
345     return hasUWTable() || !doesNotThrow();
346   }
347
348   /// @brief Determine if the function returns a structure through first
349   /// pointer argument.
350   bool hasStructRetAttr() const {
351     return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
352            AttributeSets.hasAttribute(2, Attribute::StructRet);
353   }
354
355   /// @brief Determine if the parameter does not alias other parameters.
356   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
357   bool doesNotAlias(unsigned n) const {
358     return AttributeSets.hasAttribute(n, Attribute::NoAlias);
359   }
360   void setDoesNotAlias(unsigned n) {
361     addAttribute(n, Attribute::NoAlias);
362   }
363
364   /// @brief Determine if the parameter can be captured.
365   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
366   bool doesNotCapture(unsigned n) const {
367     return AttributeSets.hasAttribute(n, Attribute::NoCapture);
368   }
369   void setDoesNotCapture(unsigned n) {
370     addAttribute(n, Attribute::NoCapture);
371   }
372
373   bool doesNotAccessMemory(unsigned n) const {
374     return AttributeSets.hasAttribute(n, Attribute::ReadNone);
375   }
376   void setDoesNotAccessMemory(unsigned n) {
377     addAttribute(n, Attribute::ReadNone);
378   }
379
380   bool onlyReadsMemory(unsigned n) const {
381     return doesNotAccessMemory(n) ||
382       AttributeSets.hasAttribute(n, Attribute::ReadOnly);
383   }
384   void setOnlyReadsMemory(unsigned n) {
385     addAttribute(n, Attribute::ReadOnly);
386   }
387
388   /// copyAttributesFrom - copy all additional attributes (those not needed to
389   /// create a Function) from the Function Src to this one.
390   void copyAttributesFrom(const GlobalValue *Src) override;
391
392   /// deleteBody - This method deletes the body of the function, and converts
393   /// the linkage to external.
394   ///
395   void deleteBody() {
396     dropAllReferences();
397     setLinkage(ExternalLinkage);
398   }
399
400   /// removeFromParent - This method unlinks 'this' from the containing module,
401   /// but does not delete it.
402   ///
403   void removeFromParent() override;
404
405   /// eraseFromParent - This method unlinks 'this' from the containing module
406   /// and deletes it.
407   ///
408   void eraseFromParent() override;
409
410
411   /// Get the underlying elements of the Function... the basic block list is
412   /// empty for external functions.
413   ///
414   const ArgumentListType &getArgumentList() const {
415     CheckLazyArguments();
416     return ArgumentList;
417   }
418   ArgumentListType &getArgumentList() {
419     CheckLazyArguments();
420     return ArgumentList;
421   }
422   static iplist<Argument> Function::*getSublistAccess(Argument*) {
423     return &Function::ArgumentList;
424   }
425
426   const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
427         BasicBlockListType &getBasicBlockList()       { return BasicBlocks; }
428   static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
429     return &Function::BasicBlocks;
430   }
431
432   const BasicBlock       &getEntryBlock() const   { return front(); }
433         BasicBlock       &getEntryBlock()         { return front(); }
434
435   //===--------------------------------------------------------------------===//
436   // Symbol Table Accessing functions...
437
438   /// getSymbolTable() - Return the symbol table...
439   ///
440   inline       ValueSymbolTable &getValueSymbolTable()       { return *SymTab; }
441   inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
442
443
444   //===--------------------------------------------------------------------===//
445   // BasicBlock iterator forwarding functions
446   //
447   iterator                begin()       { return BasicBlocks.begin(); }
448   const_iterator          begin() const { return BasicBlocks.begin(); }
449   iterator                end  ()       { return BasicBlocks.end();   }
450   const_iterator          end  () const { return BasicBlocks.end();   }
451
452   size_t                   size() const { return BasicBlocks.size();  }
453   bool                    empty() const { return BasicBlocks.empty(); }
454   const BasicBlock       &front() const { return BasicBlocks.front(); }
455         BasicBlock       &front()       { return BasicBlocks.front(); }
456   const BasicBlock        &back() const { return BasicBlocks.back();  }
457         BasicBlock        &back()       { return BasicBlocks.back();  }
458
459 /// @name Function Argument Iteration
460 /// @{
461
462   arg_iterator arg_begin() {
463     CheckLazyArguments();
464     return ArgumentList.begin();
465   }
466   const_arg_iterator arg_begin() const {
467     CheckLazyArguments();
468     return ArgumentList.begin();
469   }
470   arg_iterator arg_end() {
471     CheckLazyArguments();
472     return ArgumentList.end();
473   }
474   const_arg_iterator arg_end() const {
475     CheckLazyArguments();
476     return ArgumentList.end();
477   }
478
479   iterator_range<arg_iterator> args() {
480     return iterator_range<arg_iterator>(arg_begin(), arg_end());
481   }
482
483   iterator_range<const_arg_iterator> args() const {
484     return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
485   }
486
487 /// @}
488
489   size_t arg_size() const;
490   bool arg_empty() const;
491
492   bool hasPrefixData() const {
493     return getSubclassDataFromValue() & (1<<1);
494   }
495
496   Constant *getPrefixData() const;
497   void setPrefixData(Constant *PrefixData);
498
499   bool hasPrologueData() const {
500     return getSubclassDataFromValue() & (1<<2);
501   }
502
503   Constant *getPrologueData() const;
504   void setPrologueData(Constant *PrologueData);
505
506   /// Print the function to an output stream with an optional
507   /// AssemblyAnnotationWriter.
508   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr) const;
509
510   /// viewCFG - This function is meant for use from the debugger.  You can just
511   /// say 'call F->viewCFG()' and a ghostview window should pop up from the
512   /// program, displaying the CFG of the current function with the code for each
513   /// basic block inside.  This depends on there being a 'dot' and 'gv' program
514   /// in your path.
515   ///
516   void viewCFG() const;
517
518   /// viewCFGOnly - This function is meant for use from the debugger.  It works
519   /// just like viewCFG, but it does not include the contents of basic blocks
520   /// into the nodes, just the label.  If you are only interested in the CFG
521   /// this can make the graph smaller.
522   ///
523   void viewCFGOnly() const;
524
525   /// Methods for support type inquiry through isa, cast, and dyn_cast:
526   static inline bool classof(const Value *V) {
527     return V->getValueID() == Value::FunctionVal;
528   }
529
530   /// dropAllReferences() - This method causes all the subinstructions to "let
531   /// go" of all references that they are maintaining.  This allows one to
532   /// 'delete' a whole module at a time, even though there may be circular
533   /// references... first all references are dropped, and all use counts go to
534   /// zero.  Then everything is deleted for real.  Note that no operations are
535   /// valid on an object that has "dropped all references", except operator
536   /// delete.
537   ///
538   /// Since no other object in the module can have references into the body of a
539   /// function, dropping all references deletes the entire body of the function,
540   /// including any contained basic blocks.
541   ///
542   void dropAllReferences();
543
544   /// hasAddressTaken - returns true if there are any uses of this function
545   /// other than direct calls or invokes to it, or blockaddress expressions.
546   /// Optionally passes back an offending user for diagnostic purposes.
547   ///
548   bool hasAddressTaken(const User** = nullptr) const;
549
550   /// isDefTriviallyDead - Return true if it is trivially safe to remove
551   /// this function definition from the module (because it isn't externally
552   /// visible, does not have its address taken, and has no callers).  To make
553   /// this more accurate, call removeDeadConstantUsers first.
554   bool isDefTriviallyDead() const;
555
556   /// callsFunctionThatReturnsTwice - Return true if the function has a call to
557   /// setjmp or other function that gcc recognizes as "returning twice".
558   bool callsFunctionThatReturnsTwice() const;
559
560   /// \brief Check if this has any metadata.
561   bool hasMetadata() const { return hasMetadataHashEntry(); }
562
563   /// \brief Get the current metadata attachment, if any.
564   ///
565   /// Returns \c nullptr if such an attachment is missing.
566   /// @{
567   MDNode *getMetadata(unsigned KindID) const;
568   MDNode *getMetadata(StringRef Kind) const;
569   /// @}
570
571   /// \brief Set a particular kind of metadata attachment.
572   ///
573   /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
574   /// replacing it if it already exists.
575   /// @{
576   void setMetadata(unsigned KindID, MDNode *MD);
577   void setMetadata(StringRef Kind, MDNode *MD);
578   /// @}
579
580   /// \brief Get all current metadata attachments.
581   void
582   getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
583
584   /// \brief Drop metadata not in the given list.
585   ///
586   /// Drop all metadata from \c this not included in \c KnownIDs.
587   void dropUnknownMetadata(ArrayRef<unsigned> KnownIDs);
588
589 private:
590   // Shadow Value::setValueSubclassData with a private forwarding method so that
591   // subclasses cannot accidentally use it.
592   void setValueSubclassData(unsigned short D) {
593     Value::setValueSubclassData(D);
594   }
595
596   bool hasMetadataHashEntry() const {
597     return getGlobalObjectSubClassData() & HasMetadataHashEntryBit;
598   }
599   void setHasMetadataHashEntry(bool HasEntry) {
600     setGlobalObjectBit(HasMetadataHashEntryBit, HasEntry);
601   }
602
603   void clearMetadata();
604 };
605
606 inline ValueSymbolTable *
607 ilist_traits<BasicBlock>::getSymTab(Function *F) {
608   return F ? &F->getValueSymbolTable() : nullptr;
609 }
610
611 inline ValueSymbolTable *
612 ilist_traits<Argument>::getSymTab(Function *F) {
613   return F ? &F->getValueSymbolTable() : nullptr;
614 }
615
616 template <>
617 struct OperandTraits<Function> : public OptionalOperandTraits<Function> {};
618
619 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
620
621 } // End llvm namespace
622
623 #endif