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"
14#include "SymbolTableListTraitsImpl.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/IR/AbstractCallSite.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"
27#include "llvm/IR/ConstantRange.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/GlobalValue.h"
31#include "llvm/IR/InstIterator.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/IntrinsicsAArch64.h"
36#include "llvm/IR/IntrinsicsAMDGPU.h"
37#include "llvm/IR/IntrinsicsARM.h"
38#include "llvm/IR/IntrinsicsBPF.h"
39#include "llvm/IR/IntrinsicsDirectX.h"
40#include "llvm/IR/IntrinsicsHexagon.h"
41#include "llvm/IR/IntrinsicsLoongArch.h"
42#include "llvm/IR/IntrinsicsMips.h"
43#include "llvm/IR/IntrinsicsNVPTX.h"
44#include "llvm/IR/IntrinsicsPowerPC.h"
45#include "llvm/IR/IntrinsicsR600.h"
46#include "llvm/IR/IntrinsicsRISCV.h"
47#include "llvm/IR/IntrinsicsS390.h"
48#include "llvm/IR/IntrinsicsSPIRV.h"
49#include "llvm/IR/IntrinsicsVE.h"
50#include "llvm/IR/IntrinsicsWebAssembly.h"
51#include "llvm/IR/IntrinsicsX86.h"
52#include "llvm/IR/IntrinsicsXCore.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/MDBuilder.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/Module.h"
57#include "llvm/IR/Operator.h"
58#include "llvm/IR/SymbolTableListTraits.h"
59#include "llvm/IR/Type.h"
60#include "llvm/IR/Use.h"
61#include "llvm/IR/User.h"
62#include "llvm/IR/Value.h"
63#include "llvm/IR/ValueSymbolTable.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/CommandLine.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/ErrorHandling.h"
68#include "llvm/Support/ModRef.h"
69#include <cassert>
70#include <cstddef>
71#include <cstdint>
72#include <cstring>
73#include <string>
74
75using namespace llvm;
76using ProfileCount = Function::ProfileCount;
77
78// Explicit instantiations of SymbolTableListTraits since some of the methods
79// are not in the public header file...
80template class llvm::SymbolTableListTraits<BasicBlock>;
81
82static cl::opt<int> NonGlobalValueMaxNameSize(
83 "non-global-value-max-name-size", cl::Hidden, cl::init(Val: 1024),
84 cl::desc("Maximum size for the name of non-global values."));
85
86extern cl::opt<bool> UseNewDbgInfoFormat;
87
88void Function::convertToNewDbgValues() {
89 IsNewDbgInfoFormat = true;
90 for (auto &BB : *this) {
91 BB.convertToNewDbgValues();
92 }
93}
94
95void Function::convertFromNewDbgValues() {
96 IsNewDbgInfoFormat = false;
97 for (auto &BB : *this) {
98 BB.convertFromNewDbgValues();
99 }
100}
101
102void Function::setIsNewDbgInfoFormat(bool NewFlag) {
103 if (NewFlag && !IsNewDbgInfoFormat)
104 convertToNewDbgValues();
105 else if (!NewFlag && IsNewDbgInfoFormat)
106 convertFromNewDbgValues();
107}
108void Function::setNewDbgInfoFormatFlag(bool NewFlag) {
109 for (auto &BB : *this) {
110 BB.setNewDbgInfoFormatFlag(NewFlag);
111 }
112 IsNewDbgInfoFormat = NewFlag;
113}
114
115//===----------------------------------------------------------------------===//
116// Argument Implementation
117//===----------------------------------------------------------------------===//
118
119Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
120 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
121 setName(Name);
122}
123
124void Argument::setParent(Function *parent) {
125 Parent = parent;
126}
127
128bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {
129 if (!getType()->isPointerTy()) return false;
130 if (getParent()->hasParamAttribute(ArgNo: getArgNo(), Kind: Attribute::NonNull) &&
131 (AllowUndefOrPoison ||
132 getParent()->hasParamAttribute(ArgNo: getArgNo(), Kind: Attribute::NoUndef)))
133 return true;
134 else if (getDereferenceableBytes() > 0 &&
135 !NullPointerIsDefined(F: getParent(),
136 AS: getType()->getPointerAddressSpace()))
137 return true;
138 return false;
139}
140
141bool Argument::hasByValAttr() const {
142 if (!getType()->isPointerTy()) return false;
143 return hasAttribute(Kind: Attribute::ByVal);
144}
145
146bool Argument::hasByRefAttr() const {
147 if (!getType()->isPointerTy())
148 return false;
149 return hasAttribute(Kind: Attribute::ByRef);
150}
151
152bool Argument::hasSwiftSelfAttr() const {
153 return getParent()->hasParamAttribute(ArgNo: getArgNo(), Kind: Attribute::SwiftSelf);
154}
155
156bool Argument::hasSwiftErrorAttr() const {
157 return getParent()->hasParamAttribute(ArgNo: getArgNo(), Kind: Attribute::SwiftError);
158}
159
160bool Argument::hasInAllocaAttr() const {
161 if (!getType()->isPointerTy()) return false;
162 return hasAttribute(Kind: Attribute::InAlloca);
163}
164
165bool Argument::hasPreallocatedAttr() const {
166 if (!getType()->isPointerTy())
167 return false;
168 return hasAttribute(Kind: Attribute::Preallocated);
169}
170
171bool Argument::hasPassPointeeByValueCopyAttr() const {
172 if (!getType()->isPointerTy()) return false;
173 AttributeList Attrs = getParent()->getAttributes();
174 return Attrs.hasParamAttr(ArgNo: getArgNo(), Kind: Attribute::ByVal) ||
175 Attrs.hasParamAttr(ArgNo: getArgNo(), Kind: Attribute::InAlloca) ||
176 Attrs.hasParamAttr(ArgNo: getArgNo(), Kind: Attribute::Preallocated);
177}
178
179bool Argument::hasPointeeInMemoryValueAttr() const {
180 if (!getType()->isPointerTy())
181 return false;
182 AttributeList Attrs = getParent()->getAttributes();
183 return Attrs.hasParamAttr(ArgNo: getArgNo(), Kind: Attribute::ByVal) ||
184 Attrs.hasParamAttr(ArgNo: getArgNo(), Kind: Attribute::StructRet) ||
185 Attrs.hasParamAttr(ArgNo: getArgNo(), Kind: Attribute::InAlloca) ||
186 Attrs.hasParamAttr(ArgNo: getArgNo(), Kind: Attribute::Preallocated) ||
187 Attrs.hasParamAttr(ArgNo: getArgNo(), Kind: Attribute::ByRef);
188}
189
190/// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
191/// parameter type.
192static Type *getMemoryParamAllocType(AttributeSet ParamAttrs) {
193 // FIXME: All the type carrying attributes are mutually exclusive, so there
194 // should be a single query to get the stored type that handles any of them.
195 if (Type *ByValTy = ParamAttrs.getByValType())
196 return ByValTy;
197 if (Type *ByRefTy = ParamAttrs.getByRefType())
198 return ByRefTy;
199 if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
200 return PreAllocTy;
201 if (Type *InAllocaTy = ParamAttrs.getInAllocaType())
202 return InAllocaTy;
203 if (Type *SRetTy = ParamAttrs.getStructRetType())
204 return SRetTy;
205
206 return nullptr;
207}
208
209uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const {
210 AttributeSet ParamAttrs =
211 getParent()->getAttributes().getParamAttrs(ArgNo: getArgNo());
212 if (Type *MemTy = getMemoryParamAllocType(ParamAttrs))
213 return DL.getTypeAllocSize(Ty: MemTy);
214 return 0;
215}
216
217Type *Argument::getPointeeInMemoryValueType() const {
218 AttributeSet ParamAttrs =
219 getParent()->getAttributes().getParamAttrs(ArgNo: getArgNo());
220 return getMemoryParamAllocType(ParamAttrs);
221}
222
223MaybeAlign Argument::getParamAlign() const {
224 assert(getType()->isPointerTy() && "Only pointers have alignments");
225 return getParent()->getParamAlign(ArgNo: getArgNo());
226}
227
228MaybeAlign Argument::getParamStackAlign() const {
229 return getParent()->getParamStackAlign(ArgNo: getArgNo());
230}
231
232Type *Argument::getParamByValType() const {
233 assert(getType()->isPointerTy() && "Only pointers have byval types");
234 return getParent()->getParamByValType(ArgNo: getArgNo());
235}
236
237Type *Argument::getParamStructRetType() const {
238 assert(getType()->isPointerTy() && "Only pointers have sret types");
239 return getParent()->getParamStructRetType(ArgNo: getArgNo());
240}
241
242Type *Argument::getParamByRefType() const {
243 assert(getType()->isPointerTy() && "Only pointers have byref types");
244 return getParent()->getParamByRefType(ArgNo: getArgNo());
245}
246
247Type *Argument::getParamInAllocaType() const {
248 assert(getType()->isPointerTy() && "Only pointers have inalloca types");
249 return getParent()->getParamInAllocaType(ArgNo: getArgNo());
250}
251
252uint64_t Argument::getDereferenceableBytes() const {
253 assert(getType()->isPointerTy() &&
254 "Only pointers have dereferenceable bytes");
255 return getParent()->getParamDereferenceableBytes(ArgNo: getArgNo());
256}
257
258uint64_t Argument::getDereferenceableOrNullBytes() const {
259 assert(getType()->isPointerTy() &&
260 "Only pointers have dereferenceable bytes");
261 return getParent()->getParamDereferenceableOrNullBytes(ArgNo: getArgNo());
262}
263
264FPClassTest Argument::getNoFPClass() const {
265 return getParent()->getParamNoFPClass(ArgNo: getArgNo());
266}
267
268std::optional<ConstantRange> Argument::getRange() const {
269 const Attribute RangeAttr = getAttribute(Kind: llvm::Attribute::Range);
270 if (RangeAttr.isValid())
271 return RangeAttr.getRange();
272 return std::nullopt;
273}
274
275bool Argument::hasNestAttr() const {
276 if (!getType()->isPointerTy()) return false;
277 return hasAttribute(Kind: Attribute::Nest);
278}
279
280bool Argument::hasNoAliasAttr() const {
281 if (!getType()->isPointerTy()) return false;
282 return hasAttribute(Kind: Attribute::NoAlias);
283}
284
285bool Argument::hasNoCaptureAttr() const {
286 if (!getType()->isPointerTy()) return false;
287 return hasAttribute(Kind: Attribute::NoCapture);
288}
289
290bool Argument::hasNoFreeAttr() const {
291 if (!getType()->isPointerTy()) return false;
292 return hasAttribute(Kind: Attribute::NoFree);
293}
294
295bool Argument::hasStructRetAttr() const {
296 if (!getType()->isPointerTy()) return false;
297 return hasAttribute(Kind: Attribute::StructRet);
298}
299
300bool Argument::hasInRegAttr() const {
301 return hasAttribute(Kind: Attribute::InReg);
302}
303
304bool Argument::hasReturnedAttr() const {
305 return hasAttribute(Kind: Attribute::Returned);
306}
307
308bool Argument::hasZExtAttr() const {
309 return hasAttribute(Kind: Attribute::ZExt);
310}
311
312bool Argument::hasSExtAttr() const {
313 return hasAttribute(Kind: Attribute::SExt);
314}
315
316bool Argument::onlyReadsMemory() const {
317 AttributeList Attrs = getParent()->getAttributes();
318 return Attrs.hasParamAttr(ArgNo: getArgNo(), Kind: Attribute::ReadOnly) ||
319 Attrs.hasParamAttr(ArgNo: getArgNo(), Kind: Attribute::ReadNone);
320}
321
322void Argument::addAttrs(AttrBuilder &B) {
323 AttributeList AL = getParent()->getAttributes();
324 AL = AL.addParamAttributes(C&: Parent->getContext(), ArgNo: getArgNo(), B);
325 getParent()->setAttributes(AL);
326}
327
328void Argument::addAttr(Attribute::AttrKind Kind) {
329 getParent()->addParamAttr(ArgNo: getArgNo(), Kind);
330}
331
332void Argument::addAttr(Attribute Attr) {
333 getParent()->addParamAttr(ArgNo: getArgNo(), Attr);
334}
335
336void Argument::removeAttr(Attribute::AttrKind Kind) {
337 getParent()->removeParamAttr(ArgNo: getArgNo(), Kind);
338}
339
340void Argument::removeAttrs(const AttributeMask &AM) {
341 AttributeList AL = getParent()->getAttributes();
342 AL = AL.removeParamAttributes(C&: Parent->getContext(), ArgNo: getArgNo(), AttrsToRemove: AM);
343 getParent()->setAttributes(AL);
344}
345
346bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
347 return getParent()->hasParamAttribute(ArgNo: getArgNo(), Kind);
348}
349
350Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
351 return getParent()->getParamAttribute(ArgNo: getArgNo(), Kind);
352}
353
354//===----------------------------------------------------------------------===//
355// Helper Methods in Function
356//===----------------------------------------------------------------------===//
357
358LLVMContext &Function::getContext() const {
359 return getType()->getContext();
360}
361
362const DataLayout &Function::getDataLayout() const {
363 return getParent()->getDataLayout();
364}
365
366unsigned Function::getInstructionCount() const {
367 unsigned NumInstrs = 0;
368 for (const BasicBlock &BB : BasicBlocks)
369 NumInstrs += std::distance(first: BB.instructionsWithoutDebug().begin(),
370 last: BB.instructionsWithoutDebug().end());
371 return NumInstrs;
372}
373
374Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
375 const Twine &N, Module &M) {
376 return Create(Ty, Linkage, AddrSpace: M.getDataLayout().getProgramAddressSpace(), N, M: &M);
377}
378
379Function *Function::createWithDefaultAttr(FunctionType *Ty,
380 LinkageTypes Linkage,
381 unsigned AddrSpace, const Twine &N,
382 Module *M) {
383 auto *F = new Function(Ty, Linkage, AddrSpace, N, M);
384 AttrBuilder B(F->getContext());
385 UWTableKind UWTable = M->getUwtable();
386 if (UWTable != UWTableKind::None)
387 B.addUWTableAttr(Kind: UWTable);
388 switch (M->getFramePointer()) {
389 case FramePointerKind::None:
390 // 0 ("none") is the default.
391 break;
392 case FramePointerKind::Reserved:
393 B.addAttribute(A: "frame-pointer", V: "reserved");
394 break;
395 case FramePointerKind::NonLeaf:
396 B.addAttribute(A: "frame-pointer", V: "non-leaf");
397 break;
398 case FramePointerKind::All:
399 B.addAttribute(A: "frame-pointer", V: "all");
400 break;
401 }
402 if (M->getModuleFlag(Key: "function_return_thunk_extern"))
403 B.addAttribute(Val: Attribute::FnRetThunkExtern);
404 StringRef DefaultCPU = F->getContext().getDefaultTargetCPU();
405 if (!DefaultCPU.empty())
406 B.addAttribute(A: "target-cpu", V: DefaultCPU);
407 StringRef DefaultFeatures = F->getContext().getDefaultTargetFeatures();
408 if (!DefaultFeatures.empty())
409 B.addAttribute(A: "target-features", V: DefaultFeatures);
410
411 // Check if the module attribute is present and not zero.
412 auto isModuleAttributeSet = [&](const StringRef &ModAttr) -> bool {
413 const auto *Attr =
414 mdconst::extract_or_null<ConstantInt>(MD: M->getModuleFlag(Key: ModAttr));
415 return Attr && !Attr->isZero();
416 };
417
418 auto AddAttributeIfSet = [&](const StringRef &ModAttr) {
419 if (isModuleAttributeSet(ModAttr))
420 B.addAttribute(A: ModAttr);
421 };
422
423 StringRef SignType = "none";
424 if (isModuleAttributeSet("sign-return-address"))
425 SignType = "non-leaf";
426 if (isModuleAttributeSet("sign-return-address-all"))
427 SignType = "all";
428 if (SignType != "none") {
429 B.addAttribute(A: "sign-return-address", V: SignType);
430 B.addAttribute(A: "sign-return-address-key",
431 V: isModuleAttributeSet("sign-return-address-with-bkey")
432 ? "b_key"
433 : "a_key");
434 }
435 AddAttributeIfSet("branch-target-enforcement");
436 AddAttributeIfSet("branch-protection-pauth-lr");
437 AddAttributeIfSet("guarded-control-stack");
438
439 F->addFnAttrs(Attrs: B);
440 return F;
441}
442
443void Function::removeFromParent() {
444 getParent()->getFunctionList().remove(IT: getIterator());
445}
446
447void Function::eraseFromParent() {
448 getParent()->getFunctionList().erase(where: getIterator());
449}
450
451void Function::splice(Function::iterator ToIt, Function *FromF,
452 Function::iterator FromBeginIt,
453 Function::iterator FromEndIt) {
454#ifdef EXPENSIVE_CHECKS
455 // Check that FromBeginIt is before FromEndIt.
456 auto FromFEnd = FromF->end();
457 for (auto It = FromBeginIt; It != FromEndIt; ++It)
458 assert(It != FromFEnd && "FromBeginIt not before FromEndIt!");
459#endif // EXPENSIVE_CHECKS
460 BasicBlocks.splice(where: ToIt, L2&: FromF->BasicBlocks, first: FromBeginIt, last: FromEndIt);
461}
462
463Function::iterator Function::erase(Function::iterator FromIt,
464 Function::iterator ToIt) {
465 return BasicBlocks.erase(first: FromIt, last: ToIt);
466}
467
468//===----------------------------------------------------------------------===//
469// Function Implementation
470//===----------------------------------------------------------------------===//
471
472static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
473 // If AS == -1 and we are passed a valid module pointer we place the function
474 // in the program address space. Otherwise we default to AS0.
475 if (AddrSpace == static_cast<unsigned>(-1))
476 return M ? M->getDataLayout().getProgramAddressSpace() : 0;
477 return AddrSpace;
478}
479
480Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
481 const Twine &name, Module *ParentModule)
482 : GlobalObject(Ty, Value::FunctionVal,
483 OperandTraits<Function>::op_begin(U: this), 0, Linkage, name,
484 computeAddrSpace(AddrSpace, M: ParentModule)),
485 NumArgs(Ty->getNumParams()), IsNewDbgInfoFormat(UseNewDbgInfoFormat) {
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>(args&: 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(val: this);
500 IsNewDbgInfoFormat = ParentModule->IsNewDbgInfoFormat;
501 }
502
503 HasLLVMReservedName = getName().starts_with(Prefix: "llvm.");
504 // Ensure intrinsics have the right parameter attributes.
505 // Note, the IntID field will have been set in Value::setName if this function
506 // name is a valid intrinsic ID.
507 if (IntID)
508 setAttributes(Intrinsic::getAttributes(C&: getContext(), id: IntID));
509}
510
511Function::~Function() {
512 dropAllReferences(); // After this it is safe to delete instructions.
513
514 // Delete all of the method arguments and unlink from symbol table...
515 if (Arguments)
516 clearArguments();
517
518 // Remove the function from the on-the-side GC table.
519 clearGC();
520}
521
522void Function::BuildLazyArguments() const {
523 // Create the arguments vector, all arguments start out unnamed.
524 auto *FT = getFunctionType();
525 if (NumArgs > 0) {
526 Arguments = std::allocator<Argument>().allocate(n: NumArgs);
527 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
528 Type *ArgTy = FT->getParamType(i);
529 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
530 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
531 }
532 }
533
534 // Clear the lazy arguments bit.
535 unsigned SDC = getSubclassDataFromValue();
536 SDC &= ~(1 << 0);
537 const_cast<Function*>(this)->setValueSubclassData(SDC);
538 assert(!hasLazyArguments());
539}
540
541static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
542 return MutableArrayRef<Argument>(Args, Count);
543}
544
545bool Function::isConstrainedFPIntrinsic() const {
546 return Intrinsic::isConstrainedFPIntrinsic(QID: getIntrinsicID());
547}
548
549void Function::clearArguments() {
550 for (Argument &A : makeArgArray(Args: Arguments, Count: NumArgs)) {
551 A.setName("");
552 A.~Argument();
553 }
554 std::allocator<Argument>().deallocate(p: Arguments, n: NumArgs);
555 Arguments = nullptr;
556}
557
558void Function::stealArgumentListFrom(Function &Src) {
559 assert(isDeclaration() && "Expected no references to current arguments");
560
561 // Drop the current arguments, if any, and set the lazy argument bit.
562 if (!hasLazyArguments()) {
563 assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
564 [](const Argument &A) { return A.use_empty(); }) &&
565 "Expected arguments to be unused in declaration");
566 clearArguments();
567 setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
568 }
569
570 // Nothing to steal if Src has lazy arguments.
571 if (Src.hasLazyArguments())
572 return;
573
574 // Steal arguments from Src, and fix the lazy argument bits.
575 assert(arg_size() == Src.arg_size());
576 Arguments = Src.Arguments;
577 Src.Arguments = nullptr;
578 for (Argument &A : makeArgArray(Args: Arguments, Count: NumArgs)) {
579 // FIXME: This does the work of transferNodesFromList inefficiently.
580 SmallString<128> Name;
581 if (A.hasName())
582 Name = A.getName();
583 if (!Name.empty())
584 A.setName("");
585 A.setParent(this);
586 if (!Name.empty())
587 A.setName(Name);
588 }
589
590 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
591 assert(!hasLazyArguments());
592 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
593}
594
595void Function::deleteBodyImpl(bool ShouldDrop) {
596 setIsMaterializable(false);
597
598 for (BasicBlock &BB : *this)
599 BB.dropAllReferences();
600
601 // Delete all basic blocks. They are now unused, except possibly by
602 // blockaddresses, but BasicBlock's destructor takes care of those.
603 while (!BasicBlocks.empty())
604 BasicBlocks.begin()->eraseFromParent();
605
606 if (getNumOperands()) {
607 if (ShouldDrop) {
608 // Drop uses of any optional data (real or placeholder).
609 User::dropAllReferences();
610 setNumHungOffUseOperands(0);
611 } else {
612 // The code needs to match Function::allocHungoffUselist().
613 auto *CPN = ConstantPointerNull::get(T: PointerType::get(C&: getContext(), AddressSpace: 0));
614 Op<0>().set(CPN);
615 Op<1>().set(CPN);
616 Op<2>().set(CPN);
617 }
618 setValueSubclassData(getSubclassDataFromValue() & ~0xe);
619 }
620
621 // Metadata is stored in a side-table.
622 clearMetadata();
623}
624
625void Function::addAttributeAtIndex(unsigned i, Attribute Attr) {
626 AttributeSets = AttributeSets.addAttributeAtIndex(C&: getContext(), Index: i, A: Attr);
627}
628
629void Function::addFnAttr(Attribute::AttrKind Kind) {
630 AttributeSets = AttributeSets.addFnAttribute(C&: getContext(), Kind);
631}
632
633void Function::addFnAttr(StringRef Kind, StringRef Val) {
634 AttributeSets = AttributeSets.addFnAttribute(C&: getContext(), Kind, Value: Val);
635}
636
637void Function::addFnAttr(Attribute Attr) {
638 AttributeSets = AttributeSets.addFnAttribute(C&: getContext(), Attr);
639}
640
641void Function::addFnAttrs(const AttrBuilder &Attrs) {
642 AttributeSets = AttributeSets.addFnAttributes(C&: getContext(), B: Attrs);
643}
644
645void Function::addRetAttr(Attribute::AttrKind Kind) {
646 AttributeSets = AttributeSets.addRetAttribute(C&: getContext(), Kind);
647}
648
649void Function::addRetAttr(Attribute Attr) {
650 AttributeSets = AttributeSets.addRetAttribute(C&: getContext(), Attr);
651}
652
653void Function::addRetAttrs(const AttrBuilder &Attrs) {
654 AttributeSets = AttributeSets.addRetAttributes(C&: getContext(), B: Attrs);
655}
656
657void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
658 AttributeSets = AttributeSets.addParamAttribute(C&: getContext(), ArgNo, Kind);
659}
660
661void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
662 AttributeSets = AttributeSets.addParamAttribute(C&: getContext(), ArgNos: ArgNo, A: Attr);
663}
664
665void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
666 AttributeSets = AttributeSets.addParamAttributes(C&: getContext(), ArgNo, B: Attrs);
667}
668
669void Function::removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) {
670 AttributeSets = AttributeSets.removeAttributeAtIndex(C&: getContext(), Index: i, Kind);
671}
672
673void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) {
674 AttributeSets = AttributeSets.removeAttributeAtIndex(C&: getContext(), Index: i, Kind);
675}
676
677void Function::removeFnAttr(Attribute::AttrKind Kind) {
678 AttributeSets = AttributeSets.removeFnAttribute(C&: getContext(), Kind);
679}
680
681void Function::removeFnAttr(StringRef Kind) {
682 AttributeSets = AttributeSets.removeFnAttribute(C&: getContext(), Kind);
683}
684
685void Function::removeFnAttrs(const AttributeMask &AM) {
686 AttributeSets = AttributeSets.removeFnAttributes(C&: getContext(), AttrsToRemove: AM);
687}
688
689void Function::removeRetAttr(Attribute::AttrKind Kind) {
690 AttributeSets = AttributeSets.removeRetAttribute(C&: getContext(), Kind);
691}
692
693void Function::removeRetAttr(StringRef Kind) {
694 AttributeSets = AttributeSets.removeRetAttribute(C&: getContext(), Kind);
695}
696
697void Function::removeRetAttrs(const AttributeMask &Attrs) {
698 AttributeSets = AttributeSets.removeRetAttributes(C&: getContext(), AttrsToRemove: Attrs);
699}
700
701void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
702 AttributeSets = AttributeSets.removeParamAttribute(C&: getContext(), ArgNo, Kind);
703}
704
705void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
706 AttributeSets = AttributeSets.removeParamAttribute(C&: getContext(), ArgNo, Kind);
707}
708
709void Function::removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs) {
710 AttributeSets =
711 AttributeSets.removeParamAttributes(C&: getContext(), ArgNo, AttrsToRemove: Attrs);
712}
713
714void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
715 AttributeSets =
716 AttributeSets.addDereferenceableParamAttr(C&: getContext(), ArgNo, Bytes);
717}
718
719bool Function::hasFnAttribute(Attribute::AttrKind Kind) const {
720 return AttributeSets.hasFnAttr(Kind);
721}
722
723bool Function::hasFnAttribute(StringRef Kind) const {
724 return AttributeSets.hasFnAttr(Kind);
725}
726
727bool Function::hasRetAttribute(Attribute::AttrKind Kind) const {
728 return AttributeSets.hasRetAttr(Kind);
729}
730
731bool Function::hasParamAttribute(unsigned ArgNo,
732 Attribute::AttrKind Kind) const {
733 return AttributeSets.hasParamAttr(ArgNo, Kind);
734}
735
736Attribute Function::getAttributeAtIndex(unsigned i,
737 Attribute::AttrKind Kind) const {
738 return AttributeSets.getAttributeAtIndex(Index: i, Kind);
739}
740
741Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const {
742 return AttributeSets.getAttributeAtIndex(Index: i, Kind);
743}
744
745Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const {
746 return AttributeSets.getFnAttr(Kind);
747}
748
749Attribute Function::getFnAttribute(StringRef Kind) const {
750 return AttributeSets.getFnAttr(Kind);
751}
752
753Attribute Function::getRetAttribute(Attribute::AttrKind Kind) const {
754 return AttributeSets.getRetAttr(Kind);
755}
756
757uint64_t Function::getFnAttributeAsParsedInteger(StringRef Name,
758 uint64_t Default) const {
759 Attribute A = getFnAttribute(Kind: Name);
760 uint64_t Result = Default;
761 if (A.isStringAttribute()) {
762 StringRef Str = A.getValueAsString();
763 if (Str.getAsInteger(Radix: 0, Result))
764 getContext().emitError(ErrorStr: "cannot parse integer attribute " + Name);
765 }
766
767 return Result;
768}
769
770/// gets the specified attribute from the list of attributes.
771Attribute Function::getParamAttribute(unsigned ArgNo,
772 Attribute::AttrKind Kind) const {
773 return AttributeSets.getParamAttr(ArgNo, Kind);
774}
775
776void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
777 uint64_t Bytes) {
778 AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(C&: getContext(),
779 ArgNo, Bytes);
780}
781
782void Function::addRangeRetAttr(const ConstantRange &CR) {
783 AttributeSets = AttributeSets.addRangeRetAttr(C&: getContext(), CR);
784}
785
786DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const {
787 if (&FPType == &APFloat::IEEEsingle()) {
788 DenormalMode Mode = getDenormalModeF32Raw();
789 // If the f32 variant of the attribute isn't specified, try to use the
790 // generic one.
791 if (Mode.isValid())
792 return Mode;
793 }
794
795 return getDenormalModeRaw();
796}
797
798DenormalMode Function::getDenormalModeRaw() const {
799 Attribute Attr = getFnAttribute(Kind: "denormal-fp-math");
800 StringRef Val = Attr.getValueAsString();
801 return parseDenormalFPAttribute(Str: Val);
802}
803
804DenormalMode Function::getDenormalModeF32Raw() const {
805 Attribute Attr = getFnAttribute(Kind: "denormal-fp-math-f32");
806 if (Attr.isValid()) {
807 StringRef Val = Attr.getValueAsString();
808 return parseDenormalFPAttribute(Str: Val);
809 }
810
811 return DenormalMode::getInvalid();
812}
813
814const std::string &Function::getGC() const {
815 assert(hasGC() && "Function has no collector");
816 return getContext().getGC(Fn: *this);
817}
818
819void Function::setGC(std::string Str) {
820 setValueSubclassDataBit(Bit: 14, On: !Str.empty());
821 getContext().setGC(Fn: *this, GCName: std::move(Str));
822}
823
824void Function::clearGC() {
825 if (!hasGC())
826 return;
827 getContext().deleteGC(Fn: *this);
828 setValueSubclassDataBit(Bit: 14, On: false);
829}
830
831bool Function::hasStackProtectorFnAttr() const {
832 return hasFnAttribute(Kind: Attribute::StackProtect) ||
833 hasFnAttribute(Kind: Attribute::StackProtectStrong) ||
834 hasFnAttribute(Kind: Attribute::StackProtectReq);
835}
836
837/// Copy all additional attributes (those not needed to create a Function) from
838/// the Function Src to this one.
839void Function::copyAttributesFrom(const Function *Src) {
840 GlobalObject::copyAttributesFrom(Src);
841 setCallingConv(Src->getCallingConv());
842 setAttributes(Src->getAttributes());
843 if (Src->hasGC())
844 setGC(Src->getGC());
845 else
846 clearGC();
847 if (Src->hasPersonalityFn())
848 setPersonalityFn(Src->getPersonalityFn());
849 if (Src->hasPrefixData())
850 setPrefixData(Src->getPrefixData());
851 if (Src->hasPrologueData())
852 setPrologueData(Src->getPrologueData());
853}
854
855MemoryEffects Function::getMemoryEffects() const {
856 return getAttributes().getMemoryEffects();
857}
858void Function::setMemoryEffects(MemoryEffects ME) {
859 addFnAttr(Attr: Attribute::getWithMemoryEffects(Context&: getContext(), ME));
860}
861
862/// Determine if the function does not access memory.
863bool Function::doesNotAccessMemory() const {
864 return getMemoryEffects().doesNotAccessMemory();
865}
866void Function::setDoesNotAccessMemory() {
867 setMemoryEffects(MemoryEffects::none());
868}
869
870/// Determine if the function does not access or only reads memory.
871bool Function::onlyReadsMemory() const {
872 return getMemoryEffects().onlyReadsMemory();
873}
874void Function::setOnlyReadsMemory() {
875 setMemoryEffects(getMemoryEffects() & MemoryEffects::readOnly());
876}
877
878/// Determine if the function does not access or only writes memory.
879bool Function::onlyWritesMemory() const {
880 return getMemoryEffects().onlyWritesMemory();
881}
882void Function::setOnlyWritesMemory() {
883 setMemoryEffects(getMemoryEffects() & MemoryEffects::writeOnly());
884}
885
886/// Determine if the call can access memmory only using pointers based
887/// on its arguments.
888bool Function::onlyAccessesArgMemory() const {
889 return getMemoryEffects().onlyAccessesArgPointees();
890}
891void Function::setOnlyAccessesArgMemory() {
892 setMemoryEffects(getMemoryEffects() & MemoryEffects::argMemOnly());
893}
894
895/// Determine if the function may only access memory that is
896/// inaccessible from the IR.
897bool Function::onlyAccessesInaccessibleMemory() const {
898 return getMemoryEffects().onlyAccessesInaccessibleMem();
899}
900void Function::setOnlyAccessesInaccessibleMemory() {
901 setMemoryEffects(getMemoryEffects() & MemoryEffects::inaccessibleMemOnly());
902}
903
904/// Determine if the function may only access memory that is
905/// either inaccessible from the IR or pointed to by its arguments.
906bool Function::onlyAccessesInaccessibleMemOrArgMem() const {
907 return getMemoryEffects().onlyAccessesInaccessibleOrArgMem();
908}
909void Function::setOnlyAccessesInaccessibleMemOrArgMem() {
910 setMemoryEffects(getMemoryEffects() &
911 MemoryEffects::inaccessibleOrArgMemOnly());
912}
913
914/// Table of string intrinsic names indexed by enum value.
915static const char * const IntrinsicNameTable[] = {
916 "not_intrinsic",
917#define GET_INTRINSIC_NAME_TABLE
918#include "llvm/IR/IntrinsicImpl.inc"
919#undef GET_INTRINSIC_NAME_TABLE
920};
921
922/// Table of per-target intrinsic name tables.
923#define GET_INTRINSIC_TARGET_DATA
924#include "llvm/IR/IntrinsicImpl.inc"
925#undef GET_INTRINSIC_TARGET_DATA
926
927bool Function::isTargetIntrinsic(Intrinsic::ID IID) {
928 return IID > TargetInfos[0].Count;
929}
930
931bool Function::isTargetIntrinsic() const {
932 return isTargetIntrinsic(IID: IntID);
933}
934
935/// Find the segment of \c IntrinsicNameTable for intrinsics with the same
936/// target as \c Name, or the generic table if \c Name is not target specific.
937///
938/// Returns the relevant slice of \c IntrinsicNameTable
939static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
940 assert(Name.starts_with("llvm."));
941
942 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
943 // Drop "llvm." and take the first dotted component. That will be the target
944 // if this is target specific.
945 StringRef Target = Name.drop_front(N: 5).split(Separator: '.').first;
946 auto It = partition_point(
947 Range&: Targets, P: [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
948 // We've either found the target or just fall back to the generic set, which
949 // is always first.
950 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
951 return ArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
952}
953
954/// This does the actual lookup of an intrinsic ID which
955/// matches the given function name.
956Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
957 ArrayRef<const char *> NameTable = findTargetSubtable(Name);
958 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
959 if (Idx == -1)
960 return Intrinsic::not_intrinsic;
961
962 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
963 // an index into a sub-table.
964 int Adjust = NameTable.data() - IntrinsicNameTable;
965 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
966
967 // If the intrinsic is not overloaded, require an exact match. If it is
968 // overloaded, require either exact or prefix match.
969 const auto MatchSize = strlen(s: NameTable[Idx]);
970 assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
971 bool IsExactMatch = Name.size() == MatchSize;
972 return IsExactMatch || Intrinsic::isOverloaded(id: ID) ? ID
973 : Intrinsic::not_intrinsic;
974}
975
976void Function::updateAfterNameChange() {
977 LibFuncCache = UnknownLibFunc;
978 StringRef Name = getName();
979 if (!Name.starts_with(Prefix: "llvm.")) {
980 HasLLVMReservedName = false;
981 IntID = Intrinsic::not_intrinsic;
982 return;
983 }
984 HasLLVMReservedName = true;
985 IntID = lookupIntrinsicID(Name);
986}
987
988/// Returns a stable mangling for the type specified for use in the name
989/// mangling scheme used by 'any' types in intrinsic signatures. The mangling
990/// of named types is simply their name. Manglings for unnamed types consist
991/// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
992/// combined with the mangling of their component types. A vararg function
993/// type will have a suffix of 'vararg'. Since function types can contain
994/// other function types, we close a function type mangling with suffix 'f'
995/// which can't be confused with it's prefix. This ensures we don't have
996/// collisions between two unrelated function types. Otherwise, you might
997/// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
998/// The HasUnnamedType boolean is set if an unnamed type was encountered,
999/// indicating that extra care must be taken to ensure a unique name.
1000static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) {
1001 std::string Result;
1002 if (PointerType *PTyp = dyn_cast<PointerType>(Val: Ty)) {
1003 Result += "p" + utostr(X: PTyp->getAddressSpace());
1004 } else if (ArrayType *ATyp = dyn_cast<ArrayType>(Val: Ty)) {
1005 Result += "a" + utostr(X: ATyp->getNumElements()) +
1006 getMangledTypeStr(Ty: ATyp->getElementType(), HasUnnamedType);
1007 } else if (StructType *STyp = dyn_cast<StructType>(Val: Ty)) {
1008 if (!STyp->isLiteral()) {
1009 Result += "s_";
1010 if (STyp->hasName())
1011 Result += STyp->getName();
1012 else
1013 HasUnnamedType = true;
1014 } else {
1015 Result += "sl_";
1016 for (auto *Elem : STyp->elements())
1017 Result += getMangledTypeStr(Ty: Elem, HasUnnamedType);
1018 }
1019 // Ensure nested structs are distinguishable.
1020 Result += "s";
1021 } else if (FunctionType *FT = dyn_cast<FunctionType>(Val: Ty)) {
1022 Result += "f_" + getMangledTypeStr(Ty: FT->getReturnType(), HasUnnamedType);
1023 for (size_t i = 0; i < FT->getNumParams(); i++)
1024 Result += getMangledTypeStr(Ty: FT->getParamType(i), HasUnnamedType);
1025 if (FT->isVarArg())
1026 Result += "vararg";
1027 // Ensure nested function types are distinguishable.
1028 Result += "f";
1029 } else if (VectorType *VTy = dyn_cast<VectorType>(Val: Ty)) {
1030 ElementCount EC = VTy->getElementCount();
1031 if (EC.isScalable())
1032 Result += "nx";
1033 Result += "v" + utostr(X: EC.getKnownMinValue()) +
1034 getMangledTypeStr(Ty: VTy->getElementType(), HasUnnamedType);
1035 } else if (TargetExtType *TETy = dyn_cast<TargetExtType>(Val: Ty)) {
1036 Result += "t";
1037 Result += TETy->getName();
1038 for (Type *ParamTy : TETy->type_params())
1039 Result += "_" + getMangledTypeStr(Ty: ParamTy, HasUnnamedType);
1040 for (unsigned IntParam : TETy->int_params())
1041 Result += "_" + utostr(X: IntParam);
1042 // Ensure nested target extension types are distinguishable.
1043 Result += "t";
1044 } else if (Ty) {
1045 switch (Ty->getTypeID()) {
1046 default: llvm_unreachable("Unhandled type");
1047 case Type::VoidTyID: Result += "isVoid"; break;
1048 case Type::MetadataTyID: Result += "Metadata"; break;
1049 case Type::HalfTyID: Result += "f16"; break;
1050 case Type::BFloatTyID: Result += "bf16"; break;
1051 case Type::FloatTyID: Result += "f32"; break;
1052 case Type::DoubleTyID: Result += "f64"; break;
1053 case Type::X86_FP80TyID: Result += "f80"; break;
1054 case Type::FP128TyID: Result += "f128"; break;
1055 case Type::PPC_FP128TyID: Result += "ppcf128"; break;
1056 case Type::X86_MMXTyID: Result += "x86mmx"; break;
1057 case Type::X86_AMXTyID: Result += "x86amx"; break;
1058 case Type::IntegerTyID:
1059 Result += "i" + utostr(X: cast<IntegerType>(Val: Ty)->getBitWidth());
1060 break;
1061 }
1062 }
1063 return Result;
1064}
1065
1066StringRef Intrinsic::getBaseName(ID id) {
1067 assert(id < num_intrinsics && "Invalid intrinsic ID!");
1068 return IntrinsicNameTable[id];
1069}
1070
1071StringRef Intrinsic::getName(ID id) {
1072 assert(id < num_intrinsics && "Invalid intrinsic ID!");
1073 assert(!Intrinsic::isOverloaded(id) &&
1074 "This version of getName does not support overloading");
1075 return getBaseName(id);
1076}
1077
1078static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef<Type *> Tys,
1079 Module *M, FunctionType *FT,
1080 bool EarlyModuleCheck) {
1081
1082 assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!");
1083 assert((Tys.empty() || Intrinsic::isOverloaded(Id)) &&
1084 "This version of getName is for overloaded intrinsics only");
1085 (void)EarlyModuleCheck;
1086 assert((!EarlyModuleCheck || M ||
1087 !any_of(Tys, [](Type *T) { return isa<PointerType>(T); })) &&
1088 "Intrinsic overloading on pointer types need to provide a Module");
1089 bool HasUnnamedType = false;
1090 std::string Result(Intrinsic::getBaseName(id: Id));
1091 for (Type *Ty : Tys)
1092 Result += "." + getMangledTypeStr(Ty, HasUnnamedType);
1093 if (HasUnnamedType) {
1094 assert(M && "unnamed types need a module");
1095 if (!FT)
1096 FT = Intrinsic::getType(Context&: M->getContext(), id: Id, Tys);
1097 else
1098 assert((FT == Intrinsic::getType(M->getContext(), Id, Tys)) &&
1099 "Provided FunctionType must match arguments");
1100 return M->getUniqueIntrinsicName(BaseName: Result, Id, Proto: FT);
1101 }
1102 return Result;
1103}
1104
1105std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M,
1106 FunctionType *FT) {
1107 assert(M && "We need to have a Module");
1108 return getIntrinsicNameImpl(Id, Tys, M, FT, EarlyModuleCheck: true);
1109}
1110
1111std::string Intrinsic::getNameNoUnnamedTypes(ID Id, ArrayRef<Type *> Tys) {
1112 return getIntrinsicNameImpl(Id, Tys, M: nullptr, FT: nullptr, EarlyModuleCheck: false);
1113}
1114
1115/// IIT_Info - These are enumerators that describe the entries returned by the
1116/// getIntrinsicInfoTableEntries function.
1117///
1118/// Defined in Intrinsics.td.
1119enum IIT_Info {
1120#define GET_INTRINSIC_IITINFO
1121#include "llvm/IR/IntrinsicImpl.inc"
1122#undef GET_INTRINSIC_IITINFO
1123};
1124
1125static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
1126 IIT_Info LastInfo,
1127 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
1128 using namespace Intrinsic;
1129
1130 bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
1131
1132 IIT_Info Info = IIT_Info(Infos[NextElt++]);
1133 unsigned StructElts = 2;
1134
1135 switch (Info) {
1136 case IIT_Done:
1137 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Void, Field: 0));
1138 return;
1139 case IIT_VARARG:
1140 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::VarArg, Field: 0));
1141 return;
1142 case IIT_MMX:
1143 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::MMX, Field: 0));
1144 return;
1145 case IIT_AMX:
1146 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::AMX, Field: 0));
1147 return;
1148 case IIT_TOKEN:
1149 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Token, Field: 0));
1150 return;
1151 case IIT_METADATA:
1152 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Metadata, Field: 0));
1153 return;
1154 case IIT_F16:
1155 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Half, Field: 0));
1156 return;
1157 case IIT_BF16:
1158 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::BFloat, Field: 0));
1159 return;
1160 case IIT_F32:
1161 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Float, Field: 0));
1162 return;
1163 case IIT_F64:
1164 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Double, Field: 0));
1165 return;
1166 case IIT_F128:
1167 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Quad, Field: 0));
1168 return;
1169 case IIT_PPCF128:
1170 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::PPCQuad, Field: 0));
1171 return;
1172 case IIT_I1:
1173 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Integer, Field: 1));
1174 return;
1175 case IIT_I2:
1176 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Integer, Field: 2));
1177 return;
1178 case IIT_I4:
1179 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Integer, Field: 4));
1180 return;
1181 case IIT_AARCH64_SVCOUNT:
1182 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::AArch64Svcount, Field: 0));
1183 return;
1184 case IIT_I8:
1185 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Integer, Field: 8));
1186 return;
1187 case IIT_I16:
1188 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Integer,Field: 16));
1189 return;
1190 case IIT_I32:
1191 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Integer, Field: 32));
1192 return;
1193 case IIT_I64:
1194 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Integer, Field: 64));
1195 return;
1196 case IIT_I128:
1197 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Integer, Field: 128));
1198 return;
1199 case IIT_V1:
1200 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 1, IsScalable: IsScalableVector));
1201 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1202 return;
1203 case IIT_V2:
1204 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 2, IsScalable: IsScalableVector));
1205 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1206 return;
1207 case IIT_V3:
1208 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 3, IsScalable: IsScalableVector));
1209 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1210 return;
1211 case IIT_V4:
1212 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 4, IsScalable: IsScalableVector));
1213 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1214 return;
1215 case IIT_V6:
1216 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 6, IsScalable: IsScalableVector));
1217 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1218 return;
1219 case IIT_V8:
1220 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 8, IsScalable: IsScalableVector));
1221 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1222 return;
1223 case IIT_V10:
1224 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 10, IsScalable: IsScalableVector));
1225 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1226 return;
1227 case IIT_V16:
1228 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 16, IsScalable: IsScalableVector));
1229 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1230 return;
1231 case IIT_V32:
1232 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 32, IsScalable: IsScalableVector));
1233 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1234 return;
1235 case IIT_V64:
1236 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 64, IsScalable: IsScalableVector));
1237 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1238 return;
1239 case IIT_V128:
1240 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 128, IsScalable: IsScalableVector));
1241 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1242 return;
1243 case IIT_V256:
1244 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 256, IsScalable: IsScalableVector));
1245 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1246 return;
1247 case IIT_V512:
1248 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 512, IsScalable: IsScalableVector));
1249 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1250 return;
1251 case IIT_V1024:
1252 OutputTable.push_back(Elt: IITDescriptor::getVector(Width: 1024, IsScalable: IsScalableVector));
1253 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1254 return;
1255 case IIT_EXTERNREF:
1256 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Pointer, Field: 10));
1257 return;
1258 case IIT_FUNCREF:
1259 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Pointer, Field: 20));
1260 return;
1261 case IIT_PTR:
1262 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Pointer, Field: 0));
1263 return;
1264 case IIT_ANYPTR: // [ANYPTR addrspace]
1265 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Pointer,
1266 Field: Infos[NextElt++]));
1267 return;
1268 case IIT_ARG: {
1269 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1270 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Argument, Field: ArgInfo));
1271 return;
1272 }
1273 case IIT_EXTEND_ARG: {
1274 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1275 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::ExtendArgument,
1276 Field: ArgInfo));
1277 return;
1278 }
1279 case IIT_TRUNC_ARG: {
1280 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1281 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::TruncArgument,
1282 Field: ArgInfo));
1283 return;
1284 }
1285 case IIT_HALF_VEC_ARG: {
1286 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1287 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::HalfVecArgument,
1288 Field: ArgInfo));
1289 return;
1290 }
1291 case IIT_SAME_VEC_WIDTH_ARG: {
1292 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1293 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::SameVecWidthArgument,
1294 Field: ArgInfo));
1295 return;
1296 }
1297 case IIT_VEC_OF_ANYPTRS_TO_ELT: {
1298 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1299 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1300 OutputTable.push_back(
1301 Elt: IITDescriptor::get(K: IITDescriptor::VecOfAnyPtrsToElt, Hi: ArgNo, Lo: RefNo));
1302 return;
1303 }
1304 case IIT_EMPTYSTRUCT:
1305 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Struct, Field: 0));
1306 return;
1307 case IIT_STRUCT9: ++StructElts; [[fallthrough]];
1308 case IIT_STRUCT8: ++StructElts; [[fallthrough]];
1309 case IIT_STRUCT7: ++StructElts; [[fallthrough]];
1310 case IIT_STRUCT6: ++StructElts; [[fallthrough]];
1311 case IIT_STRUCT5: ++StructElts; [[fallthrough]];
1312 case IIT_STRUCT4: ++StructElts; [[fallthrough]];
1313 case IIT_STRUCT3: ++StructElts; [[fallthrough]];
1314 case IIT_STRUCT2: {
1315 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Struct,Field: StructElts));
1316
1317 for (unsigned i = 0; i != StructElts; ++i)
1318 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1319 return;
1320 }
1321 case IIT_SUBDIVIDE2_ARG: {
1322 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1323 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Subdivide2Argument,
1324 Field: ArgInfo));
1325 return;
1326 }
1327 case IIT_SUBDIVIDE4_ARG: {
1328 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1329 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::Subdivide4Argument,
1330 Field: ArgInfo));
1331 return;
1332 }
1333 case IIT_VEC_ELEMENT: {
1334 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1335 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::VecElementArgument,
1336 Field: ArgInfo));
1337 return;
1338 }
1339 case IIT_SCALABLE_VEC: {
1340 DecodeIITType(NextElt, Infos, LastInfo: Info, OutputTable);
1341 return;
1342 }
1343 case IIT_VEC_OF_BITCASTS_TO_INT: {
1344 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1345 OutputTable.push_back(Elt: IITDescriptor::get(K: IITDescriptor::VecOfBitcastsToInt,
1346 Field: ArgInfo));
1347 return;
1348 }
1349 }
1350 llvm_unreachable("unhandled");
1351}
1352
1353#define GET_INTRINSIC_GENERATOR_GLOBAL
1354#include "llvm/IR/IntrinsicImpl.inc"
1355#undef GET_INTRINSIC_GENERATOR_GLOBAL
1356
1357void Intrinsic::getIntrinsicInfoTableEntries(ID id,
1358 SmallVectorImpl<IITDescriptor> &T){
1359 // Check to see if the intrinsic's type was expressible by the table.
1360 unsigned TableVal = IIT_Table[id-1];
1361
1362 // Decode the TableVal into an array of IITValues.
1363 SmallVector<unsigned char, 8> IITValues;
1364 ArrayRef<unsigned char> IITEntries;
1365 unsigned NextElt = 0;
1366 if ((TableVal >> 31) != 0) {
1367 // This is an offset into the IIT_LongEncodingTable.
1368 IITEntries = IIT_LongEncodingTable;
1369
1370 // Strip sentinel bit.
1371 NextElt = (TableVal << 1) >> 1;
1372 } else {
1373 // Decode the TableVal into an array of IITValues. If the entry was encoded
1374 // into a single word in the table itself, decode it now.
1375 do {
1376 IITValues.push_back(Elt: TableVal & 0xF);
1377 TableVal >>= 4;
1378 } while (TableVal);
1379
1380 IITEntries = IITValues;
1381 NextElt = 0;
1382 }
1383
1384 // Okay, decode the table into the output vector of IITDescriptors.
1385 DecodeIITType(NextElt, Infos: IITEntries, LastInfo: IIT_Done, OutputTable&: T);
1386 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
1387 DecodeIITType(NextElt, Infos: IITEntries, LastInfo: IIT_Done, OutputTable&: T);
1388}
1389
1390static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
1391 ArrayRef<Type*> Tys, LLVMContext &Context) {
1392 using namespace Intrinsic;
1393
1394 IITDescriptor D = Infos.front();
1395 Infos = Infos.slice(N: 1);
1396
1397 switch (D.Kind) {
1398 case IITDescriptor::Void: return Type::getVoidTy(C&: Context);
1399 case IITDescriptor::VarArg: return Type::getVoidTy(C&: Context);
1400 case IITDescriptor::MMX: return Type::getX86_MMXTy(C&: Context);
1401 case IITDescriptor::AMX: return Type::getX86_AMXTy(C&: Context);
1402 case IITDescriptor::Token: return Type::getTokenTy(C&: Context);
1403 case IITDescriptor::Metadata: return Type::getMetadataTy(C&: Context);
1404 case IITDescriptor::Half: return Type::getHalfTy(C&: Context);
1405 case IITDescriptor::BFloat: return Type::getBFloatTy(C&: Context);
1406 case IITDescriptor::Float: return Type::getFloatTy(C&: Context);
1407 case IITDescriptor::Double: return Type::getDoubleTy(C&: Context);
1408 case IITDescriptor::Quad: return Type::getFP128Ty(C&: Context);
1409 case IITDescriptor::PPCQuad: return Type::getPPC_FP128Ty(C&: Context);
1410 case IITDescriptor::AArch64Svcount:
1411 return TargetExtType::get(Context, Name: "aarch64.svcount");
1412
1413 case IITDescriptor::Integer:
1414 return IntegerType::get(C&: Context, NumBits: D.Integer_Width);
1415 case IITDescriptor::Vector:
1416 return VectorType::get(ElementType: DecodeFixedType(Infos, Tys, Context),
1417 EC: D.Vector_Width);
1418 case IITDescriptor::Pointer:
1419 return PointerType::get(C&: Context, AddressSpace: D.Pointer_AddressSpace);
1420 case IITDescriptor::Struct: {
1421 SmallVector<Type *, 8> Elts;
1422 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1423 Elts.push_back(Elt: DecodeFixedType(Infos, Tys, Context));
1424 return StructType::get(Context, Elements: Elts);
1425 }
1426 case IITDescriptor::Argument:
1427 return Tys[D.getArgumentNumber()];
1428 case IITDescriptor::ExtendArgument: {
1429 Type *Ty = Tys[D.getArgumentNumber()];
1430 if (VectorType *VTy = dyn_cast<VectorType>(Val: Ty))
1431 return VectorType::getExtendedElementVectorType(VTy);
1432
1433 return IntegerType::get(C&: Context, NumBits: 2 * cast<IntegerType>(Val: Ty)->getBitWidth());
1434 }
1435 case IITDescriptor::TruncArgument: {
1436 Type *Ty = Tys[D.getArgumentNumber()];
1437 if (VectorType *VTy = dyn_cast<VectorType>(Val: Ty))
1438 return VectorType::getTruncatedElementVectorType(VTy);
1439
1440 IntegerType *ITy = cast<IntegerType>(Val: Ty);
1441 assert(ITy->getBitWidth() % 2 == 0);
1442 return IntegerType::get(C&: Context, NumBits: ITy->getBitWidth() / 2);
1443 }
1444 case IITDescriptor::Subdivide2Argument:
1445 case IITDescriptor::Subdivide4Argument: {
1446 Type *Ty = Tys[D.getArgumentNumber()];
1447 VectorType *VTy = dyn_cast<VectorType>(Val: Ty);
1448 assert(VTy && "Expected an argument of Vector Type");
1449 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1450 return VectorType::getSubdividedVectorType(VTy, NumSubdivs: SubDivs);
1451 }
1452 case IITDescriptor::HalfVecArgument:
1453 return VectorType::getHalfElementsVectorType(VTy: cast<VectorType>(
1454 Val: Tys[D.getArgumentNumber()]));
1455 case IITDescriptor::SameVecWidthArgument: {
1456 Type *EltTy = DecodeFixedType(Infos, Tys, Context);
1457 Type *Ty = Tys[D.getArgumentNumber()];
1458 if (auto *VTy = dyn_cast<VectorType>(Val: Ty))
1459 return VectorType::get(ElementType: EltTy, EC: VTy->getElementCount());
1460 return EltTy;
1461 }
1462 case IITDescriptor::VecElementArgument: {
1463 Type *Ty = Tys[D.getArgumentNumber()];
1464 if (VectorType *VTy = dyn_cast<VectorType>(Val: Ty))
1465 return VTy->getElementType();
1466 llvm_unreachable("Expected an argument of Vector Type");
1467 }
1468 case IITDescriptor::VecOfBitcastsToInt: {
1469 Type *Ty = Tys[D.getArgumentNumber()];
1470 VectorType *VTy = dyn_cast<VectorType>(Val: Ty);
1471 assert(VTy && "Expected an argument of Vector Type");
1472 return VectorType::getInteger(VTy);
1473 }
1474 case IITDescriptor::VecOfAnyPtrsToElt:
1475 // Return the overloaded type (which determines the pointers address space)
1476 return Tys[D.getOverloadArgNumber()];
1477 }
1478 llvm_unreachable("unhandled");
1479}
1480
1481FunctionType *Intrinsic::getType(LLVMContext &Context,
1482 ID id, ArrayRef<Type*> Tys) {
1483 SmallVector<IITDescriptor, 8> Table;
1484 getIntrinsicInfoTableEntries(id, T&: Table);
1485
1486 ArrayRef<IITDescriptor> TableRef = Table;
1487 Type *ResultTy = DecodeFixedType(Infos&: TableRef, Tys, Context);
1488
1489 SmallVector<Type*, 8> ArgTys;
1490 while (!TableRef.empty())
1491 ArgTys.push_back(Elt: DecodeFixedType(Infos&: TableRef, Tys, Context));
1492
1493 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
1494 // If we see void type as the type of the last argument, it is vararg intrinsic
1495 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
1496 ArgTys.pop_back();
1497 return FunctionType::get(Result: ResultTy, Params: ArgTys, isVarArg: true);
1498 }
1499 return FunctionType::get(Result: ResultTy, Params: ArgTys, isVarArg: false);
1500}
1501
1502bool Intrinsic::isOverloaded(ID id) {
1503#define GET_INTRINSIC_OVERLOAD_TABLE
1504#include "llvm/IR/IntrinsicImpl.inc"
1505#undef GET_INTRINSIC_OVERLOAD_TABLE
1506}
1507
1508/// This defines the "Intrinsic::getAttributes(ID id)" method.
1509#define GET_INTRINSIC_ATTRIBUTES
1510#include "llvm/IR/IntrinsicImpl.inc"
1511#undef GET_INTRINSIC_ATTRIBUTES
1512
1513Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
1514 // There can never be multiple globals with the same name of different types,
1515 // because intrinsics must be a specific type.
1516 auto *FT = getType(Context&: M->getContext(), id, Tys);
1517 return cast<Function>(
1518 Val: M->getOrInsertFunction(
1519 Name: Tys.empty() ? getName(id) : getName(Id: id, Tys, M, FT), T: FT)
1520 .getCallee());
1521}
1522
1523// This defines the "Intrinsic::getIntrinsicForClangBuiltin()" method.
1524#define GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN
1525#include "llvm/IR/IntrinsicImpl.inc"
1526#undef GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN
1527
1528// This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
1529#define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1530#include "llvm/IR/IntrinsicImpl.inc"
1531#undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1532
1533bool Intrinsic::isConstrainedFPIntrinsic(ID QID) {
1534 switch (QID) {
1535#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
1536 case Intrinsic::INTRINSIC:
1537#include "llvm/IR/ConstrainedOps.def"
1538#undef INSTRUCTION
1539 return true;
1540 default:
1541 return false;
1542 }
1543}
1544
1545bool Intrinsic::hasConstrainedFPRoundingModeOperand(Intrinsic::ID QID) {
1546 switch (QID) {
1547#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
1548 case Intrinsic::INTRINSIC: \
1549 return ROUND_MODE == 1;
1550#include "llvm/IR/ConstrainedOps.def"
1551#undef INSTRUCTION
1552 default:
1553 return false;
1554 }
1555}
1556
1557using DeferredIntrinsicMatchPair =
1558 std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
1559
1560static bool matchIntrinsicType(
1561 Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
1562 SmallVectorImpl<Type *> &ArgTys,
1563 SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
1564 bool IsDeferredCheck) {
1565 using namespace Intrinsic;
1566
1567 // If we ran out of descriptors, there are too many arguments.
1568 if (Infos.empty()) return true;
1569
1570 // Do this before slicing off the 'front' part
1571 auto InfosRef = Infos;
1572 auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
1573 DeferredChecks.emplace_back(Args&: T, Args&: InfosRef);
1574 return false;
1575 };
1576
1577 IITDescriptor D = Infos.front();
1578 Infos = Infos.slice(N: 1);
1579
1580 switch (D.Kind) {
1581 case IITDescriptor::Void: return !Ty->isVoidTy();
1582 case IITDescriptor::VarArg: return true;
1583 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
1584 case IITDescriptor::AMX: return !Ty->isX86_AMXTy();
1585 case IITDescriptor::Token: return !Ty->isTokenTy();
1586 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1587 case IITDescriptor::Half: return !Ty->isHalfTy();
1588 case IITDescriptor::BFloat: return !Ty->isBFloatTy();
1589 case IITDescriptor::Float: return !Ty->isFloatTy();
1590 case IITDescriptor::Double: return !Ty->isDoubleTy();
1591 case IITDescriptor::Quad: return !Ty->isFP128Ty();
1592 case IITDescriptor::PPCQuad: return !Ty->isPPC_FP128Ty();
1593 case IITDescriptor::Integer: return !Ty->isIntegerTy(Bitwidth: D.Integer_Width);
1594 case IITDescriptor::AArch64Svcount:
1595 return !isa<TargetExtType>(Val: Ty) ||
1596 cast<TargetExtType>(Val: Ty)->getName() != "aarch64.svcount";
1597 case IITDescriptor::Vector: {
1598 VectorType *VT = dyn_cast<VectorType>(Val: Ty);
1599 return !VT || VT->getElementCount() != D.Vector_Width ||
1600 matchIntrinsicType(Ty: VT->getElementType(), Infos, ArgTys,
1601 DeferredChecks, IsDeferredCheck);
1602 }
1603 case IITDescriptor::Pointer: {
1604 PointerType *PT = dyn_cast<PointerType>(Val: Ty);
1605 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace;
1606 }
1607
1608 case IITDescriptor::Struct: {
1609 StructType *ST = dyn_cast<StructType>(Val: Ty);
1610 if (!ST || !ST->isLiteral() || ST->isPacked() ||
1611 ST->getNumElements() != D.Struct_NumElements)
1612 return true;
1613
1614 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1615 if (matchIntrinsicType(Ty: ST->getElementType(N: i), Infos, ArgTys,
1616 DeferredChecks, IsDeferredCheck))
1617 return true;
1618 return false;
1619 }
1620
1621 case IITDescriptor::Argument:
1622 // If this is the second occurrence of an argument,
1623 // verify that the later instance matches the previous instance.
1624 if (D.getArgumentNumber() < ArgTys.size())
1625 return Ty != ArgTys[D.getArgumentNumber()];
1626
1627 if (D.getArgumentNumber() > ArgTys.size() ||
1628 D.getArgumentKind() == IITDescriptor::AK_MatchType)
1629 return IsDeferredCheck || DeferCheck(Ty);
1630
1631 assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
1632 "Table consistency error");
1633 ArgTys.push_back(Elt: Ty);
1634
1635 switch (D.getArgumentKind()) {
1636 case IITDescriptor::AK_Any: return false; // Success
1637 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1638 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
1639 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Val: Ty);
1640 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Val: Ty);
1641 default: break;
1642 }
1643 llvm_unreachable("all argument kinds not covered");
1644
1645 case IITDescriptor::ExtendArgument: {
1646 // If this is a forward reference, defer the check for later.
1647 if (D.getArgumentNumber() >= ArgTys.size())
1648 return IsDeferredCheck || DeferCheck(Ty);
1649
1650 Type *NewTy = ArgTys[D.getArgumentNumber()];
1651 if (VectorType *VTy = dyn_cast<VectorType>(Val: NewTy))
1652 NewTy = VectorType::getExtendedElementVectorType(VTy);
1653 else if (IntegerType *ITy = dyn_cast<IntegerType>(Val: NewTy))
1654 NewTy = IntegerType::get(C&: ITy->getContext(), NumBits: 2 * ITy->getBitWidth());
1655 else
1656 return true;
1657
1658 return Ty != NewTy;
1659 }
1660 case IITDescriptor::TruncArgument: {
1661 // If this is a forward reference, defer the check for later.
1662 if (D.getArgumentNumber() >= ArgTys.size())
1663 return IsDeferredCheck || DeferCheck(Ty);
1664
1665 Type *NewTy = ArgTys[D.getArgumentNumber()];
1666 if (VectorType *VTy = dyn_cast<VectorType>(Val: NewTy))
1667 NewTy = VectorType::getTruncatedElementVectorType(VTy);
1668 else if (IntegerType *ITy = dyn_cast<IntegerType>(Val: NewTy))
1669 NewTy = IntegerType::get(C&: ITy->getContext(), NumBits: ITy->getBitWidth() / 2);
1670 else
1671 return true;
1672
1673 return Ty != NewTy;
1674 }
1675 case IITDescriptor::HalfVecArgument:
1676 // If this is a forward reference, defer the check for later.
1677 if (D.getArgumentNumber() >= ArgTys.size())
1678 return IsDeferredCheck || DeferCheck(Ty);
1679 return !isa<VectorType>(Val: ArgTys[D.getArgumentNumber()]) ||
1680 VectorType::getHalfElementsVectorType(
1681 VTy: cast<VectorType>(Val: ArgTys[D.getArgumentNumber()])) != Ty;
1682 case IITDescriptor::SameVecWidthArgument: {
1683 if (D.getArgumentNumber() >= ArgTys.size()) {
1684 // Defer check and subsequent check for the vector element type.
1685 Infos = Infos.slice(N: 1);
1686 return IsDeferredCheck || DeferCheck(Ty);
1687 }
1688 auto *ReferenceType = dyn_cast<VectorType>(Val: ArgTys[D.getArgumentNumber()]);
1689 auto *ThisArgType = dyn_cast<VectorType>(Val: Ty);
1690 // Both must be vectors of the same number of elements or neither.
1691 if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
1692 return true;
1693 Type *EltTy = Ty;
1694 if (ThisArgType) {
1695 if (ReferenceType->getElementCount() !=
1696 ThisArgType->getElementCount())
1697 return true;
1698 EltTy = ThisArgType->getElementType();
1699 }
1700 return matchIntrinsicType(Ty: EltTy, Infos, ArgTys, DeferredChecks,
1701 IsDeferredCheck);
1702 }
1703 case IITDescriptor::VecOfAnyPtrsToElt: {
1704 unsigned RefArgNumber = D.getRefArgNumber();
1705 if (RefArgNumber >= ArgTys.size()) {
1706 if (IsDeferredCheck)
1707 return true;
1708 // If forward referencing, already add the pointer-vector type and
1709 // defer the checks for later.
1710 ArgTys.push_back(Elt: Ty);
1711 return DeferCheck(Ty);
1712 }
1713
1714 if (!IsDeferredCheck){
1715 assert(D.getOverloadArgNumber() == ArgTys.size() &&
1716 "Table consistency error");
1717 ArgTys.push_back(Elt: Ty);
1718 }
1719
1720 // Verify the overloaded type "matches" the Ref type.
1721 // i.e. Ty is a vector with the same width as Ref.
1722 // Composed of pointers to the same element type as Ref.
1723 auto *ReferenceType = dyn_cast<VectorType>(Val: ArgTys[RefArgNumber]);
1724 auto *ThisArgVecTy = dyn_cast<VectorType>(Val: Ty);
1725 if (!ThisArgVecTy || !ReferenceType ||
1726 (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))
1727 return true;
1728 return !ThisArgVecTy->getElementType()->isPointerTy();
1729 }
1730 case IITDescriptor::VecElementArgument: {
1731 if (D.getArgumentNumber() >= ArgTys.size())
1732 return IsDeferredCheck ? true : DeferCheck(Ty);
1733 auto *ReferenceType = dyn_cast<VectorType>(Val: ArgTys[D.getArgumentNumber()]);
1734 return !ReferenceType || Ty != ReferenceType->getElementType();
1735 }
1736 case IITDescriptor::Subdivide2Argument:
1737 case IITDescriptor::Subdivide4Argument: {
1738 // If this is a forward reference, defer the check for later.
1739 if (D.getArgumentNumber() >= ArgTys.size())
1740 return IsDeferredCheck || DeferCheck(Ty);
1741
1742 Type *NewTy = ArgTys[D.getArgumentNumber()];
1743 if (auto *VTy = dyn_cast<VectorType>(Val: NewTy)) {
1744 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1745 NewTy = VectorType::getSubdividedVectorType(VTy, NumSubdivs: SubDivs);
1746 return Ty != NewTy;
1747 }
1748 return true;
1749 }
1750 case IITDescriptor::VecOfBitcastsToInt: {
1751 if (D.getArgumentNumber() >= ArgTys.size())
1752 return IsDeferredCheck || DeferCheck(Ty);
1753 auto *ReferenceType = dyn_cast<VectorType>(Val: ArgTys[D.getArgumentNumber()]);
1754 auto *ThisArgVecTy = dyn_cast<VectorType>(Val: Ty);
1755 if (!ThisArgVecTy || !ReferenceType)
1756 return true;
1757 return ThisArgVecTy != VectorType::getInteger(VTy: ReferenceType);
1758 }
1759 }
1760 llvm_unreachable("unhandled");
1761}
1762
1763Intrinsic::MatchIntrinsicTypesResult
1764Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
1765 ArrayRef<Intrinsic::IITDescriptor> &Infos,
1766 SmallVectorImpl<Type *> &ArgTys) {
1767 SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
1768 if (matchIntrinsicType(Ty: FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
1769 IsDeferredCheck: false))
1770 return MatchIntrinsicTypes_NoMatchRet;
1771
1772 unsigned NumDeferredReturnChecks = DeferredChecks.size();
1773
1774 for (auto *Ty : FTy->params())
1775 if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, IsDeferredCheck: false))
1776 return MatchIntrinsicTypes_NoMatchArg;
1777
1778 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
1779 DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
1780 if (matchIntrinsicType(Ty: Check.first, Infos&: Check.second, ArgTys, DeferredChecks,
1781 IsDeferredCheck: true))
1782 return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
1783 : MatchIntrinsicTypes_NoMatchArg;
1784 }
1785
1786 return MatchIntrinsicTypes_Match;
1787}
1788
1789bool
1790Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1791 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1792 // If there are no descriptors left, then it can't be a vararg.
1793 if (Infos.empty())
1794 return isVarArg;
1795
1796 // There should be only one descriptor remaining at this point.
1797 if (Infos.size() != 1)
1798 return true;
1799
1800 // Check and verify the descriptor.
1801 IITDescriptor D = Infos.front();
1802 Infos = Infos.slice(N: 1);
1803 if (D.Kind == IITDescriptor::VarArg)
1804 return !isVarArg;
1805
1806 return true;
1807}
1808
1809bool Intrinsic::getIntrinsicSignature(Intrinsic::ID ID, FunctionType *FT,
1810 SmallVectorImpl<Type *> &ArgTys) {
1811 if (!ID)
1812 return false;
1813
1814 SmallVector<Intrinsic::IITDescriptor, 8> Table;
1815 getIntrinsicInfoTableEntries(id: ID, T&: Table);
1816 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1817
1818 if (Intrinsic::matchIntrinsicSignature(FTy: FT, Infos&: TableRef, ArgTys) !=
1819 Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {
1820 return false;
1821 }
1822 if (Intrinsic::matchIntrinsicVarArg(isVarArg: FT->isVarArg(), Infos&: TableRef))
1823 return false;
1824 return true;
1825}
1826
1827bool Intrinsic::getIntrinsicSignature(Function *F,
1828 SmallVectorImpl<Type *> &ArgTys) {
1829 return getIntrinsicSignature(ID: F->getIntrinsicID(), FT: F->getFunctionType(),
1830 ArgTys);
1831}
1832
1833std::optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {
1834 SmallVector<Type *, 4> ArgTys;
1835 if (!getIntrinsicSignature(F, ArgTys))
1836 return std::nullopt;
1837
1838 Intrinsic::ID ID = F->getIntrinsicID();
1839 StringRef Name = F->getName();
1840 std::string WantedName =
1841 Intrinsic::getName(Id: ID, Tys: ArgTys, M: F->getParent(), FT: F->getFunctionType());
1842 if (Name == WantedName)
1843 return std::nullopt;
1844
1845 Function *NewDecl = [&] {
1846 if (auto *ExistingGV = F->getParent()->getNamedValue(Name: WantedName)) {
1847 if (auto *ExistingF = dyn_cast<Function>(Val: ExistingGV))
1848 if (ExistingF->getFunctionType() == F->getFunctionType())
1849 return ExistingF;
1850
1851 // The name already exists, but is not a function or has the wrong
1852 // prototype. Make place for the new one by renaming the old version.
1853 // Either this old version will be removed later on or the module is
1854 // invalid and we'll get an error.
1855 ExistingGV->setName(WantedName + ".renamed");
1856 }
1857 return Intrinsic::getDeclaration(M: F->getParent(), id: ID, Tys: ArgTys);
1858 }();
1859
1860 NewDecl->setCallingConv(F->getCallingConv());
1861 assert(NewDecl->getFunctionType() == F->getFunctionType() &&
1862 "Shouldn't change the signature");
1863 return NewDecl;
1864}
1865
1866/// hasAddressTaken - returns true if there are any uses of this function
1867/// other than direct calls or invokes to it. Optionally ignores callback
1868/// uses, assume like pointer annotation calls, and references in llvm.used
1869/// and llvm.compiler.used variables.
1870bool Function::hasAddressTaken(const User **PutOffender,
1871 bool IgnoreCallbackUses,
1872 bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed,
1873 bool IgnoreARCAttachedCall,
1874 bool IgnoreCastedDirectCall) const {
1875 for (const Use &U : uses()) {
1876 const User *FU = U.getUser();
1877 if (isa<BlockAddress>(Val: FU))
1878 continue;
1879
1880 if (IgnoreCallbackUses) {
1881 AbstractCallSite ACS(&U);
1882 if (ACS && ACS.isCallbackCall())
1883 continue;
1884 }
1885
1886 const auto *Call = dyn_cast<CallBase>(Val: FU);
1887 if (!Call) {
1888 if (IgnoreAssumeLikeCalls &&
1889 isa<BitCastOperator, AddrSpaceCastOperator>(Val: FU) &&
1890 all_of(Range: FU->users(), P: [](const User *U) {
1891 if (const auto *I = dyn_cast<IntrinsicInst>(Val: U))
1892 return I->isAssumeLikeIntrinsic();
1893 return false;
1894 })) {
1895 continue;
1896 }
1897
1898 if (IgnoreLLVMUsed && !FU->user_empty()) {
1899 const User *FUU = FU;
1900 if (isa<BitCastOperator, AddrSpaceCastOperator>(Val: FU) &&
1901 FU->hasOneUse() && !FU->user_begin()->user_empty())
1902 FUU = *FU->user_begin();
1903 if (llvm::all_of(Range: FUU->users(), P: [](const User *U) {
1904 if (const auto *GV = dyn_cast<GlobalVariable>(Val: U))
1905 return GV->hasName() &&
1906 (GV->getName() == "llvm.compiler.used" ||
1907 GV->getName() == "llvm.used");
1908 return false;
1909 }))
1910 continue;
1911 }
1912 if (PutOffender)
1913 *PutOffender = FU;
1914 return true;
1915 }
1916
1917 if (IgnoreAssumeLikeCalls) {
1918 if (const auto *I = dyn_cast<IntrinsicInst>(Val: Call))
1919 if (I->isAssumeLikeIntrinsic())
1920 continue;
1921 }
1922
1923 if (!Call->isCallee(U: &U) || (!IgnoreCastedDirectCall &&
1924 Call->getFunctionType() != getFunctionType())) {
1925 if (IgnoreARCAttachedCall &&
1926 Call->isOperandBundleOfType(ID: LLVMContext::OB_clang_arc_attachedcall,
1927 Idx: U.getOperandNo()))
1928 continue;
1929
1930 if (PutOffender)
1931 *PutOffender = FU;
1932 return true;
1933 }
1934 }
1935 return false;
1936}
1937
1938bool Function::isDefTriviallyDead() const {
1939 // Check the linkage
1940 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1941 !hasAvailableExternallyLinkage())
1942 return false;
1943
1944 // Check if the function is used by anything other than a blockaddress.
1945 for (const User *U : users())
1946 if (!isa<BlockAddress>(Val: U))
1947 return false;
1948
1949 return true;
1950}
1951
1952/// callsFunctionThatReturnsTwice - Return true if the function has a call to
1953/// setjmp or other function that gcc recognizes as "returning twice".
1954bool Function::callsFunctionThatReturnsTwice() const {
1955 for (const Instruction &I : instructions(F: this))
1956 if (const auto *Call = dyn_cast<CallBase>(Val: &I))
1957 if (Call->hasFnAttr(Kind: Attribute::ReturnsTwice))
1958 return true;
1959
1960 return false;
1961}
1962
1963Constant *Function::getPersonalityFn() const {
1964 assert(hasPersonalityFn() && getNumOperands());
1965 return cast<Constant>(Val: Op<0>());
1966}
1967
1968void Function::setPersonalityFn(Constant *Fn) {
1969 setHungoffOperand<0>(Fn);
1970 setValueSubclassDataBit(Bit: 3, On: Fn != nullptr);
1971}
1972
1973Constant *Function::getPrefixData() const {
1974 assert(hasPrefixData() && getNumOperands());
1975 return cast<Constant>(Val: Op<1>());
1976}
1977
1978void Function::setPrefixData(Constant *PrefixData) {
1979 setHungoffOperand<1>(PrefixData);
1980 setValueSubclassDataBit(Bit: 1, On: PrefixData != nullptr);
1981}
1982
1983Constant *Function::getPrologueData() const {
1984 assert(hasPrologueData() && getNumOperands());
1985 return cast<Constant>(Val: Op<2>());
1986}
1987
1988void Function::setPrologueData(Constant *PrologueData) {
1989 setHungoffOperand<2>(PrologueData);
1990 setValueSubclassDataBit(Bit: 2, On: PrologueData != nullptr);
1991}
1992
1993void Function::allocHungoffUselist() {
1994 // If we've already allocated a uselist, stop here.
1995 if (getNumOperands())
1996 return;
1997
1998 allocHungoffUses(N: 3, /*IsPhi=*/ false);
1999 setNumHungOffUseOperands(3);
2000
2001 // Initialize the uselist with placeholder operands to allow traversal.
2002 auto *CPN = ConstantPointerNull::get(T: PointerType::get(C&: getContext(), AddressSpace: 0));
2003 Op<0>().set(CPN);
2004 Op<1>().set(CPN);
2005 Op<2>().set(CPN);
2006}
2007
2008template <int Idx>
2009void Function::setHungoffOperand(Constant *C) {
2010 if (C) {
2011 allocHungoffUselist();
2012 Op<Idx>().set(C);
2013 } else if (getNumOperands()) {
2014 Op<Idx>().set(ConstantPointerNull::get(T: PointerType::get(C&: getContext(), AddressSpace: 0)));
2015 }
2016}
2017
2018void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
2019 assert(Bit < 16 && "SubclassData contains only 16 bits");
2020 if (On)
2021 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
2022 else
2023 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
2024}
2025
2026void Function::setEntryCount(ProfileCount Count,
2027 const DenseSet<GlobalValue::GUID> *S) {
2028#if !defined(NDEBUG)
2029 auto PrevCount = getEntryCount();
2030 assert(!PrevCount || PrevCount->getType() == Count.getType());
2031#endif
2032
2033 auto ImportGUIDs = getImportGUIDs();
2034 if (S == nullptr && ImportGUIDs.size())
2035 S = &ImportGUIDs;
2036
2037 MDBuilder MDB(getContext());
2038 setMetadata(
2039 KindID: LLVMContext::MD_prof,
2040 Node: MDB.createFunctionEntryCount(Count: Count.getCount(), Synthetic: Count.isSynthetic(), Imports: S));
2041}
2042
2043void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
2044 const DenseSet<GlobalValue::GUID> *Imports) {
2045 setEntryCount(Count: ProfileCount(Count, Type), S: Imports);
2046}
2047
2048std::optional<ProfileCount> Function::getEntryCount(bool AllowSynthetic) const {
2049 MDNode *MD = getMetadata(KindID: LLVMContext::MD_prof);
2050 if (MD && MD->getOperand(I: 0))
2051 if (MDString *MDS = dyn_cast<MDString>(Val: MD->getOperand(I: 0))) {
2052 if (MDS->getString() == "function_entry_count") {
2053 ConstantInt *CI = mdconst::extract<ConstantInt>(MD: MD->getOperand(I: 1));
2054 uint64_t Count = CI->getValue().getZExtValue();
2055 // A value of -1 is used for SamplePGO when there were no samples.
2056 // Treat this the same as unknown.
2057 if (Count == (uint64_t)-1)
2058 return std::nullopt;
2059 return ProfileCount(Count, PCT_Real);
2060 } else if (AllowSynthetic &&
2061 MDS->getString() == "synthetic_function_entry_count") {
2062 ConstantInt *CI = mdconst::extract<ConstantInt>(MD: MD->getOperand(I: 1));
2063 uint64_t Count = CI->getValue().getZExtValue();
2064 return ProfileCount(Count, PCT_Synthetic);
2065 }
2066 }
2067 return std::nullopt;
2068}
2069
2070DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
2071 DenseSet<GlobalValue::GUID> R;
2072 if (MDNode *MD = getMetadata(KindID: LLVMContext::MD_prof))
2073 if (MDString *MDS = dyn_cast<MDString>(Val: MD->getOperand(I: 0)))
2074 if (MDS->getString() == "function_entry_count")
2075 for (unsigned i = 2; i < MD->getNumOperands(); i++)
2076 R.insert(V: mdconst::extract<ConstantInt>(MD: MD->getOperand(I: i))
2077 ->getValue()
2078 .getZExtValue());
2079 return R;
2080}
2081
2082void Function::setSectionPrefix(StringRef Prefix) {
2083 MDBuilder MDB(getContext());
2084 setMetadata(KindID: LLVMContext::MD_section_prefix,
2085 Node: MDB.createFunctionSectionPrefix(Prefix));
2086}
2087
2088std::optional<StringRef> Function::getSectionPrefix() const {
2089 if (MDNode *MD = getMetadata(KindID: LLVMContext::MD_section_prefix)) {
2090 assert(cast<MDString>(MD->getOperand(0))->getString() ==
2091 "function_section_prefix" &&
2092 "Metadata not match");
2093 return cast<MDString>(Val: MD->getOperand(I: 1))->getString();
2094 }
2095 return std::nullopt;
2096}
2097
2098bool Function::nullPointerIsDefined() const {
2099 return hasFnAttribute(Kind: Attribute::NullPointerIsValid);
2100}
2101
2102bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
2103 if (F && F->nullPointerIsDefined())
2104 return true;
2105
2106 if (AS != 0)
2107 return true;
2108
2109 return false;
2110}
2111