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