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