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