Move ownership of GCStrategy objects to LLVMContext
[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/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"
28
29 namespace llvm {
30
31 class FunctionType;
32 class GCStrategy;  
33 class LLVMContext;
34
35 // Traits for intrusive list of basic blocks...
36 template<> struct ilist_traits<BasicBlock>
37   : public SymbolTableListTraits<BasicBlock, Function> {
38
39   // createSentinel is used to get hold of the node that marks the end of the
40   // list... (same trick used here as in ilist_traits<Instruction>)
41   BasicBlock *createSentinel() const {
42     return static_cast<BasicBlock*>(&Sentinel);
43   }
44   static void destroySentinel(BasicBlock*) {}
45
46   BasicBlock *provideInitialHead() const { return createSentinel(); }
47   BasicBlock *ensureHead(BasicBlock*) const { return createSentinel(); }
48   static void noteHead(BasicBlock*, BasicBlock*) {}
49
50   static ValueSymbolTable *getSymTab(Function *ItemParent);
51 private:
52   mutable ilist_half_node<BasicBlock> Sentinel;
53 };
54
55 template<> struct ilist_traits<Argument>
56   : public SymbolTableListTraits<Argument, Function> {
57
58   Argument *createSentinel() const {
59     return static_cast<Argument*>(&Sentinel);
60   }
61   static void destroySentinel(Argument*) {}
62
63   Argument *provideInitialHead() const { return createSentinel(); }
64   Argument *ensureHead(Argument*) const { return createSentinel(); }
65   static void noteHead(Argument*, Argument*) {}
66
67   static ValueSymbolTable *getSymTab(Function *ItemParent);
68 private:
69   mutable ilist_half_node<Argument> Sentinel;
70 };
71
72 class Function : public GlobalObject, public ilist_node<Function> {
73 public:
74   typedef iplist<Argument> ArgumentListType;
75   typedef iplist<BasicBlock> BasicBlockListType;
76
77   // BasicBlock iterators...
78   typedef BasicBlockListType::iterator iterator;
79   typedef BasicBlockListType::const_iterator const_iterator;
80
81   typedef ArgumentListType::iterator arg_iterator;
82   typedef ArgumentListType::const_iterator const_arg_iterator;
83
84 private:
85   // Important things that make up a function!
86   BasicBlockListType  BasicBlocks;        ///< The basic blocks
87   mutable ArgumentListType ArgumentList;  ///< The formal arguments
88   ValueSymbolTable *SymTab;               ///< Symbol table of args/instructions
89   AttributeSet AttributeSets;             ///< Parameter attributes
90
91   /*
92    * Value::SubclassData
93    *
94    * bit 0  : HasLazyArguments
95    * bit 1  : HasPrefixData
96    * bit 2  : HasPrologueData
97    * bit 3-6: CallingConvention
98    */
99
100   friend class SymbolTableListTraits<Function, Module>;
101
102   void setParent(Module *parent);
103
104   /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
105   /// built on demand, so that the list isn't allocated until the first client
106   /// needs it.  The hasLazyArguments predicate returns true if the arg list
107   /// hasn't been set up yet.
108   bool hasLazyArguments() const {
109     return getSubclassDataFromValue() & (1<<0);
110   }
111   void CheckLazyArguments() const {
112     if (hasLazyArguments())
113       BuildLazyArguments();
114   }
115   void BuildLazyArguments() const;
116
117   Function(const Function&) LLVM_DELETED_FUNCTION;
118   void operator=(const Function&) LLVM_DELETED_FUNCTION;
119
120   /// Do the actual lookup of an intrinsic ID when the query could not be
121   /// answered from the cache.
122   unsigned lookupIntrinsicID() const LLVM_READONLY;
123
124   /// Function ctor - If the (optional) Module argument is specified, the
125   /// function is automatically inserted into the end of the function list for
126   /// the module.
127   ///
128   Function(FunctionType *Ty, LinkageTypes Linkage,
129            const Twine &N = "", Module *M = nullptr);
130
131 public:
132   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
133                           const Twine &N = "", Module *M = nullptr) {
134     return new(0) Function(Ty, Linkage, N, M);
135   }
136
137   ~Function();
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 pointer to the LLVMContext associated with this
143   /// function, or NULL if this function is not bound to a context yet.
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.  Results are cached in the LLVM context,
159   /// subsequent requests for the same ID return results much faster from the
160   /// cache.
161   ///
162   unsigned getIntrinsicID() const LLVM_READONLY;
163   bool isIntrinsic() const { return getName().startswith("llvm."); }
164
165   /// getCallingConv()/setCallingConv(CC) - These method get and set the
166   /// calling convention of this function.  The enum values for the known
167   /// calling conventions are defined in CallingConv.h.
168   CallingConv::ID getCallingConv() const {
169     return static_cast<CallingConv::ID>(getSubclassDataFromValue() >> 3);
170   }
171   void setCallingConv(CallingConv::ID CC) {
172     setValueSubclassData((getSubclassDataFromValue() & 7) |
173                          (static_cast<unsigned>(CC) << 3));
174   }
175
176   /// @brief Return the attribute list for this Function.
177   AttributeSet getAttributes() const { return AttributeSets; }
178
179   /// @brief Set the attribute list for this Function.
180   void setAttributes(AttributeSet attrs) { AttributeSets = attrs; }
181
182   /// @brief Add function attributes to this function.
183   void addFnAttr(Attribute::AttrKind N) {
184     setAttributes(AttributeSets.addAttribute(getContext(),
185                                              AttributeSet::FunctionIndex, N));
186   }
187
188   /// @brief Remove function attributes from this function.
189   void removeFnAttr(Attribute::AttrKind N) {
190     setAttributes(AttributeSets.removeAttribute(
191         getContext(), AttributeSet::FunctionIndex, N));
192   }
193
194   /// @brief Add function attributes to this function.
195   void addFnAttr(StringRef Kind) {
196     setAttributes(
197       AttributeSets.addAttribute(getContext(),
198                                  AttributeSet::FunctionIndex, Kind));
199   }
200   void addFnAttr(StringRef Kind, StringRef Value) {
201     setAttributes(
202       AttributeSets.addAttribute(getContext(),
203                                  AttributeSet::FunctionIndex, Kind, Value));
204   }
205
206   /// @brief Return true if the function has the attribute.
207   bool hasFnAttribute(Attribute::AttrKind Kind) const {
208     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
209   }
210   bool hasFnAttribute(StringRef Kind) const {
211     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex, Kind);
212   }
213
214   /// @brief Return the attribute for the given attribute kind.
215   Attribute getFnAttribute(Attribute::AttrKind Kind) const {
216     return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
217   }
218   Attribute getFnAttribute(StringRef Kind) const {
219     return AttributeSets.getAttribute(AttributeSet::FunctionIndex, Kind);
220   }
221
222   /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
223   ///                             to use during code generation.
224   bool hasGC() const;
225   const char *getGC() const;
226   void setGC(const char *Str);
227   void clearGC();
228
229   /// Returns the GCStrategy associated with the specified garbage collector
230   /// algorithm or nullptr if one is not set.
231   GCStrategy *getGCStrategy() const;
232
233   /// @brief adds the attribute to the list of attributes.
234   void addAttribute(unsigned i, Attribute::AttrKind attr);
235
236   /// @brief adds the attributes to the list of attributes.
237   void addAttributes(unsigned i, AttributeSet attrs);
238
239   /// @brief removes the attributes from the list of attributes.
240   void removeAttributes(unsigned i, AttributeSet attr);
241
242   /// @brief Extract the alignment for a call or parameter (0=unknown).
243   unsigned getParamAlignment(unsigned i) const {
244     return AttributeSets.getParamAlignment(i);
245   }
246
247   /// @brief Extract the number of dereferenceable bytes for a call or
248   /// parameter (0=unknown).
249   uint64_t getDereferenceableBytes(unsigned i) const {
250     return AttributeSets.getDereferenceableBytes(i);
251   }
252
253   /// @brief Determine if the function does not access memory.
254   bool doesNotAccessMemory() const {
255     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
256                                       Attribute::ReadNone);
257   }
258   void setDoesNotAccessMemory() {
259     addFnAttr(Attribute::ReadNone);
260   }
261
262   /// @brief Determine if the function does not access or only reads memory.
263   bool onlyReadsMemory() const {
264     return doesNotAccessMemory() ||
265       AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
266                                  Attribute::ReadOnly);
267   }
268   void setOnlyReadsMemory() {
269     addFnAttr(Attribute::ReadOnly);
270   }
271
272   /// @brief Determine if the function cannot return.
273   bool doesNotReturn() const {
274     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
275                                       Attribute::NoReturn);
276   }
277   void setDoesNotReturn() {
278     addFnAttr(Attribute::NoReturn);
279   }
280
281   /// @brief Determine if the function cannot unwind.
282   bool doesNotThrow() const {
283     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
284                                       Attribute::NoUnwind);
285   }
286   void setDoesNotThrow() {
287     addFnAttr(Attribute::NoUnwind);
288   }
289
290   /// @brief Determine if the call cannot be duplicated.
291   bool cannotDuplicate() const {
292     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
293                                       Attribute::NoDuplicate);
294   }
295   void setCannotDuplicate() {
296     addFnAttr(Attribute::NoDuplicate);
297   }
298
299   /// @brief True if the ABI mandates (or the user requested) that this
300   /// function be in a unwind table.
301   bool hasUWTable() const {
302     return AttributeSets.hasAttribute(AttributeSet::FunctionIndex,
303                                       Attribute::UWTable);
304   }
305   void setHasUWTable() {
306     addFnAttr(Attribute::UWTable);
307   }
308
309   /// @brief True if this function needs an unwind table.
310   bool needsUnwindTableEntry() const {
311     return hasUWTable() || !doesNotThrow();
312   }
313
314   /// @brief Determine if the function returns a structure through first
315   /// pointer argument.
316   bool hasStructRetAttr() const {
317     return AttributeSets.hasAttribute(1, Attribute::StructRet) ||
318            AttributeSets.hasAttribute(2, Attribute::StructRet);
319   }
320
321   /// @brief Determine if the parameter does not alias other parameters.
322   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
323   bool doesNotAlias(unsigned n) const {
324     return AttributeSets.hasAttribute(n, Attribute::NoAlias);
325   }
326   void setDoesNotAlias(unsigned n) {
327     addAttribute(n, Attribute::NoAlias);
328   }
329
330   /// @brief Determine if the parameter can be captured.
331   /// @param n The parameter to check. 1 is the first parameter, 0 is the return
332   bool doesNotCapture(unsigned n) const {
333     return AttributeSets.hasAttribute(n, Attribute::NoCapture);
334   }
335   void setDoesNotCapture(unsigned n) {
336     addAttribute(n, Attribute::NoCapture);
337   }
338
339   bool doesNotAccessMemory(unsigned n) const {
340     return AttributeSets.hasAttribute(n, Attribute::ReadNone);
341   }
342   void setDoesNotAccessMemory(unsigned n) {
343     addAttribute(n, Attribute::ReadNone);
344   }
345
346   bool onlyReadsMemory(unsigned n) const {
347     return doesNotAccessMemory(n) ||
348       AttributeSets.hasAttribute(n, Attribute::ReadOnly);
349   }
350   void setOnlyReadsMemory(unsigned n) {
351     addAttribute(n, Attribute::ReadOnly);
352   }
353
354   /// copyAttributesFrom - copy all additional attributes (those not needed to
355   /// create a Function) from the Function Src to this one.
356   void copyAttributesFrom(const GlobalValue *Src) override;
357
358   /// deleteBody - This method deletes the body of the function, and converts
359   /// the linkage to external.
360   ///
361   void deleteBody() {
362     dropAllReferences();
363     setLinkage(ExternalLinkage);
364   }
365
366   /// removeFromParent - This method unlinks 'this' from the containing module,
367   /// but does not delete it.
368   ///
369   void removeFromParent() override;
370
371   /// eraseFromParent - This method unlinks 'this' from the containing module
372   /// and deletes it.
373   ///
374   void eraseFromParent() override;
375
376
377   /// Get the underlying elements of the Function... the basic block list is
378   /// empty for external functions.
379   ///
380   const ArgumentListType &getArgumentList() const {
381     CheckLazyArguments();
382     return ArgumentList;
383   }
384   ArgumentListType &getArgumentList() {
385     CheckLazyArguments();
386     return ArgumentList;
387   }
388   static iplist<Argument> Function::*getSublistAccess(Argument*) {
389     return &Function::ArgumentList;
390   }
391
392   const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
393         BasicBlockListType &getBasicBlockList()       { return BasicBlocks; }
394   static iplist<BasicBlock> Function::*getSublistAccess(BasicBlock*) {
395     return &Function::BasicBlocks;
396   }
397
398   const BasicBlock       &getEntryBlock() const   { return front(); }
399         BasicBlock       &getEntryBlock()         { return front(); }
400
401   //===--------------------------------------------------------------------===//
402   // Symbol Table Accessing functions...
403
404   /// getSymbolTable() - Return the symbol table...
405   ///
406   inline       ValueSymbolTable &getValueSymbolTable()       { return *SymTab; }
407   inline const ValueSymbolTable &getValueSymbolTable() const { return *SymTab; }
408
409
410   //===--------------------------------------------------------------------===//
411   // BasicBlock iterator forwarding functions
412   //
413   iterator                begin()       { return BasicBlocks.begin(); }
414   const_iterator          begin() const { return BasicBlocks.begin(); }
415   iterator                end  ()       { return BasicBlocks.end();   }
416   const_iterator          end  () const { return BasicBlocks.end();   }
417
418   size_t                   size() const { return BasicBlocks.size();  }
419   bool                    empty() const { return BasicBlocks.empty(); }
420   const BasicBlock       &front() const { return BasicBlocks.front(); }
421         BasicBlock       &front()       { return BasicBlocks.front(); }
422   const BasicBlock        &back() const { return BasicBlocks.back();  }
423         BasicBlock        &back()       { return BasicBlocks.back();  }
424
425 /// @name Function Argument Iteration
426 /// @{
427
428   arg_iterator arg_begin() {
429     CheckLazyArguments();
430     return ArgumentList.begin();
431   }
432   const_arg_iterator arg_begin() const {
433     CheckLazyArguments();
434     return ArgumentList.begin();
435   }
436   arg_iterator arg_end() {
437     CheckLazyArguments();
438     return ArgumentList.end();
439   }
440   const_arg_iterator arg_end() const {
441     CheckLazyArguments();
442     return ArgumentList.end();
443   }
444
445   iterator_range<arg_iterator> args() {
446     return iterator_range<arg_iterator>(arg_begin(), arg_end());
447   }
448
449   iterator_range<const_arg_iterator> args() const {
450     return iterator_range<const_arg_iterator>(arg_begin(), arg_end());
451   }
452
453 /// @}
454
455   size_t arg_size() const;
456   bool arg_empty() const;
457
458   bool hasPrefixData() const {
459     return getSubclassDataFromValue() & (1<<1);
460   }
461
462   Constant *getPrefixData() const;
463   void setPrefixData(Constant *PrefixData);
464
465   bool hasPrologueData() const {
466     return getSubclassDataFromValue() & (1<<2);
467   }
468
469   Constant *getPrologueData() const;
470   void setPrologueData(Constant *PrologueData);
471
472   /// viewCFG - This function is meant for use from the debugger.  You can just
473   /// say 'call F->viewCFG()' and a ghostview window should pop up from the
474   /// program, displaying the CFG of the current function with the code for each
475   /// basic block inside.  This depends on there being a 'dot' and 'gv' program
476   /// in your path.
477   ///
478   void viewCFG() const;
479
480   /// viewCFGOnly - This function is meant for use from the debugger.  It works
481   /// just like viewCFG, but it does not include the contents of basic blocks
482   /// into the nodes, just the label.  If you are only interested in the CFG
483   /// this can make the graph smaller.
484   ///
485   void viewCFGOnly() const;
486
487   /// Methods for support type inquiry through isa, cast, and dyn_cast:
488   static inline bool classof(const Value *V) {
489     return V->getValueID() == Value::FunctionVal;
490   }
491
492   /// dropAllReferences() - This method causes all the subinstructions to "let
493   /// go" of all references that they are maintaining.  This allows one to
494   /// 'delete' a whole module at a time, even though there may be circular
495   /// references... first all references are dropped, and all use counts go to
496   /// zero.  Then everything is deleted for real.  Note that no operations are
497   /// valid on an object that has "dropped all references", except operator
498   /// delete.
499   ///
500   /// Since no other object in the module can have references into the body of a
501   /// function, dropping all references deletes the entire body of the function,
502   /// including any contained basic blocks.
503   ///
504   void dropAllReferences();
505
506   /// hasAddressTaken - returns true if there are any uses of this function
507   /// other than direct calls or invokes to it, or blockaddress expressions.
508   /// Optionally passes back an offending user for diagnostic purposes.
509   ///
510   bool hasAddressTaken(const User** = nullptr) const;
511
512   /// isDefTriviallyDead - Return true if it is trivially safe to remove
513   /// this function definition from the module (because it isn't externally
514   /// visible, does not have its address taken, and has no callers).  To make
515   /// this more accurate, call removeDeadConstantUsers first.
516   bool isDefTriviallyDead() const;
517
518   /// callsFunctionThatReturnsTwice - Return true if the function has a call to
519   /// setjmp or other function that gcc recognizes as "returning twice".
520   bool callsFunctionThatReturnsTwice() const;
521
522 private:
523   // Shadow Value::setValueSubclassData with a private forwarding method so that
524   // subclasses cannot accidentally use it.
525   void setValueSubclassData(unsigned short D) {
526     Value::setValueSubclassData(D);
527   }
528 };
529
530 inline ValueSymbolTable *
531 ilist_traits<BasicBlock>::getSymTab(Function *F) {
532   return F ? &F->getValueSymbolTable() : nullptr;
533 }
534
535 inline ValueSymbolTable *
536 ilist_traits<Argument>::getSymTab(Function *F) {
537   return F ? &F->getValueSymbolTable() : nullptr;
538 }
539
540 } // End llvm namespace
541
542 #endif