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