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