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

source code of llvm/include/llvm/IR/Function.h