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