LLVM 22.0.0git
Function.cpp
Go to the documentation of this file.
1//===- Function.cpp - Implement the Global object classes -----------------===//
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 implements the Function class for the IR library.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Function.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
23#include "llvm/IR/Argument.h"
24#include "llvm/IR/Attributes.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/Constant.h"
28#include "llvm/IR/Constants.h"
30#include "llvm/IR/GlobalValue.h"
32#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/MDBuilder.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
42#include "llvm/IR/Type.h"
43#include "llvm/IR/Use.h"
44#include "llvm/IR/User.h"
45#include "llvm/IR/Value.h"
51#include "llvm/Support/ModRef.h"
52#include <cassert>
53#include <cstddef>
54#include <cstdint>
55#include <cstring>
56#include <string>
57
58using namespace llvm;
60
61// Explicit instantiations of SymbolTableListTraits since some of the methods
62// are not in the public header file...
64
66 "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
67 cl::desc("Maximum size for the name of non-global values."));
68
70 validateBlockNumbers();
71
72 NextBlockNum = 0;
73 for (auto &BB : *this)
74 BB.Number = NextBlockNum++;
75 BlockNumEpoch++;
76}
77
78void Function::validateBlockNumbers() const {
79#ifndef NDEBUG
80 BitVector Numbers(NextBlockNum);
81 for (const auto &BB : *this) {
82 unsigned Num = BB.getNumber();
83 assert(Num < NextBlockNum && "out of range block number");
84 assert(!Numbers[Num] && "duplicate block numbers");
85 Numbers.set(Num);
86 }
87#endif
88}
89
91 for (auto &BB : *this) {
92 BB.convertToNewDbgValues();
93 }
94}
95
97 for (auto &BB : *this) {
98 BB.convertFromNewDbgValues();
99 }
100}
101
102//===----------------------------------------------------------------------===//
103// Argument Implementation
104//===----------------------------------------------------------------------===//
105
106Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
107 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
108 setName(Name);
109}
110
111void Argument::setParent(Function *parent) {
112 Parent = parent;
113}
114
115bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {
116 if (!getType()->isPointerTy()) return false;
117 if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) &&
118 (AllowUndefOrPoison ||
119 getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef)))
120 return true;
121 else if (getDereferenceableBytes() > 0 &&
124 return true;
125 return false;
126}
127
128bool Argument::hasByValAttr() const {
129 if (!getType()->isPointerTy()) return false;
130 return hasAttribute(Attribute::ByVal);
131}
132
134 if (!getType()->isPointerTy())
135 return false;
136 return hasAttribute(Attribute::DeadOnReturn);
137}
138
139bool Argument::hasByRefAttr() const {
140 if (!getType()->isPointerTy())
141 return false;
142 return hasAttribute(Attribute::ByRef);
143}
144
145bool Argument::hasSwiftSelfAttr() const {
146 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
147}
148
149bool Argument::hasSwiftErrorAttr() const {
150 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
151}
152
153bool Argument::hasInAllocaAttr() const {
154 if (!getType()->isPointerTy()) return false;
155 return hasAttribute(Attribute::InAlloca);
156}
157
159 if (!getType()->isPointerTy())
160 return false;
161 return hasAttribute(Attribute::Preallocated);
162}
163
165 if (!getType()->isPointerTy()) return false;
166 AttributeList Attrs = getParent()->getAttributes();
167 return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||
168 Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||
169 Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated);
170}
171
173 if (!getType()->isPointerTy())
174 return false;
175 AttributeList Attrs = getParent()->getAttributes();
176 return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||
177 Attrs.hasParamAttr(getArgNo(), Attribute::StructRet) ||
178 Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||
179 Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated) ||
180 Attrs.hasParamAttr(getArgNo(), Attribute::ByRef);
181}
182
183/// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
184/// parameter type.
185static Type *getMemoryParamAllocType(AttributeSet ParamAttrs) {
186 // FIXME: All the type carrying attributes are mutually exclusive, so there
187 // should be a single query to get the stored type that handles any of them.
188 if (Type *ByValTy = ParamAttrs.getByValType())
189 return ByValTy;
190 if (Type *ByRefTy = ParamAttrs.getByRefType())
191 return ByRefTy;
192 if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
193 return PreAllocTy;
194 if (Type *InAllocaTy = ParamAttrs.getInAllocaType())
195 return InAllocaTy;
196 if (Type *SRetTy = ParamAttrs.getStructRetType())
197 return SRetTy;
198
199 return nullptr;
200}
201
203 AttributeSet ParamAttrs =
204 getParent()->getAttributes().getParamAttrs(getArgNo());
205 if (Type *MemTy = getMemoryParamAllocType(ParamAttrs))
206 return DL.getTypeAllocSize(MemTy);
207 return 0;
208}
209
211 AttributeSet ParamAttrs =
212 getParent()->getAttributes().getParamAttrs(getArgNo());
213 return getMemoryParamAllocType(ParamAttrs);
214}
215
217 assert(getType()->isPointerTy() && "Only pointers have alignments");
218 return getParent()->getParamAlign(getArgNo());
219}
220
222 return getParent()->getParamStackAlign(getArgNo());
223}
224
225Type *Argument::getParamByValType() const {
226 assert(getType()->isPointerTy() && "Only pointers have byval types");
227 return getParent()->getParamByValType(getArgNo());
228}
229
231 assert(getType()->isPointerTy() && "Only pointers have sret types");
232 return getParent()->getParamStructRetType(getArgNo());
233}
234
235Type *Argument::getParamByRefType() const {
236 assert(getType()->isPointerTy() && "Only pointers have byref types");
237 return getParent()->getParamByRefType(getArgNo());
238}
239
240Type *Argument::getParamInAllocaType() const {
241 assert(getType()->isPointerTy() && "Only pointers have inalloca types");
242 return getParent()->getParamInAllocaType(getArgNo());
243}
244
247 "Only pointers have dereferenceable bytes");
248 return getParent()->getParamDereferenceableBytes(getArgNo());
249}
250
253 "Only pointers have dereferenceable bytes");
254 return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
255}
256
257FPClassTest Argument::getNoFPClass() const {
258 return getParent()->getParamNoFPClass(getArgNo());
259}
260
261std::optional<ConstantRange> Argument::getRange() const {
262 const Attribute RangeAttr = getAttribute(llvm::Attribute::Range);
263 if (RangeAttr.isValid())
264 return RangeAttr.getRange();
265 return std::nullopt;
266}
267
268bool Argument::hasNestAttr() const {
269 if (!getType()->isPointerTy()) return false;
270 return hasAttribute(Attribute::Nest);
271}
272
273bool Argument::hasNoAliasAttr() const {
274 if (!getType()->isPointerTy()) return false;
275 return hasAttribute(Attribute::NoAlias);
276}
277
278bool Argument::hasNoCaptureAttr() const {
279 if (!getType()->isPointerTy()) return false;
280 return capturesNothing(getAttributes().getCaptureInfo());
281}
282
283bool Argument::hasNoFreeAttr() const {
284 if (!getType()->isPointerTy()) return false;
285 return hasAttribute(Attribute::NoFree);
286}
287
288bool Argument::hasStructRetAttr() const {
289 if (!getType()->isPointerTy()) return false;
290 return hasAttribute(Attribute::StructRet);
291}
292
293bool Argument::hasInRegAttr() const {
294 return hasAttribute(Attribute::InReg);
295}
296
297bool Argument::hasReturnedAttr() const {
298 return hasAttribute(Attribute::Returned);
299}
300
301bool Argument::hasZExtAttr() const {
302 return hasAttribute(Attribute::ZExt);
303}
304
305bool Argument::hasSExtAttr() const {
306 return hasAttribute(Attribute::SExt);
307}
308
309bool Argument::onlyReadsMemory() const {
310 AttributeList Attrs = getParent()->getAttributes();
311 return Attrs.hasParamAttr(getArgNo(), Attribute::ReadOnly) ||
312 Attrs.hasParamAttr(getArgNo(), Attribute::ReadNone);
313}
314
315void Argument::addAttrs(AttrBuilder &B) {
316 AttributeList AL = getParent()->getAttributes();
317 AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
318 getParent()->setAttributes(AL);
319}
320
322 getParent()->addParamAttr(getArgNo(), Kind);
323}
324
325void Argument::addAttr(Attribute Attr) {
326 getParent()->addParamAttr(getArgNo(), Attr);
327}
328
330 getParent()->removeParamAttr(getArgNo(), Kind);
331}
332
333void Argument::removeAttrs(const AttributeMask &AM) {
334 AttributeList AL = getParent()->getAttributes();
335 AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), AM);
336 getParent()->setAttributes(AL);
337}
338
340 return getParent()->hasParamAttribute(getArgNo(), Kind);
341}
342
343bool Argument::hasAttribute(StringRef Kind) const {
344 return getParent()->hasParamAttribute(getArgNo(), Kind);
345}
346
347Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
348 return getParent()->getParamAttribute(getArgNo(), Kind);
349}
350
352 return getParent()->getAttributes().getParamAttrs(getArgNo());
353}
354
355//===----------------------------------------------------------------------===//
356// Helper Methods in Function
357//===----------------------------------------------------------------------===//
358
360 return getType()->getContext();
361}
362
363const DataLayout &Function::getDataLayout() const {
364 return getParent()->getDataLayout();
365}
366
367unsigned Function::getInstructionCount() const {
368 unsigned NumInstrs = 0;
369 for (const BasicBlock &BB : BasicBlocks)
370 NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
371 BB.instructionsWithoutDebug().end());
372 return NumInstrs;
373}
374
376 const Twine &N, Module &M) {
377 return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
378}
379
381 LinkageTypes Linkage,
382 unsigned AddrSpace, const Twine &N,
383 Module *M) {
384 auto *F = new (AllocMarker) Function(Ty, Linkage, AddrSpace, N, M);
385 AttrBuilder B(F->getContext());
386 UWTableKind UWTable = M->getUwtable();
387 if (UWTable != UWTableKind::None)
388 B.addUWTableAttr(UWTable);
389 switch (M->getFramePointer()) {
391 // 0 ("none") is the default.
392 break;
394 B.addAttribute("frame-pointer", "reserved");
395 break;
397 B.addAttribute("frame-pointer", "non-leaf");
398 break;
400 B.addAttribute("frame-pointer", "all");
401 break;
402 }
403 if (M->getModuleFlag("function_return_thunk_extern"))
404 B.addAttribute(Attribute::FnRetThunkExtern);
405 StringRef DefaultCPU = F->getContext().getDefaultTargetCPU();
406 if (!DefaultCPU.empty())
407 B.addAttribute("target-cpu", DefaultCPU);
408 StringRef DefaultFeatures = F->getContext().getDefaultTargetFeatures();
409 if (!DefaultFeatures.empty())
410 B.addAttribute("target-features", DefaultFeatures);
411
412 // Check if the module attribute is present and not zero.
413 auto isModuleAttributeSet = [&](const StringRef &ModAttr) -> bool {
414 const auto *Attr =
415 mdconst::extract_or_null<ConstantInt>(M->getModuleFlag(ModAttr));
416 return Attr && !Attr->isZero();
417 };
418
419 auto AddAttributeIfSet = [&](const StringRef &ModAttr) {
420 if (isModuleAttributeSet(ModAttr))
421 B.addAttribute(ModAttr);
422 };
423
424 StringRef SignType = "none";
425 if (isModuleAttributeSet("sign-return-address"))
426 SignType = "non-leaf";
427 if (isModuleAttributeSet("sign-return-address-all"))
428 SignType = "all";
429 if (SignType != "none") {
430 B.addAttribute("sign-return-address", SignType);
431 B.addAttribute("sign-return-address-key",
432 isModuleAttributeSet("sign-return-address-with-bkey")
433 ? "b_key"
434 : "a_key");
435 }
436 AddAttributeIfSet("branch-target-enforcement");
437 AddAttributeIfSet("branch-protection-pauth-lr");
438 AddAttributeIfSet("guarded-control-stack");
439
440 F->addFnAttrs(B);
441 return F;
442}
443
445 getParent()->getFunctionList().remove(getIterator());
446}
447
449 getParent()->getFunctionList().erase(getIterator());
450}
451
453 Function::iterator FromBeginIt,
454 Function::iterator FromEndIt) {
455#ifdef EXPENSIVE_CHECKS
456 // Check that FromBeginIt is before FromEndIt.
457 auto FromFEnd = FromF->end();
458 for (auto It = FromBeginIt; It != FromEndIt; ++It)
459 assert(It != FromFEnd && "FromBeginIt not before FromEndIt!");
460#endif // EXPENSIVE_CHECKS
461 BasicBlocks.splice(ToIt, FromF->BasicBlocks, FromBeginIt, FromEndIt);
462}
463
465 Function::iterator ToIt) {
466 return BasicBlocks.erase(FromIt, ToIt);
467}
468
469//===----------------------------------------------------------------------===//
470// Function Implementation
471//===----------------------------------------------------------------------===//
472
473static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
474 // If AS == -1 and we are passed a valid module pointer we place the function
475 // in the program address space. Otherwise we default to AS0.
476 if (AddrSpace == static_cast<unsigned>(-1))
477 return M ? M->getDataLayout().getProgramAddressSpace() : 0;
478 return AddrSpace;
479}
480
481Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
482 const Twine &name, Module *ParentModule)
483 : GlobalObject(Ty, Value::FunctionVal, AllocMarker, Linkage, name,
484 computeAddrSpace(AddrSpace, ParentModule)),
485 NumArgs(Ty->getNumParams()) {
486 assert(FunctionType::isValidReturnType(getReturnType()) &&
487 "invalid return type");
488 setGlobalObjectSubClassData(0);
489
490 // We only need a symbol table for a function if the context keeps value names
491 if (!getContext().shouldDiscardValueNames())
492 SymTab = std::make_unique<ValueSymbolTable>(NonGlobalValueMaxNameSize);
493
494 // If the function has arguments, mark them as lazily built.
495 if (Ty->getNumParams())
496 setValueSubclassData(1); // Set the "has lazy arguments" bit.
497
498 if (ParentModule) {
499 ParentModule->getFunctionList().push_back(this);
500 }
501
502 HasLLVMReservedName = getName().starts_with("llvm.");
503 // Ensure intrinsics have the right parameter attributes.
504 // Note, the IntID field will have been set in Value::setName if this function
505 // name is a valid intrinsic ID.
506 if (IntID) {
507 // Don't set the attributes if the intrinsic signature is invalid. This
508 // case will either be auto-upgraded or fail verification.
509 SmallVector<Type *> OverloadTys;
510 if (!Intrinsic::getIntrinsicSignature(IntID, Ty, OverloadTys))
511 return;
512
513 setAttributes(Intrinsic::getAttributes(getContext(), IntID, Ty));
514 }
515}
516
518 validateBlockNumbers();
519
520 dropAllReferences(); // After this it is safe to delete instructions.
521
522 // Delete all of the method arguments and unlink from symbol table...
523 if (Arguments)
524 clearArguments();
525
526 // Remove the function from the on-the-side GC table.
527 clearGC();
528}
529
530void Function::BuildLazyArguments() const {
531 // Create the arguments vector, all arguments start out unnamed.
532 auto *FT = getFunctionType();
533 if (NumArgs > 0) {
534 Arguments = std::allocator<Argument>().allocate(NumArgs);
535 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
536 Type *ArgTy = FT->getParamType(i);
537 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
538 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
539 }
540 }
541
542 // Clear the lazy arguments bit.
543 unsigned SDC = getSubclassDataFromValue();
544 SDC &= ~(1 << 0);
545 const_cast<Function*>(this)->setValueSubclassData(SDC);
546 assert(!hasLazyArguments());
547}
548
550 return MutableArrayRef<Argument>(Args, Count);
551}
552
555}
556
557void Function::clearArguments() {
558 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
559 A.setName("");
560 A.~Argument();
561 }
562 std::allocator<Argument>().deallocate(Arguments, NumArgs);
563 Arguments = nullptr;
564}
565
567 assert(isDeclaration() && "Expected no references to current arguments");
568
569 // Drop the current arguments, if any, and set the lazy argument bit.
570 if (!hasLazyArguments()) {
572 [](const Argument &A) { return A.use_empty(); }) &&
573 "Expected arguments to be unused in declaration");
574 clearArguments();
575 setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
576 }
577
578 // Nothing to steal if Src has lazy arguments.
579 if (Src.hasLazyArguments())
580 return;
581
582 // Steal arguments from Src, and fix the lazy argument bits.
583 assert(arg_size() == Src.arg_size());
584 Arguments = Src.Arguments;
585 Src.Arguments = nullptr;
586 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
587 // FIXME: This does the work of transferNodesFromList inefficiently.
589 if (A.hasName())
590 Name = A.getName();
591 if (!Name.empty())
592 A.setName("");
593 A.setParent(this);
594 if (!Name.empty())
595 A.setName(Name);
596 }
597
598 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
599 assert(!hasLazyArguments());
600 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
601}
602
603void Function::deleteBodyImpl(bool ShouldDrop) {
604 setIsMaterializable(false);
605
606 for (BasicBlock &BB : *this)
608
609 // Delete all basic blocks. They are now unused, except possibly by
610 // blockaddresses, but BasicBlock's destructor takes care of those.
611 while (!BasicBlocks.empty())
612 BasicBlocks.begin()->eraseFromParent();
613
614 if (getNumOperands()) {
615 if (ShouldDrop) {
616 // Drop uses of any optional data (real or placeholder).
618 setNumHungOffUseOperands(0);
619 } else {
620 // The code needs to match Function::allocHungoffUselist().
622 Op<0>().set(CPN);
623 Op<1>().set(CPN);
624 Op<2>().set(CPN);
625 }
626 setValueSubclassData(getSubclassDataFromValue() & ~0xe);
627 }
628
629 // Metadata is stored in a side-table.
630 clearMetadata();
631}
632
633void Function::addAttributeAtIndex(unsigned i, Attribute Attr) {
634 AttributeSets = AttributeSets.addAttributeAtIndex(getContext(), i, Attr);
635}
636
638 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind);
639}
640
642 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind, Val);
643}
644
645void Function::addFnAttr(Attribute Attr) {
646 AttributeSets = AttributeSets.addFnAttribute(getContext(), Attr);
647}
648
649void Function::addFnAttrs(const AttrBuilder &Attrs) {
650 AttributeSets = AttributeSets.addFnAttributes(getContext(), Attrs);
651}
652
654 AttributeSets = AttributeSets.addRetAttribute(getContext(), Kind);
655}
656
657void Function::addRetAttr(Attribute Attr) {
658 AttributeSets = AttributeSets.addRetAttribute(getContext(), Attr);
659}
660
661void Function::addRetAttrs(const AttrBuilder &Attrs) {
662 AttributeSets = AttributeSets.addRetAttributes(getContext(), Attrs);
663}
664
665void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
666 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Kind);
667}
668
669void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
670 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Attr);
671}
672
673void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
674 AttributeSets = AttributeSets.addParamAttributes(getContext(), ArgNo, Attrs);
675}
676
678 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
679}
680
681void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) {
682 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
683}
684
686 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
687}
688
690 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
691}
692
694 AttributeSets = AttributeSets.removeFnAttributes(getContext(), AM);
695}
696
698 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
699}
700
702 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
703}
704
705void Function::removeRetAttrs(const AttributeMask &Attrs) {
706 AttributeSets = AttributeSets.removeRetAttributes(getContext(), Attrs);
707}
708
709void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
710 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
711}
712
713void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
714 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
715}
716
717void Function::removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs) {
718 AttributeSets =
719 AttributeSets.removeParamAttributes(getContext(), ArgNo, Attrs);
720}
721
722void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
723 AttributeSets =
724 AttributeSets.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
725}
726
728 return AttributeSets.hasFnAttr(Kind);
729}
730
731bool Function::hasFnAttribute(StringRef Kind) const {
732 return AttributeSets.hasFnAttr(Kind);
733}
734
736 return AttributeSets.hasRetAttr(Kind);
737}
738
739bool Function::hasParamAttribute(unsigned ArgNo,
740 Attribute::AttrKind Kind) const {
741 return AttributeSets.hasParamAttr(ArgNo, Kind);
742}
743
744bool Function::hasParamAttribute(unsigned ArgNo, StringRef Kind) const {
745 return AttributeSets.hasParamAttr(ArgNo, Kind);
746}
747
748Attribute Function::getAttributeAtIndex(unsigned i,
749 Attribute::AttrKind Kind) const {
750 return AttributeSets.getAttributeAtIndex(i, Kind);
751}
752
753Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const {
754 return AttributeSets.getAttributeAtIndex(i, Kind);
755}
756
757bool Function::hasAttributeAtIndex(unsigned Idx,
758 Attribute::AttrKind Kind) const {
759 return AttributeSets.hasAttributeAtIndex(Idx, Kind);
760}
761
762Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const {
763 return AttributeSets.getFnAttr(Kind);
764}
765
766Attribute Function::getFnAttribute(StringRef Kind) const {
767 return AttributeSets.getFnAttr(Kind);
768}
769
771 return AttributeSets.getRetAttr(Kind);
772}
773
775 uint64_t Default) const {
776 Attribute A = getFnAttribute(Name);
778 if (A.isStringAttribute()) {
779 StringRef Str = A.getValueAsString();
780 if (Str.getAsInteger(0, Result))
781 getContext().emitError("cannot parse integer attribute " + Name);
782 }
783
784 return Result;
785}
786
787/// gets the specified attribute from the list of attributes.
788Attribute Function::getParamAttribute(unsigned ArgNo,
789 Attribute::AttrKind Kind) const {
790 return AttributeSets.getParamAttr(ArgNo, Kind);
791}
792
794 uint64_t Bytes) {
795 AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(getContext(),
796 ArgNo, Bytes);
797}
798
800 AttributeSets = AttributeSets.addRangeRetAttr(getContext(), CR);
801}
802
804 if (&FPType == &APFloat::IEEEsingle()) {
805 DenormalMode Mode = getDenormalModeF32Raw();
806 // If the f32 variant of the attribute isn't specified, try to use the
807 // generic one.
808 if (Mode.isValid())
809 return Mode;
810 }
811
812 return getDenormalModeRaw();
813}
814
816 Attribute Attr = getFnAttribute("denormal-fp-math");
817 StringRef Val = Attr.getValueAsString();
818 return parseDenormalFPAttribute(Val);
819}
820
822 Attribute Attr = getFnAttribute("denormal-fp-math-f32");
823 if (Attr.isValid()) {
824 StringRef Val = Attr.getValueAsString();
825 return parseDenormalFPAttribute(Val);
826 }
827
829}
830
831const std::string &Function::getGC() const {
832 assert(hasGC() && "Function has no collector");
833 return getContext().getGC(*this);
834}
835
836void Function::setGC(std::string Str) {
837 setValueSubclassDataBit(14, !Str.empty());
838 getContext().setGC(*this, std::move(Str));
839}
840
841void Function::clearGC() {
842 if (!hasGC())
843 return;
844 getContext().deleteGC(*this);
845 setValueSubclassDataBit(14, false);
846}
847
849 return hasFnAttribute(Attribute::StackProtect) ||
850 hasFnAttribute(Attribute::StackProtectStrong) ||
851 hasFnAttribute(Attribute::StackProtectReq);
852}
853
854/// Copy all additional attributes (those not needed to create a Function) from
855/// the Function Src to this one.
856void Function::copyAttributesFrom(const Function *Src) {
858 setCallingConv(Src->getCallingConv());
859 setAttributes(Src->getAttributes());
860 if (Src->hasGC())
861 setGC(Src->getGC());
862 else
863 clearGC();
864 if (Src->hasPersonalityFn())
865 setPersonalityFn(Src->getPersonalityFn());
866 if (Src->hasPrefixData())
867 setPrefixData(Src->getPrefixData());
868 if (Src->hasPrologueData())
869 setPrologueData(Src->getPrologueData());
870}
871
873 return getAttributes().getMemoryEffects();
874}
877}
878
879/// Determine if the function does not access memory.
881 return getMemoryEffects().doesNotAccessMemory();
882}
885}
886
887/// Determine if the function does not access or only reads memory.
888bool Function::onlyReadsMemory() const {
889 return getMemoryEffects().onlyReadsMemory();
890}
892 setMemoryEffects(getMemoryEffects() & MemoryEffects::readOnly());
893}
894
895/// Determine if the function does not access or only writes memory.
896bool Function::onlyWritesMemory() const {
897 return getMemoryEffects().onlyWritesMemory();
898}
900 setMemoryEffects(getMemoryEffects() & MemoryEffects::writeOnly());
901}
902
903/// Determine if the call can access memory only using pointers based
904/// on its arguments.
906 return getMemoryEffects().onlyAccessesArgPointees();
907}
909 setMemoryEffects(getMemoryEffects() & MemoryEffects::argMemOnly());
910}
911
912/// Determine if the function may only access memory that is
913/// inaccessible from the IR.
915 return getMemoryEffects().onlyAccessesInaccessibleMem();
916}
919}
920
921/// Determine if the function may only access memory that is
922/// either inaccessible from the IR or pointed to by its arguments.
924 return getMemoryEffects().onlyAccessesInaccessibleOrArgMem();
925}
927 setMemoryEffects(getMemoryEffects() &
929}
930
931bool Function::isTargetIntrinsic() const {
932 return Intrinsic::isTargetIntrinsic(IntID);
933}
934
936 LibFuncCache = UnknownLibFunc;
938 if (!Name.starts_with("llvm.")) {
939 HasLLVMReservedName = false;
941 return;
942 }
943 HasLLVMReservedName = true;
944 IntID = Intrinsic::lookupIntrinsicID(Name);
945}
946
947/// hasAddressTaken - returns true if there are any uses of this function
948/// other than direct calls or invokes to it. Optionally ignores callback
949/// uses, assume like pointer annotation calls, and references in llvm.used
950/// and llvm.compiler.used variables.
951bool Function::hasAddressTaken(const User **PutOffender,
952 bool IgnoreCallbackUses,
953 bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed,
954 bool IgnoreARCAttachedCall,
955 bool IgnoreCastedDirectCall) const {
956 for (const Use &U : uses()) {
957 const User *FU = U.getUser();
958 if (IgnoreCallbackUses) {
959 AbstractCallSite ACS(&U);
960 if (ACS && ACS.isCallbackCall())
961 continue;
962 }
963
964 const auto *Call = dyn_cast<CallBase>(FU);
965 if (!Call) {
966 if (IgnoreAssumeLikeCalls &&
968 all_of(FU->users(), [](const User *U) {
969 if (const auto *I = dyn_cast<IntrinsicInst>(U))
970 return I->isAssumeLikeIntrinsic();
971 return false;
972 })) {
973 continue;
974 }
975
976 if (IgnoreLLVMUsed && !FU->user_empty()) {
977 const User *FUU = FU;
979 FU->hasOneUse() && !FU->user_begin()->user_empty())
980 FUU = *FU->user_begin();
981 if (llvm::all_of(FUU->users(), [](const User *U) {
982 if (const auto *GV = dyn_cast<GlobalVariable>(U))
983 return GV->hasName() &&
984 (GV->getName() == "llvm.compiler.used" ||
985 GV->getName() == "llvm.used");
986 return false;
987 }))
988 continue;
989 }
990 if (PutOffender)
991 *PutOffender = FU;
992 return true;
993 }
994
995 if (IgnoreAssumeLikeCalls) {
996 if (const auto *I = dyn_cast<IntrinsicInst>(Call))
997 if (I->isAssumeLikeIntrinsic())
998 continue;
999 }
1000
1001 if (!Call->isCallee(&U) || (!IgnoreCastedDirectCall &&
1002 Call->getFunctionType() != getFunctionType())) {
1003 if (IgnoreARCAttachedCall &&
1004 Call->isOperandBundleOfType(LLVMContext::OB_clang_arc_attachedcall,
1005 U.getOperandNo()))
1006 continue;
1007
1008 if (PutOffender)
1009 *PutOffender = FU;
1010 return true;
1011 }
1012 }
1013 return false;
1014}
1015
1016bool Function::isDefTriviallyDead() const {
1017 // Check the linkage
1018 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1019 !hasAvailableExternallyLinkage())
1020 return false;
1021
1022 return use_empty();
1023}
1024
1025/// callsFunctionThatReturnsTwice - Return true if the function has a call to
1026/// setjmp or other function that gcc recognizes as "returning twice".
1028 for (const Instruction &I : instructions(this))
1029 if (const auto *Call = dyn_cast<CallBase>(&I))
1030 if (Call->hasFnAttr(Attribute::ReturnsTwice))
1031 return true;
1032
1033 return false;
1034}
1035
1037 assert(hasPersonalityFn() && getNumOperands());
1038 return cast<Constant>(Op<0>());
1039}
1040
1042 setHungoffOperand<0>(Fn);
1043 setValueSubclassDataBit(3, Fn != nullptr);
1044}
1045
1047 assert(hasPrefixData() && getNumOperands());
1048 return cast<Constant>(Op<1>());
1049}
1050
1051void Function::setPrefixData(Constant *PrefixData) {
1052 setHungoffOperand<1>(PrefixData);
1053 setValueSubclassDataBit(1, PrefixData != nullptr);
1054}
1055
1057 assert(hasPrologueData() && getNumOperands());
1058 return cast<Constant>(Op<2>());
1059}
1060
1061void Function::setPrologueData(Constant *PrologueData) {
1062 setHungoffOperand<2>(PrologueData);
1063 setValueSubclassDataBit(2, PrologueData != nullptr);
1064}
1065
1066void Function::allocHungoffUselist() {
1067 // If we've already allocated a uselist, stop here.
1068 if (getNumOperands())
1069 return;
1070
1071 allocHungoffUses(3, /*IsPhi=*/ false);
1072 setNumHungOffUseOperands(3);
1073
1074 // Initialize the uselist with placeholder operands to allow traversal.
1076 Op<0>().set(CPN);
1077 Op<1>().set(CPN);
1078 Op<2>().set(CPN);
1079}
1080
1081template <int Idx>
1082void Function::setHungoffOperand(Constant *C) {
1083 if (C) {
1084 allocHungoffUselist();
1085 Op<Idx>().set(C);
1086 } else if (getNumOperands()) {
1088 }
1089}
1090
1091void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1092 assert(Bit < 16 && "SubclassData contains only 16 bits");
1093 if (On)
1094 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1095 else
1096 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1097}
1098
1100 const DenseSet<GlobalValue::GUID> *S) {
1101#if !defined(NDEBUG)
1102 auto PrevCount = getEntryCount();
1103 assert(!PrevCount || PrevCount->getType() == Count.getType());
1104#endif
1105
1106 auto ImportGUIDs = getImportGUIDs();
1107 if (S == nullptr && ImportGUIDs.size())
1108 S = &ImportGUIDs;
1109
1110 MDBuilder MDB(getContext());
1111 setMetadata(
1112 LLVMContext::MD_prof,
1113 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
1114}
1115
1117 const DenseSet<GlobalValue::GUID> *Imports) {
1118 setEntryCount(ProfileCount(Count, Type), Imports);
1119}
1120
1121std::optional<ProfileCount> Function::getEntryCount(bool AllowSynthetic) const {
1122 MDNode *MD = getMetadata(LLVMContext::MD_prof);
1123 if (MD && MD->getOperand(0))
1124 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
1125 if (MDS->getString() == MDProfLabels::FunctionEntryCount) {
1128 // A value of -1 is used for SamplePGO when there were no samples.
1129 // Treat this the same as unknown.
1130 if (Count == (uint64_t)-1)
1131 return std::nullopt;
1132 return ProfileCount(Count, PCT_Real);
1133 } else if (AllowSynthetic &&
1134 MDS->getString() ==
1138 return ProfileCount(Count, PCT_Synthetic);
1139 }
1140 }
1141 return std::nullopt;
1142}
1143
1146 if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1147 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1148 if (MDS->getString() == MDProfLabels::FunctionEntryCount)
1149 for (unsigned i = 2; i < MD->getNumOperands(); i++)
1151 ->getValue()
1152 .getZExtValue());
1153 return R;
1154}
1155
1156bool Function::nullPointerIsDefined() const {
1157 return hasFnAttribute(Attribute::NullPointerIsValid);
1158}
1159
1160unsigned Function::getVScaleValue() const {
1161 Attribute Attr = getFnAttribute(Attribute::VScaleRange);
1162 if (!Attr.isValid())
1163 return 0;
1164
1165 unsigned VScale = Attr.getVScaleRangeMin();
1166 if (VScale && VScale == Attr.getVScaleRangeMax())
1167 return VScale;
1168
1169 return 0;
1170}
1171
1172bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
1173 if (F && F->nullPointerIsDefined())
1174 return true;
1175
1176 if (AS != 0)
1177 return true;
1178
1179 return false;
1180}
1181
1183 switch (CC) {
1184 case CallingConv::C:
1185 case CallingConv::Fast:
1186 case CallingConv::Cold:
1187 case CallingConv::GHC:
1188 case CallingConv::HiPE:
1192 case CallingConv::Swift:
1194 case CallingConv::Tail:
1209 case CallingConv::Win64:
1217 return true;
1222 return false;
1240 case CallingConv::GRAAL:
1257 return true;
1258 default:
1259 return false;
1260 }
1261
1262 llvm_unreachable("covered callingconv switch");
1263}
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Lower Kernel Arguments
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
This file implements the BitVector class.
static bool setMemoryEffects(Function &F, MemoryEffects ME)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:215
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Finalize Linkage
This file defines the DenseSet and SmallDenseSet classes.
@ Default
Module.h This file contains the declarations for the Module class.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
Machine Check Debug Module
This file contains the declarations for metadata subclasses.
This file contains the declarations for profiling metadata utility functions.
static StringRef getName(Value *V)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static const char * name
This file contains some templates that are useful if you are working with the STL at all.
static Type * getMemoryParamAllocType(AttributeSet ParamAttrs)
For a byval, sret, inalloca, or preallocated parameter, get the in-memory parameter type.
Definition Function.cpp:185
static cl::opt< int > NonGlobalValueMaxNameSize("non-global-value-max-name-size", cl::Hidden, cl::init(1024), cl::desc("Maximum size for the name of non-global values."))
static MutableArrayRef< Argument > makeArgArray(Argument *Args, size_t Count)
Definition Function.cpp:549
static unsigned computeAddrSpace(unsigned AddrSpace, Module *M)
Definition Function.cpp:473
This file defines the SmallString class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1540
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI Type * getParamByRefType() const
If this is a byref argument, return its type.
Definition Function.cpp:235
LLVM_ABI bool hasDeadOnReturnAttr() const
Return true if this argument has the dead_on_return attribute.
Definition Function.cpp:133
LLVM_ABI Attribute getAttribute(Attribute::AttrKind Kind) const
Definition Function.cpp:347
LLVM_ABI bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
Definition Function.cpp:273
LLVM_ABI bool hasNonNullAttr(bool AllowUndefOrPoison=true) const
Return true if this argument has the nonnull attribute.
Definition Function.cpp:115
LLVM_ABI bool hasByRefAttr() const
Return true if this argument has the byref attribute.
Definition Function.cpp:139
LLVM_ABI uint64_t getDereferenceableOrNullBytes() const
If this argument has the dereferenceable_or_null attribute, return the number of bytes known to be de...
Definition Function.cpp:251
LLVM_ABI void addAttr(Attribute::AttrKind Kind)
Definition Function.cpp:321
LLVM_ABI Argument(Type *Ty, const Twine &Name="", Function *F=nullptr, unsigned ArgNo=0)
Argument constructor.
Definition Function.cpp:106
LLVM_ABI bool onlyReadsMemory() const
Return true if this argument has the readonly or readnone attribute.
Definition Function.cpp:309
LLVM_ABI bool hasPointeeInMemoryValueAttr() const
Return true if this argument has the byval, sret, inalloca, preallocated, or byref attribute.
Definition Function.cpp:172
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Check if an argument has a given attribute.
Definition Function.cpp:339
LLVM_ABI bool hasReturnedAttr() const
Return true if this argument has the returned attribute.
Definition Function.cpp:297
LLVM_ABI Type * getParamStructRetType() const
If this is an sret argument, return its type.
Definition Function.cpp:230
LLVM_ABI bool hasInRegAttr() const
Return true if this argument has the inreg attribute.
Definition Function.cpp:293
LLVM_ABI bool hasByValAttr() const
Return true if this argument has the byval attribute.
Definition Function.cpp:128
LLVM_ABI bool hasPreallocatedAttr() const
Return true if this argument has the preallocated attribute.
Definition Function.cpp:158
LLVM_ABI bool hasSExtAttr() const
Return true if this argument has the sext attribute.
Definition Function.cpp:305
LLVM_ABI void removeAttr(Attribute::AttrKind Kind)
Remove attributes from an argument.
Definition Function.cpp:329
LLVM_ABI uint64_t getPassPointeeByValueCopySize(const DataLayout &DL) const
If this argument satisfies has hasPassPointeeByValueAttr, return the in-memory ABI size copied to the...
Definition Function.cpp:202
LLVM_ABI void removeAttrs(const AttributeMask &AM)
Definition Function.cpp:333
LLVM_ABI Type * getPointeeInMemoryValueType() const
If hasPointeeInMemoryValueAttr returns true, the in-memory ABI type is returned.
Definition Function.cpp:210
LLVM_ABI bool hasInAllocaAttr() const
Return true if this argument has the inalloca attribute.
Definition Function.cpp:153
LLVM_ABI bool hasSwiftErrorAttr() const
Return true if this argument has the swifterror attribute.
Definition Function.cpp:149
LLVM_ABI FPClassTest getNoFPClass() const
If this argument has nofpclass attribute, return the mask representing disallowed floating-point valu...
Definition Function.cpp:257
LLVM_ABI void addAttrs(AttrBuilder &B)
Add attributes to an argument.
Definition Function.cpp:315
LLVM_ABI bool hasNoFreeAttr() const
Return true if this argument has the nofree attribute.
Definition Function.cpp:283
LLVM_ABI bool hasSwiftSelfAttr() const
Return true if this argument has the swiftself attribute.
Definition Function.cpp:145
LLVM_ABI Type * getParamInAllocaType() const
If this is an inalloca argument, return its type.
Definition Function.cpp:240
LLVM_ABI bool hasZExtAttr() const
Return true if this argument has the zext attribute.
Definition Function.cpp:301
LLVM_ABI Type * getParamByValType() const
If this is a byval argument, return its type.
Definition Function.cpp:225
LLVM_ABI bool hasNestAttr() const
Return true if this argument has the nest attribute.
Definition Function.cpp:268
LLVM_ABI MaybeAlign getParamAlign() const
If this is a byval or inalloca argument, return its alignment.
Definition Function.cpp:216
LLVM_ABI std::optional< ConstantRange > getRange() const
If this argument has a range attribute, return the value range of the argument.
Definition Function.cpp:261
LLVM_ABI bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
Definition Function.cpp:288
LLVM_ABI AttributeSet getAttributes() const
Definition Function.cpp:351
LLVM_ABI bool hasPassPointeeByValueCopyAttr() const
Return true if this argument has the byval, inalloca, or preallocated attribute.
Definition Function.cpp:164
LLVM_ABI MaybeAlign getParamStackAlign() const
Definition Function.cpp:221
LLVM_ABI bool hasNoCaptureAttr() const
Return true if this argument has the nocapture attribute.
Definition Function.cpp:278
LLVM_ABI uint64_t getDereferenceableBytes() const
If this argument has the dereferenceable attribute, return the number of bytes known to be dereferenc...
Definition Function.cpp:245
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:361
LLVM_ABI Type * getInAllocaType() const
LLVM_ABI Type * getByValType() const
LLVM_ABI Type * getStructRetType() const
LLVM_ABI Type * getPreallocatedType() const
LLVM_ABI Type * getByRefType() const
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:88
static LLVM_ABI Attribute getWithMemoryEffects(LLVMContext &Context, MemoryEffects ME)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:154
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This class represents a range of values.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Implements a dense probed hash-table based set.
Definition DenseSet.h:261
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition Type.cpp:399
Class to represent profile counts.
Definition Function.h:297
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:637
unsigned getVScaleValue() const
Return the value for vscale based on the vscale_range attribute or 0 when unknown.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs)
adds the attributes to the list of attributes for the given arg.
Definition Function.cpp:673
void removeRetAttr(Attribute::AttrKind Kind)
removes the attribute from the return value list of attributes.
Definition Function.cpp:697
void addRetAttrs(const AttrBuilder &Attrs)
Add return value attributes to this function.
Definition Function.cpp:661
bool isDefTriviallyDead() const
isDefTriviallyDead - Return true if it is trivially safe to remove this function definition from the ...
bool onlyAccessesInaccessibleMemOrArgMem() const
Determine if the function may only access memory that is either inaccessible from the IR or pointed t...
Definition Function.cpp:923
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition Function.h:759
BasicBlockListType::iterator iterator
Definition Function.h:69
bool hasAddressTaken(const User **=nullptr, bool IgnoreCallbackUses=false, bool IgnoreAssumeLikeCalls=true, bool IngoreLLVMUsed=false, bool IgnoreARCAttachedCall=false, bool IgnoreCastedDirectCall=false) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition Function.cpp:951
void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
removes the attribute from the list of attributes.
Definition Function.cpp:709
bool nullPointerIsDefined() const
Check if null pointer dereferencing is considered undefined behavior for the function.
Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
gets the specified attribute from the list of attributes.
Definition Function.cpp:788
void setPrefixData(Constant *PrefixData)
bool hasStackProtectorFnAttr() const
Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
Definition Function.cpp:848
void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it.
Definition Function.cpp:444
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:363
void addFnAttrs(const AttrBuilder &Attrs)
Add function attributes to this function.
Definition Function.cpp:649
void renumberBlocks()
Renumber basic blocks into a dense value range starting from 0.
Definition Function.cpp:69
void setDoesNotAccessMemory()
Definition Function.cpp:883
void setGC(std::string Str)
Definition Function.cpp:836
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:762
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:774
bool isConstrainedFPIntrinsic() const
Returns true if the function is one of the "Constrained Floating-PointIntrinsics".
Definition Function.cpp:553
void setOnlyAccessesArgMemory()
Definition Function.cpp:908
MemoryEffects getMemoryEffects() const
Definition Function.cpp:872
void setOnlyAccessesInaccessibleMemory()
Definition Function.cpp:917
void removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs)
removes the attribute from the list of attributes.
Definition Function.cpp:717
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
check if an attributes is in the list of attributes.
Definition Function.cpp:739
bool hasAttributeAtIndex(unsigned Idx, Attribute::AttrKind Kind) const
Check if attribute of the given kind is set at the given index.
Definition Function.cpp:757
static Function * createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Creates a function with some attributes recorded in llvm.module.flags and the LLVMContext applied.
Definition Function.cpp:380
void setOnlyReadsMemory()
Definition Function.cpp:891
bool isTargetIntrinsic() const
isTargetIntrinsic - Returns true if this function is an intrinsic and the intrinsic is specific to a ...
Definition Function.cpp:931
void removeFnAttrs(const AttributeMask &Attrs)
Definition Function.cpp:693
DenormalMode getDenormalModeRaw() const
Return the representational value of "denormal-fp-math".
Definition Function.cpp:815
void addRetAttr(Attribute::AttrKind Kind)
Add return value attributes to this function.
Definition Function.cpp:653
DenormalMode getDenormalModeF32Raw() const
Return the representational value of "denormal-fp-math-f32".
Definition Function.cpp:821
Constant * getPrologueData() const
Get the prologue data associated with this function.
void convertFromNewDbgValues()
Definition Function.cpp:96
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void setOnlyWritesMemory()
Definition Function.cpp:899
void setPersonalityFn(Constant *Fn)
DenseSet< GlobalValue::GUID > getImportGUIDs() const
Returns the set of GUIDs that needs to be imported to the function for sample PGO,...
void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind)
removes the attribute from the list of attributes.
Definition Function.cpp:677
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:448
void removeFnAttr(Attribute::AttrKind Kind)
Remove function attributes from this function.
Definition Function.cpp:685
void addDereferenceableOrNullParamAttr(unsigned ArgNo, uint64_t Bytes)
adds the dereferenceable_or_null attribute to the list of attributes for the given arg.
Definition Function.cpp:793
void addRangeRetAttr(const ConstantRange &CR)
adds the range attribute to the list of attributes for the return value.
Definition Function.cpp:799
void stealArgumentListFrom(Function &Src)
Steal arguments from another function.
Definition Function.cpp:566
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:359
const std::string & getGC() const
Definition Function.cpp:831
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition Function.cpp:665
bool doesNotAccessMemory() const
Determine if the function does not access memory.
Definition Function.cpp:880
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
Definition Function.cpp:803
void updateAfterNameChange()
Update internal caches that depend on the function name (such as the intrinsic ID and libcall cache).
Definition Function.cpp:935
bool callsFunctionThatReturnsTwice() const
callsFunctionThatReturnsTwice - Return true if the function has a call to setjmp or other function th...
bool hasRetAttribute(Attribute::AttrKind Kind) const
check if an attribute is in the list of attributes for the return value.
Definition Function.cpp:735
bool onlyWritesMemory() const
Determine if the function does not access or only writes memory.
Definition Function.cpp:896
std::optional< ProfileCount > getEntryCount(bool AllowSynthetic=false) const
Get the entry count for this function.
bool onlyAccessesInaccessibleMemory() const
Determine if the function may only access memory that is inaccessible from the IR.
Definition Function.cpp:914
void setPrologueData(Constant *PrologueData)
void removeRetAttrs(const AttributeMask &Attrs)
removes the attributes from the return value list of attributes.
Definition Function.cpp:705
bool onlyAccessesArgMemory() const
Determine if the call can access memory only using pointers based on its arguments.
Definition Function.cpp:905
Function::iterator erase(Function::iterator FromIt, Function::iterator ToIt)
Erases a range of BasicBlocks from FromIt to (not including) ToIt.
Definition Function.cpp:464
void setMemoryEffects(MemoryEffects ME)
Definition Function.cpp:875
Constant * getPrefixData() const
Get the prefix data associated with this function.
Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const
gets the attribute from the list of attributes.
Definition Function.cpp:748
iterator end()
Definition Function.h:853
void convertToNewDbgValues()
Definition Function.cpp:90
void setOnlyAccessesInaccessibleMemOrArgMem()
Definition Function.cpp:926
void setEntryCount(ProfileCount Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes)
adds the dereferenceable attribute to the list of attributes for the given arg.
Definition Function.cpp:722
unsigned getInstructionCount() const
Returns the number of non-debug IR instructions in this function.
Definition Function.cpp:367
bool onlyReadsMemory() const
Determine if the function does not access or only reads memory.
Definition Function.cpp:888
void addAttributeAtIndex(unsigned i, Attribute Attr)
adds the attribute to the list of attributes.
Definition Function.cpp:633
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:727
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:856
Attribute getRetAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind for the return value.
Definition Function.cpp:770
LLVM_ABI void copyAttributesFrom(const GlobalObject *Src)
Definition Globals.cpp:155
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Metadata node.
Definition Metadata.h:1077
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1445
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1451
A single uniqued string.
Definition Metadata.h:720
static MemoryEffectsBase readOnly()
Definition ModRef.h:125
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:135
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:141
static MemoryEffectsBase writeOnly()
Definition ModRef.h:130
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:158
static MemoryEffectsBase none()
Definition ModRef.h:120
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
Definition Module.h:596
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition ArrayRef.h:303
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:151
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void dropAllReferences()
Drop all references to operands.
Definition User.h:349
user_iterator user_begin()
Definition Value.h:402
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
iterator_range< user_iterator > users()
Definition Value.h:426
bool user_empty() const
Definition Value.h:389
void push_back(pointer val)
Definition ilist.h:250
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
LLVM_ABI LLVM_READNONE bool supportsNonVoidReturnType(CallingConv::ID CC)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ ARM64EC_Thunk_Native
Calling convention used in the ARM64EC ABI to implement calls between ARM64 code and thunks.
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ M68k_INTR
Used for M68k interrupt routines.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ MSP430_BUILTIN
Used for special MSP430 rtlib functions which have an "optimized" convention using additional registe...
@ AVR_SIGNAL
Used for AVR signal routines.
@ HiPE
Used by the High-Performance Erlang Compiler (HiPE).
Definition CallingConv.h:53
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ RISCV_VLSCall_32
Calling convention used for RISC-V V-extension fixed vectors.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ WASM_EmscriptenInvoke
For emscripten __invoke_* functions.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AVR_BUILTIN
Used for special AVR rtlib functions which have an "optimized" convention to preserve registers.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ ARM64EC_Thunk_X64
Calling convention used in the ARM64EC ABI to implement calls between x64 code and thunks.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
LLVM_ABI bool isConstrainedFPIntrinsic(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics".
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
LLVM_ABI bool isTargetIntrinsic(ID IID)
isTargetIntrinsic - Returns true if IID is an intrinsic specific to a certain target.
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:681
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:666
constexpr double e
Definition MathExtras.h:47
Context & getContext() const
Definition BasicBlock.h:99
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1727
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:294
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:296
UWTableKind
Definition CodeGen.h:148
@ None
No unwind table requested.
Definition CodeGen.h:149
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:288
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
Function::ProfileCount ProfileCount
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
DWARFExpression::Operation Op
DenormalMode parseDenormalFPAttribute(StringRef Str)
Returns the denormal mode to use for inputs and outputs.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:315
#define N
static LLVM_ABI const fltSemantics & IEEEsingle() LLVM_READNONE
Definition APFloat.cpp:266
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getInvalid()
static LLVM_ABI const char * SyntheticFunctionEntryCount
static LLVM_ABI const char * FunctionEntryCount
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:117