1 //===- llvm/Function.h - Class to represent a single function ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the declaration of the Function class, which represents a
10 // single function/procedure in LLVM.
11 //
12 // A function basically consists of a list of basic blocks, a list of arguments,
13 // and a symbol table.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #ifndef LLVM_IR_FUNCTION_H
18 #define LLVM_IR_FUNCTION_H
19 
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/ADT/ilist_node.h"
24 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/IR/Argument.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalObject.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/OperandTraits.h"
33 #include "llvm/IR/SymbolTableListTraits.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/Compiler.h"
37 #include <cassert>
38 #include <cstddef>
39 #include <cstdint>
40 #include <memory>
41 #include <string>
42 
43 namespace llvm {
44 
45 namespace Intrinsic {
46 typedef unsigned ID;
47 }
48 
49 class AssemblyAnnotationWriter;
50 class Constant;
51 class DISubprogram;
52 class LLVMContext;
53 class Module;
54 template <typename T> class Optional;
55 class raw_ostream;
56 class Type;
57 class User;
58 class BranchProbabilityInfo;
59 class BlockFrequencyInfo;
60 
61 class LLVM_EXTERNAL_VISIBILITY Function : public GlobalObject,
62                                           public ilist_node<Function> {
63 public:
64   using BasicBlockListType = SymbolTableList<BasicBlock>;
65 
66   // BasicBlock iterators...
67   using iterator = BasicBlockListType::iterator;
68   using const_iterator = BasicBlockListType::const_iterator;
69 
70   using arg_iterator = Argument *;
71   using const_arg_iterator = const Argument *;
72 
73 private:
74   // Important things that make up a function!
75   BasicBlockListType BasicBlocks;         ///< The basic blocks
76   mutable Argument *Arguments = nullptr;  ///< The formal arguments
77   size_t NumArgs;
78   std::unique_ptr<ValueSymbolTable>
79       SymTab;                             ///< Symbol table of args/instructions
80   AttributeList AttributeSets;            ///< Parameter attributes
81 
82   /*
83    * Value::SubclassData
84    *
85    * bit 0      : HasLazyArguments
86    * bit 1      : HasPrefixData
87    * bit 2      : HasPrologueData
88    * bit 3      : HasPersonalityFn
89    * bits 4-13  : CallingConvention
90    * bits 14    : HasGC
91    * bits 15 : [reserved]
92    */
93 
94   /// Bits from GlobalObject::GlobalObjectSubclassData.
95   enum {
96     /// Whether this function is materializable.
97     IsMaterializableBit = 0,
98   };
99 
100   friend class SymbolTableListTraits<Function>;
101 
102   /// hasLazyArguments/CheckLazyArguments - The argument list of a function is
103   /// built on demand, so that the list isn't allocated until the first client
104   /// needs it.  The hasLazyArguments predicate returns true if the arg list
105   /// hasn't been set up yet.
106 public:
hasLazyArguments()107   bool hasLazyArguments() const {
108     return getSubclassDataFromValue() & (1<<0);
109   }
110 
111 private:
CheckLazyArguments()112   void CheckLazyArguments() const {
113     if (hasLazyArguments())
114       BuildLazyArguments();
115   }
116 
117   void BuildLazyArguments() const;
118 
119   void clearArguments();
120 
121   /// Function ctor - If the (optional) Module argument is specified, the
122   /// function is automatically inserted into the end of the function list for
123   /// the module.
124   ///
125   Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
126            const Twine &N = "", Module *M = nullptr);
127 
128 public:
129   Function(const Function&) = delete;
130   void operator=(const Function&) = delete;
131   ~Function();
132 
133   // This is here to help easily convert from FunctionT * (Function * or
134   // MachineFunction *) in BlockFrequencyInfoImpl to Function * by calling
135   // FunctionT->getFunction().
getFunction()136   const Function &getFunction() const { return *this; }
137 
138   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
139                           unsigned AddrSpace, const Twine &N = "",
140                           Module *M = nullptr) {
141     return new Function(Ty, Linkage, AddrSpace, N, M);
142   }
143 
144   // TODO: remove this once all users have been updated to pass an AddrSpace
145   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
146                           const Twine &N = "", Module *M = nullptr) {
147     return new Function(Ty, Linkage, static_cast<unsigned>(-1), N, M);
148   }
149 
150   /// Creates a new function and attaches it to a module.
151   ///
152   /// Places the function in the program address space as specified
153   /// by the module's data layout.
154   static Function *Create(FunctionType *Ty, LinkageTypes Linkage,
155                           const Twine &N, Module &M);
156 
157   /// Creates a function with some attributes recorded in llvm.module.flags
158   /// applied.
159   ///
160   /// Use this when synthesizing new functions that need attributes that would
161   /// have been set by command line options.
162   static Function *createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage,
163                                          unsigned AddrSpace,
164                                          const Twine &N = "",
165                                          Module *M = nullptr);
166 
167   // Provide fast operand accessors.
168   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
169 
170   /// Returns the number of non-debug IR instructions in this function.
171   /// This is equivalent to the sum of the sizes of each basic block contained
172   /// within this function.
173   unsigned getInstructionCount() const;
174 
175   /// Returns the FunctionType for me.
getFunctionType()176   FunctionType *getFunctionType() const {
177     return cast<FunctionType>(getValueType());
178   }
179 
180   /// Returns the type of the ret val.
getReturnType()181   Type *getReturnType() const { return getFunctionType()->getReturnType(); }
182 
183   /// getContext - Return a reference to the LLVMContext associated with this
184   /// function.
185   LLVMContext &getContext() const;
186 
187   /// isVarArg - Return true if this function takes a variable number of
188   /// arguments.
isVarArg()189   bool isVarArg() const { return getFunctionType()->isVarArg(); }
190 
isMaterializable()191   bool isMaterializable() const {
192     return getGlobalObjectSubClassData() & (1 << IsMaterializableBit);
193   }
setIsMaterializable(bool V)194   void setIsMaterializable(bool V) {
195     unsigned Mask = 1 << IsMaterializableBit;
196     setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
197                                 (V ? Mask : 0u));
198   }
199 
200   /// getIntrinsicID - This method returns the ID number of the specified
201   /// function, or Intrinsic::not_intrinsic if the function is not an
202   /// intrinsic, or if the pointer is null.  This value is always defined to be
203   /// zero to allow easy checking for whether a function is intrinsic or not.
204   /// The particular intrinsic functions which correspond to this value are
205   /// defined in llvm/Intrinsics.h.
getIntrinsicID()206   Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; }
207 
208   /// isIntrinsic - Returns true if the function's name starts with "llvm.".
209   /// It's possible for this function to return true while getIntrinsicID()
210   /// returns Intrinsic::not_intrinsic!
isIntrinsic()211   bool isIntrinsic() const { return HasLLVMReservedName; }
212 
213   /// isTargetIntrinsic - Returns true if IID is an intrinsic specific to a
214   /// certain target. If it is a generic intrinsic false is returned.
215   static bool isTargetIntrinsic(Intrinsic::ID IID);
216 
217   /// isTargetIntrinsic - Returns true if this function is an intrinsic and the
218   /// intrinsic is specific to a certain target. If this is not an intrinsic
219   /// or a generic intrinsic, false is returned.
220   bool isTargetIntrinsic() const;
221 
222   /// Returns true if the function is one of the "Constrained Floating-Point
223   /// Intrinsics". Returns false if not, and returns false when
224   /// getIntrinsicID() returns Intrinsic::not_intrinsic.
225   bool isConstrainedFPIntrinsic() const;
226 
227   static Intrinsic::ID lookupIntrinsicID(StringRef Name);
228 
229   /// Recalculate the ID for this function if it is an Intrinsic defined
230   /// in llvm/Intrinsics.h.  Sets the intrinsic ID to Intrinsic::not_intrinsic
231   /// if the name of this function does not match an intrinsic in that header.
232   /// Note, this method does not need to be called directly, as it is called
233   /// from Value::setName() whenever the name of this function changes.
234   void recalculateIntrinsicID();
235 
236   /// getCallingConv()/setCallingConv(CC) - These method get and set the
237   /// calling convention of this function.  The enum values for the known
238   /// calling conventions are defined in CallingConv.h.
getCallingConv()239   CallingConv::ID getCallingConv() const {
240     return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) &
241                                         CallingConv::MaxID);
242   }
setCallingConv(CallingConv::ID CC)243   void setCallingConv(CallingConv::ID CC) {
244     auto ID = static_cast<unsigned>(CC);
245     assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention");
246     setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4));
247   }
248 
249   /// Return the attribute list for this Function.
getAttributes()250   AttributeList getAttributes() const { return AttributeSets; }
251 
252   /// Set the attribute list for this Function.
setAttributes(AttributeList Attrs)253   void setAttributes(AttributeList Attrs) { AttributeSets = Attrs; }
254 
255   /// Add function attributes to this function.
addFnAttr(Attribute::AttrKind Kind)256   void addFnAttr(Attribute::AttrKind Kind) {
257     addAttribute(AttributeList::FunctionIndex, Kind);
258   }
259 
260   /// Add function attributes to this function.
261   void addFnAttr(StringRef Kind, StringRef Val = StringRef()) {
262     addAttribute(AttributeList::FunctionIndex,
263                  Attribute::get(getContext(), Kind, Val));
264   }
265 
266   /// Add function attributes to this function.
addFnAttr(Attribute Attr)267   void addFnAttr(Attribute Attr) {
268     addAttribute(AttributeList::FunctionIndex, Attr);
269   }
270 
271   /// Remove function attributes from this function.
removeFnAttr(Attribute::AttrKind Kind)272   void removeFnAttr(Attribute::AttrKind Kind) {
273     removeAttribute(AttributeList::FunctionIndex, Kind);
274   }
275 
276   /// Remove function attribute from this function.
removeFnAttr(StringRef Kind)277   void removeFnAttr(StringRef Kind) {
278     setAttributes(getAttributes().removeAttribute(
279         getContext(), AttributeList::FunctionIndex, Kind));
280   }
281 
282   /// A function will have the "coroutine.presplit" attribute if it's
283   /// a coroutine and has not gone through full CoroSplit pass.
isPresplitCoroutine()284   bool isPresplitCoroutine() const {
285     return hasFnAttribute("coroutine.presplit");
286   }
287 
288   enum ProfileCountType { PCT_Invalid, PCT_Real, PCT_Synthetic };
289 
290   /// Class to represent profile counts.
291   ///
292   /// This class represents both real and synthetic profile counts.
293   class ProfileCount {
294   private:
295     uint64_t Count;
296     ProfileCountType PCT;
297     static ProfileCount Invalid;
298 
299   public:
ProfileCount()300     ProfileCount() : Count(-1), PCT(PCT_Invalid) {}
ProfileCount(uint64_t Count,ProfileCountType PCT)301     ProfileCount(uint64_t Count, ProfileCountType PCT)
302         : Count(Count), PCT(PCT) {}
hasValue()303     bool hasValue() const { return PCT != PCT_Invalid; }
getCount()304     uint64_t getCount() const { return Count; }
getType()305     ProfileCountType getType() const { return PCT; }
isSynthetic()306     bool isSynthetic() const { return PCT == PCT_Synthetic; }
307     explicit operator bool() { return hasValue(); }
308     bool operator!() const { return !hasValue(); }
309     // Update the count retaining the same profile count type.
setCount(uint64_t C)310     ProfileCount &setCount(uint64_t C) {
311       Count = C;
312       return *this;
313     }
getInvalid()314     static ProfileCount getInvalid() { return ProfileCount(-1, PCT_Invalid); }
315   };
316 
317   /// Set the entry count for this function.
318   ///
319   /// Entry count is the number of times this function was executed based on
320   /// pgo data. \p Imports points to a set of GUIDs that needs to
321   /// be imported by the function for sample PGO, to enable the same inlines as
322   /// the profiled optimized binary.
323   void setEntryCount(ProfileCount Count,
324                      const DenseSet<GlobalValue::GUID> *Imports = nullptr);
325 
326   /// A convenience wrapper for setting entry count
327   void setEntryCount(uint64_t Count, ProfileCountType Type = PCT_Real,
328                      const DenseSet<GlobalValue::GUID> *Imports = nullptr);
329 
330   /// Get the entry count for this function.
331   ///
332   /// Entry count is the number of times the function was executed.
333   /// When AllowSynthetic is false, only pgo_data will be returned.
334   ProfileCount getEntryCount(bool AllowSynthetic = false) const;
335 
336   /// Return true if the function is annotated with profile data.
337   ///
338   /// Presence of entry counts from a profile run implies the function has
339   /// profile annotations. If IncludeSynthetic is false, only return true
340   /// when the profile data is real.
341   bool hasProfileData(bool IncludeSynthetic = false) const {
342     return getEntryCount(IncludeSynthetic).hasValue();
343   }
344 
345   /// Returns the set of GUIDs that needs to be imported to the function for
346   /// sample PGO, to enable the same inlines as the profiled optimized binary.
347   DenseSet<GlobalValue::GUID> getImportGUIDs() const;
348 
349   /// Set the section prefix for this function.
350   void setSectionPrefix(StringRef Prefix);
351 
352   /// Get the section prefix for this function.
353   Optional<StringRef> getSectionPrefix() const;
354 
355   /// Return true if the function has the attribute.
hasFnAttribute(Attribute::AttrKind Kind)356   bool hasFnAttribute(Attribute::AttrKind Kind) const {
357     return AttributeSets.hasFnAttribute(Kind);
358   }
359 
360   /// Return true if the function has the attribute.
hasFnAttribute(StringRef Kind)361   bool hasFnAttribute(StringRef Kind) const {
362     return AttributeSets.hasFnAttribute(Kind);
363   }
364 
365   /// Return the attribute for the given attribute kind.
getFnAttribute(Attribute::AttrKind Kind)366   Attribute getFnAttribute(Attribute::AttrKind Kind) const {
367     return getAttribute(AttributeList::FunctionIndex, Kind);
368   }
369 
370   /// Return the attribute for the given attribute kind.
getFnAttribute(StringRef Kind)371   Attribute getFnAttribute(StringRef Kind) const {
372     return getAttribute(AttributeList::FunctionIndex, Kind);
373   }
374 
375   /// Return the stack alignment for the function.
getFnStackAlignment()376   unsigned getFnStackAlignment() const {
377     if (!hasFnAttribute(Attribute::StackAlignment))
378       return 0;
379     if (const auto MA =
380             AttributeSets.getStackAlignment(AttributeList::FunctionIndex))
381       return MA->value();
382     return 0;
383   }
384 
385   /// Return the stack alignment for the function.
getFnStackAlign()386   MaybeAlign getFnStackAlign() const {
387     if (!hasFnAttribute(Attribute::StackAlignment))
388       return None;
389     return AttributeSets.getStackAlignment(AttributeList::FunctionIndex);
390   }
391 
392   /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
393   ///                             to use during code generation.
hasGC()394   bool hasGC() const {
395     return getSubclassDataFromValue() & (1<<14);
396   }
397   const std::string &getGC() const;
398   void setGC(std::string Str);
399   void clearGC();
400 
401   /// Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
402   bool hasStackProtectorFnAttr() const;
403 
404   /// adds the attribute to the list of attributes.
405   void addAttribute(unsigned i, Attribute::AttrKind Kind);
406 
407   /// adds the attribute to the list of attributes.
408   void addAttribute(unsigned i, Attribute Attr);
409 
410   /// adds the attributes to the list of attributes.
411   void addAttributes(unsigned i, const AttrBuilder &Attrs);
412 
413   /// adds the attribute to the list of attributes for the given arg.
414   void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
415 
416   /// adds the attribute to the list of attributes for the given arg.
417   void addParamAttr(unsigned ArgNo, Attribute Attr);
418 
419   /// adds the attributes to the list of attributes for the given arg.
420   void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs);
421 
422   /// removes the attribute from the list of attributes.
423   void removeAttribute(unsigned i, Attribute::AttrKind Kind);
424 
425   /// removes the attribute from the list of attributes.
426   void removeAttribute(unsigned i, StringRef Kind);
427 
428   /// removes the attributes from the list of attributes.
429   void removeAttributes(unsigned i, const AttrBuilder &Attrs);
430 
431   /// removes the attribute from the list of attributes.
432   void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind);
433 
434   /// removes the attribute from the list of attributes.
435   void removeParamAttr(unsigned ArgNo, StringRef Kind);
436 
437   /// removes the attribute from the list of attributes.
438   void removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs);
439 
440   /// removes noundef and other attributes that imply undefined behavior if a
441   /// `undef` or `poison` value is passed from the list of attributes.
442   void removeParamUndefImplyingAttrs(unsigned ArgNo);
443 
444   /// check if an attributes is in the list of attributes.
hasAttribute(unsigned i,Attribute::AttrKind Kind)445   bool hasAttribute(unsigned i, Attribute::AttrKind Kind) const {
446     return getAttributes().hasAttribute(i, Kind);
447   }
448 
449   /// check if an attributes is in the list of attributes.
hasParamAttribute(unsigned ArgNo,Attribute::AttrKind Kind)450   bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const {
451     return getAttributes().hasParamAttribute(ArgNo, Kind);
452   }
453 
454   /// gets the specified attribute from the list of attributes.
getParamAttribute(unsigned ArgNo,Attribute::AttrKind Kind)455   Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const {
456     return getAttributes().getParamAttr(ArgNo, Kind);
457   }
458 
459   /// gets the attribute from the list of attributes.
getAttribute(unsigned i,Attribute::AttrKind Kind)460   Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const {
461     return AttributeSets.getAttribute(i, Kind);
462   }
463 
464   /// gets the attribute from the list of attributes.
getAttribute(unsigned i,StringRef Kind)465   Attribute getAttribute(unsigned i, StringRef Kind) const {
466     return AttributeSets.getAttribute(i, Kind);
467   }
468 
469   /// adds the dereferenceable attribute to the list of attributes.
470   void addDereferenceableAttr(unsigned i, uint64_t Bytes);
471 
472   /// adds the dereferenceable attribute to the list of attributes for
473   /// the given arg.
474   void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes);
475 
476   /// adds the dereferenceable_or_null attribute to the list of
477   /// attributes.
478   void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes);
479 
480   /// adds the dereferenceable_or_null attribute to the list of
481   /// attributes for the given arg.
482   void addDereferenceableOrNullParamAttr(unsigned ArgNo, uint64_t Bytes);
483 
484   /// Extract the alignment for a call or parameter (0=unknown).
485   /// FIXME: Remove this function once transition to Align is over.
486   /// Use getParamAlign() instead.
getParamAlignment(unsigned ArgNo)487   unsigned getParamAlignment(unsigned ArgNo) const {
488     if (const auto MA = getParamAlign(ArgNo))
489       return MA->value();
490     return 0;
491   }
492 
getParamAlign(unsigned ArgNo)493   MaybeAlign getParamAlign(unsigned ArgNo) const {
494     return AttributeSets.getParamAlignment(ArgNo);
495   }
496 
getParamStackAlign(unsigned ArgNo)497   MaybeAlign getParamStackAlign(unsigned ArgNo) const {
498     return AttributeSets.getParamStackAlignment(ArgNo);
499   }
500 
501   /// Extract the byval type for a parameter.
getParamByValType(unsigned ArgNo)502   Type *getParamByValType(unsigned ArgNo) const {
503     return AttributeSets.getParamByValType(ArgNo);
504   }
505 
506   /// Extract the sret type for a parameter.
getParamStructRetType(unsigned ArgNo)507   Type *getParamStructRetType(unsigned ArgNo) const {
508     return AttributeSets.getParamStructRetType(ArgNo);
509   }
510 
511   /// Extract the inalloca type for a parameter.
getParamInAllocaType(unsigned ArgNo)512   Type *getParamInAllocaType(unsigned ArgNo) const {
513     return AttributeSets.getParamInAllocaType(ArgNo);
514   }
515 
516   /// Extract the byref type for a parameter.
getParamByRefType(unsigned ArgNo)517   Type *getParamByRefType(unsigned ArgNo) const {
518     return AttributeSets.getParamByRefType(ArgNo);
519   }
520 
521   /// Extract the number of dereferenceable bytes for a call or
522   /// parameter (0=unknown).
523   /// @param i AttributeList index, referring to a return value or argument.
getDereferenceableBytes(unsigned i)524   uint64_t getDereferenceableBytes(unsigned i) const {
525     return AttributeSets.getDereferenceableBytes(i);
526   }
527 
528   /// Extract the number of dereferenceable bytes for a parameter.
529   /// @param ArgNo Index of an argument, with 0 being the first function arg.
getParamDereferenceableBytes(unsigned ArgNo)530   uint64_t getParamDereferenceableBytes(unsigned ArgNo) const {
531     return AttributeSets.getParamDereferenceableBytes(ArgNo);
532   }
533 
534   /// Extract the number of dereferenceable_or_null bytes for a call or
535   /// parameter (0=unknown).
536   /// @param i AttributeList index, referring to a return value or argument.
getDereferenceableOrNullBytes(unsigned i)537   uint64_t getDereferenceableOrNullBytes(unsigned i) const {
538     return AttributeSets.getDereferenceableOrNullBytes(i);
539   }
540 
541   /// Extract the number of dereferenceable_or_null bytes for a
542   /// parameter.
543   /// @param ArgNo AttributeList ArgNo, referring to an argument.
getParamDereferenceableOrNullBytes(unsigned ArgNo)544   uint64_t getParamDereferenceableOrNullBytes(unsigned ArgNo) const {
545     return AttributeSets.getParamDereferenceableOrNullBytes(ArgNo);
546   }
547 
548   /// Determine if the function does not access memory.
doesNotAccessMemory()549   bool doesNotAccessMemory() const {
550     return hasFnAttribute(Attribute::ReadNone);
551   }
setDoesNotAccessMemory()552   void setDoesNotAccessMemory() {
553     addFnAttr(Attribute::ReadNone);
554   }
555 
556   /// Determine if the function does not access or only reads memory.
onlyReadsMemory()557   bool onlyReadsMemory() const {
558     return doesNotAccessMemory() || hasFnAttribute(Attribute::ReadOnly);
559   }
setOnlyReadsMemory()560   void setOnlyReadsMemory() {
561     addFnAttr(Attribute::ReadOnly);
562   }
563 
564   /// Determine if the function does not access or only writes memory.
doesNotReadMemory()565   bool doesNotReadMemory() const {
566     return doesNotAccessMemory() || hasFnAttribute(Attribute::WriteOnly);
567   }
setDoesNotReadMemory()568   void setDoesNotReadMemory() {
569     addFnAttr(Attribute::WriteOnly);
570   }
571 
572   /// Determine if the call can access memmory only using pointers based
573   /// on its arguments.
onlyAccessesArgMemory()574   bool onlyAccessesArgMemory() const {
575     return hasFnAttribute(Attribute::ArgMemOnly);
576   }
setOnlyAccessesArgMemory()577   void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); }
578 
579   /// Determine if the function may only access memory that is
580   ///  inaccessible from the IR.
onlyAccessesInaccessibleMemory()581   bool onlyAccessesInaccessibleMemory() const {
582     return hasFnAttribute(Attribute::InaccessibleMemOnly);
583   }
setOnlyAccessesInaccessibleMemory()584   void setOnlyAccessesInaccessibleMemory() {
585     addFnAttr(Attribute::InaccessibleMemOnly);
586   }
587 
588   /// Determine if the function may only access memory that is
589   ///  either inaccessible from the IR or pointed to by its arguments.
onlyAccessesInaccessibleMemOrArgMem()590   bool onlyAccessesInaccessibleMemOrArgMem() const {
591     return hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly);
592   }
setOnlyAccessesInaccessibleMemOrArgMem()593   void setOnlyAccessesInaccessibleMemOrArgMem() {
594     addFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
595   }
596 
597   /// Determine if the function cannot return.
doesNotReturn()598   bool doesNotReturn() const {
599     return hasFnAttribute(Attribute::NoReturn);
600   }
setDoesNotReturn()601   void setDoesNotReturn() {
602     addFnAttr(Attribute::NoReturn);
603   }
604 
605   /// Determine if the function should not perform indirect branch tracking.
doesNoCfCheck()606   bool doesNoCfCheck() const { return hasFnAttribute(Attribute::NoCfCheck); }
607 
608   /// Determine if the function cannot unwind.
doesNotThrow()609   bool doesNotThrow() const {
610     return hasFnAttribute(Attribute::NoUnwind);
611   }
setDoesNotThrow()612   void setDoesNotThrow() {
613     addFnAttr(Attribute::NoUnwind);
614   }
615 
616   /// Determine if the call cannot be duplicated.
cannotDuplicate()617   bool cannotDuplicate() const {
618     return hasFnAttribute(Attribute::NoDuplicate);
619   }
setCannotDuplicate()620   void setCannotDuplicate() {
621     addFnAttr(Attribute::NoDuplicate);
622   }
623 
624   /// Determine if the call is convergent.
isConvergent()625   bool isConvergent() const {
626     return hasFnAttribute(Attribute::Convergent);
627   }
setConvergent()628   void setConvergent() {
629     addFnAttr(Attribute::Convergent);
630   }
setNotConvergent()631   void setNotConvergent() {
632     removeFnAttr(Attribute::Convergent);
633   }
634 
635   /// Determine if the call has sideeffects.
isSpeculatable()636   bool isSpeculatable() const {
637     return hasFnAttribute(Attribute::Speculatable);
638   }
setSpeculatable()639   void setSpeculatable() {
640     addFnAttr(Attribute::Speculatable);
641   }
642 
643   /// Determine if the call might deallocate memory.
doesNotFreeMemory()644   bool doesNotFreeMemory() const {
645     return onlyReadsMemory() || hasFnAttribute(Attribute::NoFree);
646   }
setDoesNotFreeMemory()647   void setDoesNotFreeMemory() {
648     addFnAttr(Attribute::NoFree);
649   }
650 
651   /// Determine if the call can synchroize with other threads
hasNoSync()652   bool hasNoSync() const {
653     return hasFnAttribute(Attribute::NoSync);
654   }
setNoSync()655   void setNoSync() {
656     addFnAttr(Attribute::NoSync);
657   }
658 
659   /// Determine if the function is known not to recurse, directly or
660   /// indirectly.
doesNotRecurse()661   bool doesNotRecurse() const {
662     return hasFnAttribute(Attribute::NoRecurse);
663   }
setDoesNotRecurse()664   void setDoesNotRecurse() {
665     addFnAttr(Attribute::NoRecurse);
666   }
667 
668   /// Determine if the function is required to make forward progress.
mustProgress()669   bool mustProgress() const {
670     return hasFnAttribute(Attribute::MustProgress) ||
671            hasFnAttribute(Attribute::WillReturn);
672   }
setMustProgress()673   void setMustProgress() { addFnAttr(Attribute::MustProgress); }
674 
675   /// Determine if the function will return.
willReturn()676   bool willReturn() const { return hasFnAttribute(Attribute::WillReturn); }
setWillReturn()677   void setWillReturn() { addFnAttr(Attribute::WillReturn); }
678 
679   /// True if the ABI mandates (or the user requested) that this
680   /// function be in a unwind table.
hasUWTable()681   bool hasUWTable() const {
682     return hasFnAttribute(Attribute::UWTable);
683   }
setHasUWTable()684   void setHasUWTable() {
685     addFnAttr(Attribute::UWTable);
686   }
687 
688   /// True if this function needs an unwind table.
needsUnwindTableEntry()689   bool needsUnwindTableEntry() const {
690     return hasUWTable() || !doesNotThrow() || hasPersonalityFn();
691   }
692 
693   /// Determine if the function returns a structure through first
694   /// or second pointer argument.
hasStructRetAttr()695   bool hasStructRetAttr() const {
696     return AttributeSets.hasParamAttribute(0, Attribute::StructRet) ||
697            AttributeSets.hasParamAttribute(1, Attribute::StructRet);
698   }
699 
700   /// Determine if the parameter or return value is marked with NoAlias
701   /// attribute.
returnDoesNotAlias()702   bool returnDoesNotAlias() const {
703     return AttributeSets.hasAttribute(AttributeList::ReturnIndex,
704                                       Attribute::NoAlias);
705   }
setReturnDoesNotAlias()706   void setReturnDoesNotAlias() {
707     addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
708   }
709 
710   /// Do not optimize this function (-O0).
hasOptNone()711   bool hasOptNone() const { return hasFnAttribute(Attribute::OptimizeNone); }
712 
713   /// Optimize this function for minimum size (-Oz).
hasMinSize()714   bool hasMinSize() const { return hasFnAttribute(Attribute::MinSize); }
715 
716   /// Optimize this function for size (-Os) or minimum size (-Oz).
hasOptSize()717   bool hasOptSize() const {
718     return hasFnAttribute(Attribute::OptimizeForSize) || hasMinSize();
719   }
720 
721   /// Returns the denormal handling type for the default rounding mode of the
722   /// function.
723   DenormalMode getDenormalMode(const fltSemantics &FPType) const;
724 
725   /// copyAttributesFrom - copy all additional attributes (those not needed to
726   /// create a Function) from the Function Src to this one.
727   void copyAttributesFrom(const Function *Src);
728 
729   /// deleteBody - This method deletes the body of the function, and converts
730   /// the linkage to external.
731   ///
deleteBody()732   void deleteBody() {
733     dropAllReferences();
734     setLinkage(ExternalLinkage);
735   }
736 
737   /// removeFromParent - This method unlinks 'this' from the containing module,
738   /// but does not delete it.
739   ///
740   void removeFromParent();
741 
742   /// eraseFromParent - This method unlinks 'this' from the containing module
743   /// and deletes it.
744   ///
745   void eraseFromParent();
746 
747   /// Steal arguments from another function.
748   ///
749   /// Drop this function's arguments and splice in the ones from \c Src.
750   /// Requires that this has no function body.
751   void stealArgumentListFrom(Function &Src);
752 
753   /// Get the underlying elements of the Function... the basic block list is
754   /// empty for external functions.
755   ///
getBasicBlockList()756   const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; }
getBasicBlockList()757         BasicBlockListType &getBasicBlockList()       { return BasicBlocks; }
758 
getSublistAccess(BasicBlock *)759   static BasicBlockListType Function::*getSublistAccess(BasicBlock*) {
760     return &Function::BasicBlocks;
761   }
762 
getEntryBlock()763   const BasicBlock       &getEntryBlock() const   { return front(); }
getEntryBlock()764         BasicBlock       &getEntryBlock()         { return front(); }
765 
766   //===--------------------------------------------------------------------===//
767   // Symbol Table Accessing functions...
768 
769   /// getSymbolTable() - Return the symbol table if any, otherwise nullptr.
770   ///
getValueSymbolTable()771   inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); }
getValueSymbolTable()772   inline const ValueSymbolTable *getValueSymbolTable() const {
773     return SymTab.get();
774   }
775 
776   //===--------------------------------------------------------------------===//
777   // BasicBlock iterator forwarding functions
778   //
begin()779   iterator                begin()       { return BasicBlocks.begin(); }
begin()780   const_iterator          begin() const { return BasicBlocks.begin(); }
end()781   iterator                end  ()       { return BasicBlocks.end();   }
end()782   const_iterator          end  () const { return BasicBlocks.end();   }
783 
size()784   size_t                   size() const { return BasicBlocks.size();  }
empty()785   bool                    empty() const { return BasicBlocks.empty(); }
front()786   const BasicBlock       &front() const { return BasicBlocks.front(); }
front()787         BasicBlock       &front()       { return BasicBlocks.front(); }
back()788   const BasicBlock        &back() const { return BasicBlocks.back();  }
back()789         BasicBlock        &back()       { return BasicBlocks.back();  }
790 
791 /// @name Function Argument Iteration
792 /// @{
793 
arg_begin()794   arg_iterator arg_begin() {
795     CheckLazyArguments();
796     return Arguments;
797   }
arg_begin()798   const_arg_iterator arg_begin() const {
799     CheckLazyArguments();
800     return Arguments;
801   }
802 
arg_end()803   arg_iterator arg_end() {
804     CheckLazyArguments();
805     return Arguments + NumArgs;
806   }
arg_end()807   const_arg_iterator arg_end() const {
808     CheckLazyArguments();
809     return Arguments + NumArgs;
810   }
811 
getArg(unsigned i)812   Argument* getArg(unsigned i) const {
813     assert (i < NumArgs && "getArg() out of range!");
814     CheckLazyArguments();
815     return Arguments + i;
816   }
817 
args()818   iterator_range<arg_iterator> args() {
819     return make_range(arg_begin(), arg_end());
820   }
args()821   iterator_range<const_arg_iterator> args() const {
822     return make_range(arg_begin(), arg_end());
823   }
824 
825 /// @}
826 
arg_size()827   size_t arg_size() const { return NumArgs; }
arg_empty()828   bool arg_empty() const { return arg_size() == 0; }
829 
830   /// Check whether this function has a personality function.
hasPersonalityFn()831   bool hasPersonalityFn() const {
832     return getSubclassDataFromValue() & (1<<3);
833   }
834 
835   /// Get the personality function associated with this function.
836   Constant *getPersonalityFn() const;
837   void setPersonalityFn(Constant *Fn);
838 
839   /// Check whether this function has prefix data.
hasPrefixData()840   bool hasPrefixData() const {
841     return getSubclassDataFromValue() & (1<<1);
842   }
843 
844   /// Get the prefix data associated with this function.
845   Constant *getPrefixData() const;
846   void setPrefixData(Constant *PrefixData);
847 
848   /// Check whether this function has prologue data.
hasPrologueData()849   bool hasPrologueData() const {
850     return getSubclassDataFromValue() & (1<<2);
851   }
852 
853   /// Get the prologue data associated with this function.
854   Constant *getPrologueData() const;
855   void setPrologueData(Constant *PrologueData);
856 
857   /// Print the function to an output stream with an optional
858   /// AssemblyAnnotationWriter.
859   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
860              bool ShouldPreserveUseListOrder = false,
861              bool IsForDebug = false) const;
862 
863   /// viewCFG - This function is meant for use from the debugger.  You can just
864   /// say 'call F->viewCFG()' and a ghostview window should pop up from the
865   /// program, displaying the CFG of the current function with the code for each
866   /// basic block inside.  This depends on there being a 'dot' and 'gv' program
867   /// in your path.
868   ///
869   void viewCFG() const;
870 
871   /// Extended form to print edge weights.
872   void viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI,
873                const BranchProbabilityInfo *BPI) const;
874 
875   /// viewCFGOnly - This function is meant for use from the debugger.  It works
876   /// just like viewCFG, but it does not include the contents of basic blocks
877   /// into the nodes, just the label.  If you are only interested in the CFG
878   /// this can make the graph smaller.
879   ///
880   void viewCFGOnly() const;
881 
882   /// Extended form to print edge weights.
883   void viewCFGOnly(const BlockFrequencyInfo *BFI,
884                    const BranchProbabilityInfo *BPI) const;
885 
886   /// Methods for support type inquiry through isa, cast, and dyn_cast:
classof(const Value * V)887   static bool classof(const Value *V) {
888     return V->getValueID() == Value::FunctionVal;
889   }
890 
891   /// dropAllReferences() - This method causes all the subinstructions to "let
892   /// go" of all references that they are maintaining.  This allows one to
893   /// 'delete' a whole module at a time, even though there may be circular
894   /// references... first all references are dropped, and all use counts go to
895   /// zero.  Then everything is deleted for real.  Note that no operations are
896   /// valid on an object that has "dropped all references", except operator
897   /// delete.
898   ///
899   /// Since no other object in the module can have references into the body of a
900   /// function, dropping all references deletes the entire body of the function,
901   /// including any contained basic blocks.
902   ///
903   void dropAllReferences();
904 
905   /// hasAddressTaken - returns true if there are any uses of this function
906   /// other than direct calls or invokes to it, or blockaddress expressions.
907   /// Optionally passes back an offending user for diagnostic purposes,
908   /// ignores callback uses, assume like pointer annotation calls, and
909   /// references in llvm.used and llvm.compiler.used variables.
910   ///
911   bool hasAddressTaken(const User ** = nullptr,
912                        bool IgnoreCallbackUses = false,
913                        bool IgnoreAssumeLikeCalls = true,
914                        bool IngoreLLVMUsed = false) const;
915 
916   /// isDefTriviallyDead - Return true if it is trivially safe to remove
917   /// this function definition from the module (because it isn't externally
918   /// visible, does not have its address taken, and has no callers).  To make
919   /// this more accurate, call removeDeadConstantUsers first.
920   bool isDefTriviallyDead() const;
921 
922   /// callsFunctionThatReturnsTwice - Return true if the function has a call to
923   /// setjmp or other function that gcc recognizes as "returning twice".
924   bool callsFunctionThatReturnsTwice() const;
925 
926   /// Set the attached subprogram.
927   ///
928   /// Calls \a setMetadata() with \a LLVMContext::MD_dbg.
929   void setSubprogram(DISubprogram *SP);
930 
931   /// Get the attached subprogram.
932   ///
933   /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result
934   /// to \a DISubprogram.
935   DISubprogram *getSubprogram() const;
936 
937   /// Returns true if we should emit debug info for profiling.
938   bool isDebugInfoForProfiling() const;
939 
940   /// Check if null pointer dereferencing is considered undefined behavior for
941   /// the function.
942   /// Return value: false => null pointer dereference is undefined.
943   /// Return value: true =>  null pointer dereference is not undefined.
944   bool nullPointerIsDefined() const;
945 
946 private:
947   void allocHungoffUselist();
948   template<int Idx> void setHungoffOperand(Constant *C);
949 
950   /// Shadow Value::setValueSubclassData with a private forwarding method so
951   /// that subclasses cannot accidentally use it.
setValueSubclassData(unsigned short D)952   void setValueSubclassData(unsigned short D) {
953     Value::setValueSubclassData(D);
954   }
955   void setValueSubclassDataBit(unsigned Bit, bool On);
956 };
957 
958 /// Check whether null pointer dereferencing is considered undefined behavior
959 /// for a given function or an address space.
960 /// Null pointer access in non-zero address space is not considered undefined.
961 /// Return value: false => null pointer dereference is undefined.
962 /// Return value: true =>  null pointer dereference is not undefined.
963 bool NullPointerIsDefined(const Function *F, unsigned AS = 0);
964 
965 template <>
966 struct OperandTraits<Function> : public HungoffOperandTraits<3> {};
967 
968 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value)
969 
970 } // end namespace llvm
971 
972 #endif // LLVM_IR_FUNCTION_H
973