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