xref: /llvm-project/llvm/lib/IR/Function.cpp (revision 7957fc6547e1b8af8e6586e2c25446b724eabb75)
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/Argument.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/InstIterator.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/MDBuilder.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/SymbolTableListTraits.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Use.h"
42 #include "llvm/IR/User.h"
43 #include "llvm/IR/Value.h"
44 #include "llvm/IR/ValueSymbolTable.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include <algorithm>
49 #include <cassert>
50 #include <cstddef>
51 #include <cstdint>
52 #include <cstring>
53 #include <string>
54 
55 using namespace llvm;
56 using ProfileCount = Function::ProfileCount;
57 
58 // Explicit instantiations of SymbolTableListTraits since some of the methods
59 // are not in the public header file...
60 template class llvm::SymbolTableListTraits<BasicBlock>;
61 
62 //===----------------------------------------------------------------------===//
63 // Argument Implementation
64 //===----------------------------------------------------------------------===//
65 
66 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
67     : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
68   setName(Name);
69 }
70 
71 void Argument::setParent(Function *parent) {
72   Parent = parent;
73 }
74 
75 bool Argument::hasNonNullAttr() const {
76   if (!getType()->isPointerTy()) return false;
77   if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull))
78     return true;
79   else if (getDereferenceableBytes() > 0 &&
80            !NullPointerIsDefined(getParent(),
81                                  getType()->getPointerAddressSpace()))
82     return true;
83   return false;
84 }
85 
86 bool Argument::hasByValAttr() const {
87   if (!getType()->isPointerTy()) return false;
88   return hasAttribute(Attribute::ByVal);
89 }
90 
91 bool Argument::hasSwiftSelfAttr() const {
92   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
93 }
94 
95 bool Argument::hasSwiftErrorAttr() const {
96   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
97 }
98 
99 bool Argument::hasInAllocaAttr() const {
100   if (!getType()->isPointerTy()) return false;
101   return hasAttribute(Attribute::InAlloca);
102 }
103 
104 bool Argument::hasByValOrInAllocaAttr() const {
105   if (!getType()->isPointerTy()) return false;
106   AttributeList Attrs = getParent()->getAttributes();
107   return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
108          Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca);
109 }
110 
111 unsigned Argument::getParamAlignment() const {
112   assert(getType()->isPointerTy() && "Only pointers have alignments");
113   return getParent()->getParamAlignment(getArgNo());
114 }
115 
116 Type *Argument::getParamByValType() const {
117   assert(getType()->isPointerTy() && "Only pointers have byval types");
118   return getParent()->getParamByValType(getArgNo());
119 }
120 
121 uint64_t Argument::getDereferenceableBytes() const {
122   assert(getType()->isPointerTy() &&
123          "Only pointers have dereferenceable bytes");
124   return getParent()->getParamDereferenceableBytes(getArgNo());
125 }
126 
127 uint64_t Argument::getDereferenceableOrNullBytes() const {
128   assert(getType()->isPointerTy() &&
129          "Only pointers have dereferenceable bytes");
130   return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
131 }
132 
133 bool Argument::hasNestAttr() const {
134   if (!getType()->isPointerTy()) return false;
135   return hasAttribute(Attribute::Nest);
136 }
137 
138 bool Argument::hasNoAliasAttr() const {
139   if (!getType()->isPointerTy()) return false;
140   return hasAttribute(Attribute::NoAlias);
141 }
142 
143 bool Argument::hasNoCaptureAttr() const {
144   if (!getType()->isPointerTy()) return false;
145   return hasAttribute(Attribute::NoCapture);
146 }
147 
148 bool Argument::hasStructRetAttr() const {
149   if (!getType()->isPointerTy()) return false;
150   return hasAttribute(Attribute::StructRet);
151 }
152 
153 bool Argument::hasInRegAttr() const {
154   return hasAttribute(Attribute::InReg);
155 }
156 
157 bool Argument::hasReturnedAttr() const {
158   return hasAttribute(Attribute::Returned);
159 }
160 
161 bool Argument::hasZExtAttr() const {
162   return hasAttribute(Attribute::ZExt);
163 }
164 
165 bool Argument::hasSExtAttr() const {
166   return hasAttribute(Attribute::SExt);
167 }
168 
169 bool Argument::onlyReadsMemory() const {
170   AttributeList Attrs = getParent()->getAttributes();
171   return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
172          Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
173 }
174 
175 void Argument::addAttrs(AttrBuilder &B) {
176   AttributeList AL = getParent()->getAttributes();
177   AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
178   getParent()->setAttributes(AL);
179 }
180 
181 void Argument::addAttr(Attribute::AttrKind Kind) {
182   getParent()->addParamAttr(getArgNo(), Kind);
183 }
184 
185 void Argument::addAttr(Attribute Attr) {
186   getParent()->addParamAttr(getArgNo(), Attr);
187 }
188 
189 void Argument::removeAttr(Attribute::AttrKind Kind) {
190   getParent()->removeParamAttr(getArgNo(), Kind);
191 }
192 
193 bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
194   return getParent()->hasParamAttribute(getArgNo(), Kind);
195 }
196 
197 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
198   return getParent()->getParamAttribute(getArgNo(), Kind);
199 }
200 
201 //===----------------------------------------------------------------------===//
202 // Helper Methods in Function
203 //===----------------------------------------------------------------------===//
204 
205 LLVMContext &Function::getContext() const {
206   return getType()->getContext();
207 }
208 
209 unsigned Function::getInstructionCount() const {
210   unsigned NumInstrs = 0;
211   for (const BasicBlock &BB : BasicBlocks)
212     NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
213                                BB.instructionsWithoutDebug().end());
214   return NumInstrs;
215 }
216 
217 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
218                            const Twine &N, Module &M) {
219   return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
220 }
221 
222 void Function::removeFromParent() {
223   getParent()->getFunctionList().remove(getIterator());
224 }
225 
226 void Function::eraseFromParent() {
227   getParent()->getFunctionList().erase(getIterator());
228 }
229 
230 //===----------------------------------------------------------------------===//
231 // Function Implementation
232 //===----------------------------------------------------------------------===//
233 
234 static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
235   // If AS == -1 and we are passed a valid module pointer we place the function
236   // in the program address space. Otherwise we default to AS0.
237   if (AddrSpace == static_cast<unsigned>(-1))
238     return M ? M->getDataLayout().getProgramAddressSpace() : 0;
239   return AddrSpace;
240 }
241 
242 Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
243                    const Twine &name, Module *ParentModule)
244     : GlobalObject(Ty, Value::FunctionVal,
245                    OperandTraits<Function>::op_begin(this), 0, Linkage, name,
246                    computeAddrSpace(AddrSpace, ParentModule)),
247       NumArgs(Ty->getNumParams()) {
248   assert(FunctionType::isValidReturnType(getReturnType()) &&
249          "invalid return type");
250   setGlobalObjectSubClassData(0);
251 
252   // We only need a symbol table for a function if the context keeps value names
253   if (!getContext().shouldDiscardValueNames())
254     SymTab = make_unique<ValueSymbolTable>();
255 
256   // If the function has arguments, mark them as lazily built.
257   if (Ty->getNumParams())
258     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
259 
260   if (ParentModule)
261     ParentModule->getFunctionList().push_back(this);
262 
263   HasLLVMReservedName = getName().startswith("llvm.");
264   // Ensure intrinsics have the right parameter attributes.
265   // Note, the IntID field will have been set in Value::setName if this function
266   // name is a valid intrinsic ID.
267   if (IntID)
268     setAttributes(Intrinsic::getAttributes(getContext(), IntID));
269 }
270 
271 Function::~Function() {
272   dropAllReferences();    // After this it is safe to delete instructions.
273 
274   // Delete all of the method arguments and unlink from symbol table...
275   if (Arguments)
276     clearArguments();
277 
278   // Remove the function from the on-the-side GC table.
279   clearGC();
280 }
281 
282 void Function::BuildLazyArguments() const {
283   // Create the arguments vector, all arguments start out unnamed.
284   auto *FT = getFunctionType();
285   if (NumArgs > 0) {
286     Arguments = std::allocator<Argument>().allocate(NumArgs);
287     for (unsigned i = 0, e = NumArgs; i != e; ++i) {
288       Type *ArgTy = FT->getParamType(i);
289       assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
290       new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
291     }
292   }
293 
294   // Clear the lazy arguments bit.
295   unsigned SDC = getSubclassDataFromValue();
296   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
297   assert(!hasLazyArguments());
298 }
299 
300 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
301   return MutableArrayRef<Argument>(Args, Count);
302 }
303 
304 void Function::clearArguments() {
305   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
306     A.setName("");
307     A.~Argument();
308   }
309   std::allocator<Argument>().deallocate(Arguments, NumArgs);
310   Arguments = nullptr;
311 }
312 
313 void Function::stealArgumentListFrom(Function &Src) {
314   assert(isDeclaration() && "Expected no references to current arguments");
315 
316   // Drop the current arguments, if any, and set the lazy argument bit.
317   if (!hasLazyArguments()) {
318     assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
319                         [](const Argument &A) { return A.use_empty(); }) &&
320            "Expected arguments to be unused in declaration");
321     clearArguments();
322     setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
323   }
324 
325   // Nothing to steal if Src has lazy arguments.
326   if (Src.hasLazyArguments())
327     return;
328 
329   // Steal arguments from Src, and fix the lazy argument bits.
330   assert(arg_size() == Src.arg_size());
331   Arguments = Src.Arguments;
332   Src.Arguments = nullptr;
333   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
334     // FIXME: This does the work of transferNodesFromList inefficiently.
335     SmallString<128> Name;
336     if (A.hasName())
337       Name = A.getName();
338     if (!Name.empty())
339       A.setName("");
340     A.setParent(this);
341     if (!Name.empty())
342       A.setName(Name);
343   }
344 
345   setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
346   assert(!hasLazyArguments());
347   Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
348 }
349 
350 // dropAllReferences() - This function causes all the subinstructions to "let
351 // go" of all references that they are maintaining.  This allows one to
352 // 'delete' a whole class at a time, even though there may be circular
353 // references... first all references are dropped, and all use counts go to
354 // zero.  Then everything is deleted for real.  Note that no operations are
355 // valid on an object that has "dropped all references", except operator
356 // delete.
357 //
358 void Function::dropAllReferences() {
359   setIsMaterializable(false);
360 
361   for (BasicBlock &BB : *this)
362     BB.dropAllReferences();
363 
364   // Delete all basic blocks. They are now unused, except possibly by
365   // blockaddresses, but BasicBlock's destructor takes care of those.
366   while (!BasicBlocks.empty())
367     BasicBlocks.begin()->eraseFromParent();
368 
369   // Drop uses of any optional data (real or placeholder).
370   if (getNumOperands()) {
371     User::dropAllReferences();
372     setNumHungOffUseOperands(0);
373     setValueSubclassData(getSubclassDataFromValue() & ~0xe);
374   }
375 
376   // Metadata is stored in a side-table.
377   clearMetadata();
378 }
379 
380 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
381   AttributeList PAL = getAttributes();
382   PAL = PAL.addAttribute(getContext(), i, Kind);
383   setAttributes(PAL);
384 }
385 
386 void Function::addAttribute(unsigned i, Attribute Attr) {
387   AttributeList PAL = getAttributes();
388   PAL = PAL.addAttribute(getContext(), i, Attr);
389   setAttributes(PAL);
390 }
391 
392 void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
393   AttributeList PAL = getAttributes();
394   PAL = PAL.addAttributes(getContext(), i, Attrs);
395   setAttributes(PAL);
396 }
397 
398 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
399   AttributeList PAL = getAttributes();
400   PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
401   setAttributes(PAL);
402 }
403 
404 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
405   AttributeList PAL = getAttributes();
406   PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
407   setAttributes(PAL);
408 }
409 
410 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
411   AttributeList PAL = getAttributes();
412   PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs);
413   setAttributes(PAL);
414 }
415 
416 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
417   AttributeList PAL = getAttributes();
418   PAL = PAL.removeAttribute(getContext(), i, Kind);
419   setAttributes(PAL);
420 }
421 
422 void Function::removeAttribute(unsigned i, StringRef Kind) {
423   AttributeList PAL = getAttributes();
424   PAL = PAL.removeAttribute(getContext(), i, Kind);
425   setAttributes(PAL);
426 }
427 
428 void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
429   AttributeList PAL = getAttributes();
430   PAL = PAL.removeAttributes(getContext(), i, Attrs);
431   setAttributes(PAL);
432 }
433 
434 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
435   AttributeList PAL = getAttributes();
436   PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
437   setAttributes(PAL);
438 }
439 
440 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
441   AttributeList PAL = getAttributes();
442   PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
443   setAttributes(PAL);
444 }
445 
446 void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
447   AttributeList PAL = getAttributes();
448   PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs);
449   setAttributes(PAL);
450 }
451 
452 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
453   AttributeList PAL = getAttributes();
454   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
455   setAttributes(PAL);
456 }
457 
458 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
459   AttributeList PAL = getAttributes();
460   PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
461   setAttributes(PAL);
462 }
463 
464 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
465   AttributeList PAL = getAttributes();
466   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
467   setAttributes(PAL);
468 }
469 
470 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
471                                                  uint64_t Bytes) {
472   AttributeList PAL = getAttributes();
473   PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes);
474   setAttributes(PAL);
475 }
476 
477 const std::string &Function::getGC() const {
478   assert(hasGC() && "Function has no collector");
479   return getContext().getGC(*this);
480 }
481 
482 void Function::setGC(std::string Str) {
483   setValueSubclassDataBit(14, !Str.empty());
484   getContext().setGC(*this, std::move(Str));
485 }
486 
487 void Function::clearGC() {
488   if (!hasGC())
489     return;
490   getContext().deleteGC(*this);
491   setValueSubclassDataBit(14, false);
492 }
493 
494 /// Copy all additional attributes (those not needed to create a Function) from
495 /// the Function Src to this one.
496 void Function::copyAttributesFrom(const Function *Src) {
497   GlobalObject::copyAttributesFrom(Src);
498   setCallingConv(Src->getCallingConv());
499   setAttributes(Src->getAttributes());
500   if (Src->hasGC())
501     setGC(Src->getGC());
502   else
503     clearGC();
504   if (Src->hasPersonalityFn())
505     setPersonalityFn(Src->getPersonalityFn());
506   if (Src->hasPrefixData())
507     setPrefixData(Src->getPrefixData());
508   if (Src->hasPrologueData())
509     setPrologueData(Src->getPrologueData());
510 }
511 
512 /// Table of string intrinsic names indexed by enum value.
513 static const char * const IntrinsicNameTable[] = {
514   "not_intrinsic",
515 #define GET_INTRINSIC_NAME_TABLE
516 #include "llvm/IR/IntrinsicImpl.inc"
517 #undef GET_INTRINSIC_NAME_TABLE
518 };
519 
520 /// Table of per-target intrinsic name tables.
521 #define GET_INTRINSIC_TARGET_DATA
522 #include "llvm/IR/IntrinsicImpl.inc"
523 #undef GET_INTRINSIC_TARGET_DATA
524 
525 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
526 /// target as \c Name, or the generic table if \c Name is not target specific.
527 ///
528 /// Returns the relevant slice of \c IntrinsicNameTable
529 static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
530   assert(Name.startswith("llvm."));
531 
532   ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
533   // Drop "llvm." and take the first dotted component. That will be the target
534   // if this is target specific.
535   StringRef Target = Name.drop_front(5).split('.').first;
536   auto It = std::lower_bound(Targets.begin(), Targets.end(), Target,
537                              [](const IntrinsicTargetInfo &TI,
538                                 StringRef Target) { return TI.Name < Target; });
539   // We've either found the target or just fall back to the generic set, which
540   // is always first.
541   const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
542   return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
543 }
544 
545 /// This does the actual lookup of an intrinsic ID which
546 /// matches the given function name.
547 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
548   ArrayRef<const char *> NameTable = findTargetSubtable(Name);
549   int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
550   if (Idx == -1)
551     return Intrinsic::not_intrinsic;
552 
553   // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
554   // an index into a sub-table.
555   int Adjust = NameTable.data() - IntrinsicNameTable;
556   Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
557 
558   // If the intrinsic is not overloaded, require an exact match. If it is
559   // overloaded, require either exact or prefix match.
560   const auto MatchSize = strlen(NameTable[Idx]);
561   assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
562   bool IsExactMatch = Name.size() == MatchSize;
563   return IsExactMatch || isOverloaded(ID) ? ID : Intrinsic::not_intrinsic;
564 }
565 
566 void Function::recalculateIntrinsicID() {
567   StringRef Name = getName();
568   if (!Name.startswith("llvm.")) {
569     HasLLVMReservedName = false;
570     IntID = Intrinsic::not_intrinsic;
571     return;
572   }
573   HasLLVMReservedName = true;
574   IntID = lookupIntrinsicID(Name);
575 }
576 
577 /// Returns a stable mangling for the type specified for use in the name
578 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
579 /// of named types is simply their name.  Manglings for unnamed types consist
580 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
581 /// combined with the mangling of their component types.  A vararg function
582 /// type will have a suffix of 'vararg'.  Since function types can contain
583 /// other function types, we close a function type mangling with suffix 'f'
584 /// which can't be confused with it's prefix.  This ensures we don't have
585 /// collisions between two unrelated function types. Otherwise, you might
586 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
587 ///
588 static std::string getMangledTypeStr(Type* Ty) {
589   std::string Result;
590   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
591     Result += "p" + utostr(PTyp->getAddressSpace()) +
592       getMangledTypeStr(PTyp->getElementType());
593   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
594     Result += "a" + utostr(ATyp->getNumElements()) +
595       getMangledTypeStr(ATyp->getElementType());
596   } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
597     if (!STyp->isLiteral()) {
598       Result += "s_";
599       Result += STyp->getName();
600     } else {
601       Result += "sl_";
602       for (auto Elem : STyp->elements())
603         Result += getMangledTypeStr(Elem);
604     }
605     // Ensure nested structs are distinguishable.
606     Result += "s";
607   } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
608     Result += "f_" + getMangledTypeStr(FT->getReturnType());
609     for (size_t i = 0; i < FT->getNumParams(); i++)
610       Result += getMangledTypeStr(FT->getParamType(i));
611     if (FT->isVarArg())
612       Result += "vararg";
613     // Ensure nested function types are distinguishable.
614     Result += "f";
615   } else if (isa<VectorType>(Ty)) {
616     Result += "v" + utostr(Ty->getVectorNumElements()) +
617       getMangledTypeStr(Ty->getVectorElementType());
618   } else if (Ty) {
619     switch (Ty->getTypeID()) {
620     default: llvm_unreachable("Unhandled type");
621     case Type::VoidTyID:      Result += "isVoid";   break;
622     case Type::MetadataTyID:  Result += "Metadata"; break;
623     case Type::HalfTyID:      Result += "f16";      break;
624     case Type::FloatTyID:     Result += "f32";      break;
625     case Type::DoubleTyID:    Result += "f64";      break;
626     case Type::X86_FP80TyID:  Result += "f80";      break;
627     case Type::FP128TyID:     Result += "f128";     break;
628     case Type::PPC_FP128TyID: Result += "ppcf128";  break;
629     case Type::X86_MMXTyID:   Result += "x86mmx";   break;
630     case Type::IntegerTyID:
631       Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
632       break;
633     }
634   }
635   return Result;
636 }
637 
638 StringRef Intrinsic::getName(ID id) {
639   assert(id < num_intrinsics && "Invalid intrinsic ID!");
640   assert(!isOverloaded(id) &&
641          "This version of getName does not support overloading");
642   return IntrinsicNameTable[id];
643 }
644 
645 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
646   assert(id < num_intrinsics && "Invalid intrinsic ID!");
647   std::string Result(IntrinsicNameTable[id]);
648   for (Type *Ty : Tys) {
649     Result += "." + getMangledTypeStr(Ty);
650   }
651   return Result;
652 }
653 
654 /// IIT_Info - These are enumerators that describe the entries returned by the
655 /// getIntrinsicInfoTableEntries function.
656 ///
657 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
658 enum IIT_Info {
659   // Common values should be encoded with 0-15.
660   IIT_Done = 0,
661   IIT_I1   = 1,
662   IIT_I8   = 2,
663   IIT_I16  = 3,
664   IIT_I32  = 4,
665   IIT_I64  = 5,
666   IIT_F16  = 6,
667   IIT_F32  = 7,
668   IIT_F64  = 8,
669   IIT_V2   = 9,
670   IIT_V4   = 10,
671   IIT_V8   = 11,
672   IIT_V16  = 12,
673   IIT_V32  = 13,
674   IIT_PTR  = 14,
675   IIT_ARG  = 15,
676 
677   // Values from 16+ are only encodable with the inefficient encoding.
678   IIT_V64  = 16,
679   IIT_MMX  = 17,
680   IIT_TOKEN = 18,
681   IIT_METADATA = 19,
682   IIT_EMPTYSTRUCT = 20,
683   IIT_STRUCT2 = 21,
684   IIT_STRUCT3 = 22,
685   IIT_STRUCT4 = 23,
686   IIT_STRUCT5 = 24,
687   IIT_EXTEND_ARG = 25,
688   IIT_TRUNC_ARG = 26,
689   IIT_ANYPTR = 27,
690   IIT_V1   = 28,
691   IIT_VARARG = 29,
692   IIT_HALF_VEC_ARG = 30,
693   IIT_SAME_VEC_WIDTH_ARG = 31,
694   IIT_PTR_TO_ARG = 32,
695   IIT_PTR_TO_ELT = 33,
696   IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
697   IIT_I128 = 35,
698   IIT_V512 = 36,
699   IIT_V1024 = 37,
700   IIT_STRUCT6 = 38,
701   IIT_STRUCT7 = 39,
702   IIT_STRUCT8 = 40,
703   IIT_F128 = 41
704 };
705 
706 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
707                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
708   using namespace Intrinsic;
709 
710   IIT_Info Info = IIT_Info(Infos[NextElt++]);
711   unsigned StructElts = 2;
712 
713   switch (Info) {
714   case IIT_Done:
715     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
716     return;
717   case IIT_VARARG:
718     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
719     return;
720   case IIT_MMX:
721     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
722     return;
723   case IIT_TOKEN:
724     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
725     return;
726   case IIT_METADATA:
727     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
728     return;
729   case IIT_F16:
730     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
731     return;
732   case IIT_F32:
733     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
734     return;
735   case IIT_F64:
736     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
737     return;
738   case IIT_F128:
739     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
740     return;
741   case IIT_I1:
742     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
743     return;
744   case IIT_I8:
745     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
746     return;
747   case IIT_I16:
748     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
749     return;
750   case IIT_I32:
751     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
752     return;
753   case IIT_I64:
754     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
755     return;
756   case IIT_I128:
757     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
758     return;
759   case IIT_V1:
760     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
761     DecodeIITType(NextElt, Infos, OutputTable);
762     return;
763   case IIT_V2:
764     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
765     DecodeIITType(NextElt, Infos, OutputTable);
766     return;
767   case IIT_V4:
768     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
769     DecodeIITType(NextElt, Infos, OutputTable);
770     return;
771   case IIT_V8:
772     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
773     DecodeIITType(NextElt, Infos, OutputTable);
774     return;
775   case IIT_V16:
776     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
777     DecodeIITType(NextElt, Infos, OutputTable);
778     return;
779   case IIT_V32:
780     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
781     DecodeIITType(NextElt, Infos, OutputTable);
782     return;
783   case IIT_V64:
784     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
785     DecodeIITType(NextElt, Infos, OutputTable);
786     return;
787   case IIT_V512:
788     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
789     DecodeIITType(NextElt, Infos, OutputTable);
790     return;
791   case IIT_V1024:
792     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
793     DecodeIITType(NextElt, Infos, OutputTable);
794     return;
795   case IIT_PTR:
796     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
797     DecodeIITType(NextElt, Infos, OutputTable);
798     return;
799   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
800     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
801                                              Infos[NextElt++]));
802     DecodeIITType(NextElt, Infos, OutputTable);
803     return;
804   }
805   case IIT_ARG: {
806     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
807     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
808     return;
809   }
810   case IIT_EXTEND_ARG: {
811     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
812     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
813                                              ArgInfo));
814     return;
815   }
816   case IIT_TRUNC_ARG: {
817     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
818     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
819                                              ArgInfo));
820     return;
821   }
822   case IIT_HALF_VEC_ARG: {
823     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
824     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
825                                              ArgInfo));
826     return;
827   }
828   case IIT_SAME_VEC_WIDTH_ARG: {
829     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
830     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
831                                              ArgInfo));
832     return;
833   }
834   case IIT_PTR_TO_ARG: {
835     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
836     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
837                                              ArgInfo));
838     return;
839   }
840   case IIT_PTR_TO_ELT: {
841     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
842     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
843     return;
844   }
845   case IIT_VEC_OF_ANYPTRS_TO_ELT: {
846     unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
847     unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
848     OutputTable.push_back(
849         IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
850     return;
851   }
852   case IIT_EMPTYSTRUCT:
853     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
854     return;
855   case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
856   case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
857   case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
858   case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
859   case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
860   case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
861   case IIT_STRUCT2: {
862     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
863 
864     for (unsigned i = 0; i != StructElts; ++i)
865       DecodeIITType(NextElt, Infos, OutputTable);
866     return;
867   }
868   }
869   llvm_unreachable("unhandled");
870 }
871 
872 #define GET_INTRINSIC_GENERATOR_GLOBAL
873 #include "llvm/IR/IntrinsicImpl.inc"
874 #undef GET_INTRINSIC_GENERATOR_GLOBAL
875 
876 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
877                                              SmallVectorImpl<IITDescriptor> &T){
878   // Check to see if the intrinsic's type was expressible by the table.
879   unsigned TableVal = IIT_Table[id-1];
880 
881   // Decode the TableVal into an array of IITValues.
882   SmallVector<unsigned char, 8> IITValues;
883   ArrayRef<unsigned char> IITEntries;
884   unsigned NextElt = 0;
885   if ((TableVal >> 31) != 0) {
886     // This is an offset into the IIT_LongEncodingTable.
887     IITEntries = IIT_LongEncodingTable;
888 
889     // Strip sentinel bit.
890     NextElt = (TableVal << 1) >> 1;
891   } else {
892     // Decode the TableVal into an array of IITValues.  If the entry was encoded
893     // into a single word in the table itself, decode it now.
894     do {
895       IITValues.push_back(TableVal & 0xF);
896       TableVal >>= 4;
897     } while (TableVal);
898 
899     IITEntries = IITValues;
900     NextElt = 0;
901   }
902 
903   // Okay, decode the table into the output vector of IITDescriptors.
904   DecodeIITType(NextElt, IITEntries, T);
905   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
906     DecodeIITType(NextElt, IITEntries, T);
907 }
908 
909 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
910                              ArrayRef<Type*> Tys, LLVMContext &Context) {
911   using namespace Intrinsic;
912 
913   IITDescriptor D = Infos.front();
914   Infos = Infos.slice(1);
915 
916   switch (D.Kind) {
917   case IITDescriptor::Void: return Type::getVoidTy(Context);
918   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
919   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
920   case IITDescriptor::Token: return Type::getTokenTy(Context);
921   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
922   case IITDescriptor::Half: return Type::getHalfTy(Context);
923   case IITDescriptor::Float: return Type::getFloatTy(Context);
924   case IITDescriptor::Double: return Type::getDoubleTy(Context);
925   case IITDescriptor::Quad: return Type::getFP128Ty(Context);
926 
927   case IITDescriptor::Integer:
928     return IntegerType::get(Context, D.Integer_Width);
929   case IITDescriptor::Vector:
930     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
931   case IITDescriptor::Pointer:
932     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
933                             D.Pointer_AddressSpace);
934   case IITDescriptor::Struct: {
935     SmallVector<Type *, 8> Elts;
936     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
937       Elts.push_back(DecodeFixedType(Infos, Tys, Context));
938     return StructType::get(Context, Elts);
939   }
940   case IITDescriptor::Argument:
941     return Tys[D.getArgumentNumber()];
942   case IITDescriptor::ExtendArgument: {
943     Type *Ty = Tys[D.getArgumentNumber()];
944     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
945       return VectorType::getExtendedElementVectorType(VTy);
946 
947     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
948   }
949   case IITDescriptor::TruncArgument: {
950     Type *Ty = Tys[D.getArgumentNumber()];
951     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
952       return VectorType::getTruncatedElementVectorType(VTy);
953 
954     IntegerType *ITy = cast<IntegerType>(Ty);
955     assert(ITy->getBitWidth() % 2 == 0);
956     return IntegerType::get(Context, ITy->getBitWidth() / 2);
957   }
958   case IITDescriptor::HalfVecArgument:
959     return VectorType::getHalfElementsVectorType(cast<VectorType>(
960                                                   Tys[D.getArgumentNumber()]));
961   case IITDescriptor::SameVecWidthArgument: {
962     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
963     Type *Ty = Tys[D.getArgumentNumber()];
964     if (auto *VTy = dyn_cast<VectorType>(Ty))
965       return VectorType::get(EltTy, VTy->getNumElements());
966     return EltTy;
967   }
968   case IITDescriptor::PtrToArgument: {
969     Type *Ty = Tys[D.getArgumentNumber()];
970     return PointerType::getUnqual(Ty);
971   }
972   case IITDescriptor::PtrToElt: {
973     Type *Ty = Tys[D.getArgumentNumber()];
974     VectorType *VTy = dyn_cast<VectorType>(Ty);
975     if (!VTy)
976       llvm_unreachable("Expected an argument of Vector Type");
977     Type *EltTy = VTy->getVectorElementType();
978     return PointerType::getUnqual(EltTy);
979   }
980   case IITDescriptor::VecOfAnyPtrsToElt:
981     // Return the overloaded type (which determines the pointers address space)
982     return Tys[D.getOverloadArgNumber()];
983   }
984   llvm_unreachable("unhandled");
985 }
986 
987 FunctionType *Intrinsic::getType(LLVMContext &Context,
988                                  ID id, ArrayRef<Type*> Tys) {
989   SmallVector<IITDescriptor, 8> Table;
990   getIntrinsicInfoTableEntries(id, Table);
991 
992   ArrayRef<IITDescriptor> TableRef = Table;
993   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
994 
995   SmallVector<Type*, 8> ArgTys;
996   while (!TableRef.empty())
997     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
998 
999   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
1000   // If we see void type as the type of the last argument, it is vararg intrinsic
1001   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
1002     ArgTys.pop_back();
1003     return FunctionType::get(ResultTy, ArgTys, true);
1004   }
1005   return FunctionType::get(ResultTy, ArgTys, false);
1006 }
1007 
1008 bool Intrinsic::isOverloaded(ID id) {
1009 #define GET_INTRINSIC_OVERLOAD_TABLE
1010 #include "llvm/IR/IntrinsicImpl.inc"
1011 #undef GET_INTRINSIC_OVERLOAD_TABLE
1012 }
1013 
1014 bool Intrinsic::isLeaf(ID id) {
1015   switch (id) {
1016   default:
1017     return true;
1018 
1019   case Intrinsic::experimental_gc_statepoint:
1020   case Intrinsic::experimental_patchpoint_void:
1021   case Intrinsic::experimental_patchpoint_i64:
1022     return false;
1023   }
1024 }
1025 
1026 /// This defines the "Intrinsic::getAttributes(ID id)" method.
1027 #define GET_INTRINSIC_ATTRIBUTES
1028 #include "llvm/IR/IntrinsicImpl.inc"
1029 #undef GET_INTRINSIC_ATTRIBUTES
1030 
1031 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
1032   // There can never be multiple globals with the same name of different types,
1033   // because intrinsics must be a specific type.
1034   return cast<Function>(
1035       M->getOrInsertFunction(getName(id, Tys),
1036                              getType(M->getContext(), id, Tys))
1037           .getCallee());
1038 }
1039 
1040 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
1041 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1042 #include "llvm/IR/IntrinsicImpl.inc"
1043 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1044 
1045 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
1046 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1047 #include "llvm/IR/IntrinsicImpl.inc"
1048 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1049 
1050 using DeferredIntrinsicMatchPair =
1051     std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
1052 
1053 static bool matchIntrinsicType(
1054     Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
1055     SmallVectorImpl<Type *> &ArgTys,
1056     SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
1057     bool IsDeferredCheck) {
1058   using namespace Intrinsic;
1059 
1060   // If we ran out of descriptors, there are too many arguments.
1061   if (Infos.empty()) return true;
1062 
1063   // Do this before slicing off the 'front' part
1064   auto InfosRef = Infos;
1065   auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
1066     DeferredChecks.emplace_back(T, InfosRef);
1067     return false;
1068   };
1069 
1070   IITDescriptor D = Infos.front();
1071   Infos = Infos.slice(1);
1072 
1073   switch (D.Kind) {
1074     case IITDescriptor::Void: return !Ty->isVoidTy();
1075     case IITDescriptor::VarArg: return true;
1076     case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
1077     case IITDescriptor::Token: return !Ty->isTokenTy();
1078     case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1079     case IITDescriptor::Half: return !Ty->isHalfTy();
1080     case IITDescriptor::Float: return !Ty->isFloatTy();
1081     case IITDescriptor::Double: return !Ty->isDoubleTy();
1082     case IITDescriptor::Quad: return !Ty->isFP128Ty();
1083     case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1084     case IITDescriptor::Vector: {
1085       VectorType *VT = dyn_cast<VectorType>(Ty);
1086       return !VT || VT->getNumElements() != D.Vector_Width ||
1087              matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
1088                                 DeferredChecks, IsDeferredCheck);
1089     }
1090     case IITDescriptor::Pointer: {
1091       PointerType *PT = dyn_cast<PointerType>(Ty);
1092       return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1093              matchIntrinsicType(PT->getElementType(), Infos, ArgTys,
1094                                 DeferredChecks, IsDeferredCheck);
1095     }
1096 
1097     case IITDescriptor::Struct: {
1098       StructType *ST = dyn_cast<StructType>(Ty);
1099       if (!ST || ST->getNumElements() != D.Struct_NumElements)
1100         return true;
1101 
1102       for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1103         if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
1104                                DeferredChecks, IsDeferredCheck))
1105           return true;
1106       return false;
1107     }
1108 
1109     case IITDescriptor::Argument:
1110       // If this is the second occurrence of an argument,
1111       // verify that the later instance matches the previous instance.
1112       if (D.getArgumentNumber() < ArgTys.size())
1113         return Ty != ArgTys[D.getArgumentNumber()];
1114 
1115       if (D.getArgumentNumber() > ArgTys.size() ||
1116           D.getArgumentKind() == IITDescriptor::AK_MatchType)
1117         return IsDeferredCheck || DeferCheck(Ty);
1118 
1119       assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
1120              "Table consistency error");
1121       ArgTys.push_back(Ty);
1122 
1123       switch (D.getArgumentKind()) {
1124         case IITDescriptor::AK_Any:        return false; // Success
1125         case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1126         case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
1127         case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
1128         case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1129         default:                           break;
1130       }
1131       llvm_unreachable("all argument kinds not covered");
1132 
1133     case IITDescriptor::ExtendArgument: {
1134       // If this is a forward reference, defer the check for later.
1135       if (D.getArgumentNumber() >= ArgTys.size())
1136         return IsDeferredCheck || DeferCheck(Ty);
1137 
1138       Type *NewTy = ArgTys[D.getArgumentNumber()];
1139       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1140         NewTy = VectorType::getExtendedElementVectorType(VTy);
1141       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1142         NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
1143       else
1144         return true;
1145 
1146       return Ty != NewTy;
1147     }
1148     case IITDescriptor::TruncArgument: {
1149       // If this is a forward reference, defer the check for later.
1150       if (D.getArgumentNumber() >= ArgTys.size())
1151         return IsDeferredCheck || DeferCheck(Ty);
1152 
1153       Type *NewTy = ArgTys[D.getArgumentNumber()];
1154       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1155         NewTy = VectorType::getTruncatedElementVectorType(VTy);
1156       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1157         NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
1158       else
1159         return true;
1160 
1161       return Ty != NewTy;
1162     }
1163     case IITDescriptor::HalfVecArgument:
1164       // If this is a forward reference, defer the check for later.
1165       return D.getArgumentNumber() >= ArgTys.size() ||
1166              !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1167              VectorType::getHalfElementsVectorType(
1168                      cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1169     case IITDescriptor::SameVecWidthArgument: {
1170       if (D.getArgumentNumber() >= ArgTys.size()) {
1171         // Defer check and subsequent check for the vector element type.
1172         Infos = Infos.slice(1);
1173         return IsDeferredCheck || DeferCheck(Ty);
1174       }
1175       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1176       auto *ThisArgType = dyn_cast<VectorType>(Ty);
1177       // Both must be vectors of the same number of elements or neither.
1178       if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
1179         return true;
1180       Type *EltTy = Ty;
1181       if (ThisArgType) {
1182         if (ReferenceType->getVectorNumElements() !=
1183             ThisArgType->getVectorNumElements())
1184           return true;
1185         EltTy = ThisArgType->getVectorElementType();
1186       }
1187       return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
1188                                 IsDeferredCheck);
1189     }
1190     case IITDescriptor::PtrToArgument: {
1191       if (D.getArgumentNumber() >= ArgTys.size())
1192         return IsDeferredCheck || DeferCheck(Ty);
1193       Type * ReferenceType = ArgTys[D.getArgumentNumber()];
1194       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1195       return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
1196     }
1197     case IITDescriptor::PtrToElt: {
1198       if (D.getArgumentNumber() >= ArgTys.size())
1199         return IsDeferredCheck || DeferCheck(Ty);
1200       VectorType * ReferenceType =
1201         dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
1202       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1203 
1204       return (!ThisArgType || !ReferenceType ||
1205               ThisArgType->getElementType() != ReferenceType->getElementType());
1206     }
1207     case IITDescriptor::VecOfAnyPtrsToElt: {
1208       unsigned RefArgNumber = D.getRefArgNumber();
1209       if (RefArgNumber >= ArgTys.size()) {
1210         if (IsDeferredCheck)
1211           return true;
1212         // If forward referencing, already add the pointer-vector type and
1213         // defer the checks for later.
1214         ArgTys.push_back(Ty);
1215         return DeferCheck(Ty);
1216       }
1217 
1218       if (!IsDeferredCheck){
1219         assert(D.getOverloadArgNumber() == ArgTys.size() &&
1220                "Table consistency error");
1221         ArgTys.push_back(Ty);
1222       }
1223 
1224       // Verify the overloaded type "matches" the Ref type.
1225       // i.e. Ty is a vector with the same width as Ref.
1226       // Composed of pointers to the same element type as Ref.
1227       VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
1228       VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1229       if (!ThisArgVecTy || !ReferenceType ||
1230           (ReferenceType->getVectorNumElements() !=
1231            ThisArgVecTy->getVectorNumElements()))
1232         return true;
1233       PointerType *ThisArgEltTy =
1234               dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
1235       if (!ThisArgEltTy)
1236         return true;
1237       return ThisArgEltTy->getElementType() !=
1238              ReferenceType->getVectorElementType();
1239     }
1240   }
1241   llvm_unreachable("unhandled");
1242 }
1243 
1244 Intrinsic::MatchIntrinsicTypesResult
1245 Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
1246                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
1247                                    SmallVectorImpl<Type *> &ArgTys) {
1248   SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
1249   if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
1250                          false))
1251     return MatchIntrinsicTypes_NoMatchRet;
1252 
1253   unsigned NumDeferredReturnChecks = DeferredChecks.size();
1254 
1255   for (auto Ty : FTy->params())
1256     if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
1257       return MatchIntrinsicTypes_NoMatchArg;
1258 
1259   for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
1260     DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
1261     if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
1262                            true))
1263       return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
1264                                          : MatchIntrinsicTypes_NoMatchArg;
1265   }
1266 
1267   return MatchIntrinsicTypes_Match;
1268 }
1269 
1270 bool
1271 Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1272                                 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1273   // If there are no descriptors left, then it can't be a vararg.
1274   if (Infos.empty())
1275     return isVarArg;
1276 
1277   // There should be only one descriptor remaining at this point.
1278   if (Infos.size() != 1)
1279     return true;
1280 
1281   // Check and verify the descriptor.
1282   IITDescriptor D = Infos.front();
1283   Infos = Infos.slice(1);
1284   if (D.Kind == IITDescriptor::VarArg)
1285     return !isVarArg;
1286 
1287   return true;
1288 }
1289 
1290 Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) {
1291   Intrinsic::ID ID = F->getIntrinsicID();
1292   if (!ID)
1293     return None;
1294 
1295   FunctionType *FTy = F->getFunctionType();
1296   // Accumulate an array of overloaded types for the given intrinsic
1297   SmallVector<Type *, 4> ArgTys;
1298   {
1299     SmallVector<Intrinsic::IITDescriptor, 8> Table;
1300     getIntrinsicInfoTableEntries(ID, Table);
1301     ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1302 
1303     if (Intrinsic::matchIntrinsicSignature(FTy, TableRef, ArgTys))
1304       return None;
1305     if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef))
1306       return None;
1307   }
1308 
1309   StringRef Name = F->getName();
1310   if (Name == Intrinsic::getName(ID, ArgTys))
1311     return None;
1312 
1313   auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
1314   NewDecl->setCallingConv(F->getCallingConv());
1315   assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature");
1316   return NewDecl;
1317 }
1318 
1319 /// hasAddressTaken - returns true if there are any uses of this function
1320 /// other than direct calls or invokes to it.
1321 bool Function::hasAddressTaken(const User* *PutOffender) const {
1322   for (const Use &U : uses()) {
1323     const User *FU = U.getUser();
1324     if (isa<BlockAddress>(FU))
1325       continue;
1326     const auto *Call = dyn_cast<CallBase>(FU);
1327     if (!Call) {
1328       if (PutOffender)
1329         *PutOffender = FU;
1330       return true;
1331     }
1332     if (!Call->isCallee(&U)) {
1333       if (PutOffender)
1334         *PutOffender = FU;
1335       return true;
1336     }
1337   }
1338   return false;
1339 }
1340 
1341 bool Function::isDefTriviallyDead() const {
1342   // Check the linkage
1343   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1344       !hasAvailableExternallyLinkage())
1345     return false;
1346 
1347   // Check if the function is used by anything other than a blockaddress.
1348   for (const User *U : users())
1349     if (!isa<BlockAddress>(U))
1350       return false;
1351 
1352   return true;
1353 }
1354 
1355 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1356 /// setjmp or other function that gcc recognizes as "returning twice".
1357 bool Function::callsFunctionThatReturnsTwice() const {
1358   for (const Instruction &I : instructions(this))
1359     if (const auto *Call = dyn_cast<CallBase>(&I))
1360       if (Call->hasFnAttr(Attribute::ReturnsTwice))
1361         return true;
1362 
1363   return false;
1364 }
1365 
1366 Constant *Function::getPersonalityFn() const {
1367   assert(hasPersonalityFn() && getNumOperands());
1368   return cast<Constant>(Op<0>());
1369 }
1370 
1371 void Function::setPersonalityFn(Constant *Fn) {
1372   setHungoffOperand<0>(Fn);
1373   setValueSubclassDataBit(3, Fn != nullptr);
1374 }
1375 
1376 Constant *Function::getPrefixData() const {
1377   assert(hasPrefixData() && getNumOperands());
1378   return cast<Constant>(Op<1>());
1379 }
1380 
1381 void Function::setPrefixData(Constant *PrefixData) {
1382   setHungoffOperand<1>(PrefixData);
1383   setValueSubclassDataBit(1, PrefixData != nullptr);
1384 }
1385 
1386 Constant *Function::getPrologueData() const {
1387   assert(hasPrologueData() && getNumOperands());
1388   return cast<Constant>(Op<2>());
1389 }
1390 
1391 void Function::setPrologueData(Constant *PrologueData) {
1392   setHungoffOperand<2>(PrologueData);
1393   setValueSubclassDataBit(2, PrologueData != nullptr);
1394 }
1395 
1396 void Function::allocHungoffUselist() {
1397   // If we've already allocated a uselist, stop here.
1398   if (getNumOperands())
1399     return;
1400 
1401   allocHungoffUses(3, /*IsPhi=*/ false);
1402   setNumHungOffUseOperands(3);
1403 
1404   // Initialize the uselist with placeholder operands to allow traversal.
1405   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
1406   Op<0>().set(CPN);
1407   Op<1>().set(CPN);
1408   Op<2>().set(CPN);
1409 }
1410 
1411 template <int Idx>
1412 void Function::setHungoffOperand(Constant *C) {
1413   if (C) {
1414     allocHungoffUselist();
1415     Op<Idx>().set(C);
1416   } else if (getNumOperands()) {
1417     Op<Idx>().set(
1418         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
1419   }
1420 }
1421 
1422 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1423   assert(Bit < 16 && "SubclassData contains only 16 bits");
1424   if (On)
1425     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1426   else
1427     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1428 }
1429 
1430 void Function::setEntryCount(ProfileCount Count,
1431                              const DenseSet<GlobalValue::GUID> *S) {
1432   assert(Count.hasValue());
1433 #if !defined(NDEBUG)
1434   auto PrevCount = getEntryCount();
1435   assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType());
1436 #endif
1437   MDBuilder MDB(getContext());
1438   setMetadata(
1439       LLVMContext::MD_prof,
1440       MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
1441 }
1442 
1443 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
1444                              const DenseSet<GlobalValue::GUID> *Imports) {
1445   setEntryCount(ProfileCount(Count, Type), Imports);
1446 }
1447 
1448 ProfileCount Function::getEntryCount(bool AllowSynthetic) const {
1449   MDNode *MD = getMetadata(LLVMContext::MD_prof);
1450   if (MD && MD->getOperand(0))
1451     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
1452       if (MDS->getString().equals("function_entry_count")) {
1453         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1454         uint64_t Count = CI->getValue().getZExtValue();
1455         // A value of -1 is used for SamplePGO when there were no samples.
1456         // Treat this the same as unknown.
1457         if (Count == (uint64_t)-1)
1458           return ProfileCount::getInvalid();
1459         return ProfileCount(Count, PCT_Real);
1460       } else if (AllowSynthetic &&
1461                  MDS->getString().equals("synthetic_function_entry_count")) {
1462         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1463         uint64_t Count = CI->getValue().getZExtValue();
1464         return ProfileCount(Count, PCT_Synthetic);
1465       }
1466     }
1467   return ProfileCount::getInvalid();
1468 }
1469 
1470 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
1471   DenseSet<GlobalValue::GUID> R;
1472   if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1473     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1474       if (MDS->getString().equals("function_entry_count"))
1475         for (unsigned i = 2; i < MD->getNumOperands(); i++)
1476           R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
1477                        ->getValue()
1478                        .getZExtValue());
1479   return R;
1480 }
1481 
1482 void Function::setSectionPrefix(StringRef Prefix) {
1483   MDBuilder MDB(getContext());
1484   setMetadata(LLVMContext::MD_section_prefix,
1485               MDB.createFunctionSectionPrefix(Prefix));
1486 }
1487 
1488 Optional<StringRef> Function::getSectionPrefix() const {
1489   if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
1490     assert(cast<MDString>(MD->getOperand(0))
1491                ->getString()
1492                .equals("function_section_prefix") &&
1493            "Metadata not match");
1494     return cast<MDString>(MD->getOperand(1))->getString();
1495   }
1496   return None;
1497 }
1498 
1499 bool Function::nullPointerIsDefined() const {
1500   return getFnAttribute("null-pointer-is-valid")
1501           .getValueAsString()
1502           .equals("true");
1503 }
1504 
1505 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
1506   if (F && F->nullPointerIsDefined())
1507     return true;
1508 
1509   if (AS != 0)
1510     return true;
1511 
1512   return false;
1513 }
1514