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