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