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