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