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