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