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