xref: /llvm-project/llvm/lib/IR/Function.cpp (revision f46262e0b7a183c22b9384cd729c5fb0f05e5d38)
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/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/CodeGen/ValueTypes.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/InstIterator.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/MDBuilder.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/RWMutex.h"
32 #include "llvm/Support/StringPool.h"
33 #include "llvm/Support/Threading.h"
34 using namespace llvm;
35 
36 // Explicit instantiations of SymbolTableListTraits since some of the methods
37 // are not in the public header file...
38 template class llvm::SymbolTableListTraits<Argument>;
39 template class llvm::SymbolTableListTraits<BasicBlock>;
40 
41 //===----------------------------------------------------------------------===//
42 // Argument Implementation
43 //===----------------------------------------------------------------------===//
44 
45 void Argument::anchor() { }
46 
47 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
48   : Value(Ty, Value::ArgumentVal) {
49   Parent = nullptr;
50 
51   if (Par)
52     Par->getArgumentList().push_back(this);
53   setName(Name);
54 }
55 
56 void Argument::setParent(Function *parent) {
57   Parent = parent;
58 }
59 
60 /// getArgNo - Return the index of this formal argument in its containing
61 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1.
62 unsigned Argument::getArgNo() const {
63   const Function *F = getParent();
64   assert(F && "Argument is not in a function");
65 
66   Function::const_arg_iterator AI = F->arg_begin();
67   unsigned ArgIdx = 0;
68   for (; &*AI != this; ++AI)
69     ++ArgIdx;
70 
71   return ArgIdx;
72 }
73 
74 /// hasNonNullAttr - Return true if this argument has the nonnull attribute on
75 /// it in its containing function. Also returns true if at least one byte is
76 /// known to be dereferenceable and the pointer is in addrspace(0).
77 bool Argument::hasNonNullAttr() const {
78   if (!getType()->isPointerTy()) return false;
79   if (getParent()->getAttributes().
80         hasAttribute(getArgNo()+1, Attribute::NonNull))
81     return true;
82   else if (getDereferenceableBytes() > 0 &&
83            getType()->getPointerAddressSpace() == 0)
84     return true;
85   return false;
86 }
87 
88 /// hasByValAttr - Return true if this argument has the byval attribute on it
89 /// in its containing function.
90 bool Argument::hasByValAttr() const {
91   if (!getType()->isPointerTy()) return false;
92   return hasAttribute(Attribute::ByVal);
93 }
94 
95 bool Argument::hasSwiftSelfAttr() const {
96   return getParent()->getAttributes().
97     hasAttribute(getArgNo()+1, Attribute::SwiftSelf);
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() & IsMaterializableBit;
218 }
219 
220 void Function::setIsMaterializable(bool V) {
221   setGlobalObjectBit(IsMaterializableBit, V);
222 }
223 
224 LLVMContext &Function::getContext() const {
225   return getType()->getContext();
226 }
227 
228 FunctionType *Function::getFunctionType() const {
229   return cast<FunctionType>(getValueType());
230 }
231 
232 bool Function::isVarArg() const {
233   return getFunctionType()->isVarArg();
234 }
235 
236 Type *Function::getReturnType() const {
237   return getFunctionType()->getReturnType();
238 }
239 
240 void Function::removeFromParent() {
241   getParent()->getFunctionList().remove(getIterator());
242 }
243 
244 void Function::eraseFromParent() {
245   getParent()->getFunctionList().erase(getIterator());
246 }
247 
248 //===----------------------------------------------------------------------===//
249 // Function Implementation
250 //===----------------------------------------------------------------------===//
251 
252 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
253                    Module *ParentModule)
254     : GlobalObject(Ty, Value::FunctionVal,
255                    OperandTraits<Function>::op_begin(this), 0, Linkage, name) {
256   assert(FunctionType::isValidReturnType(getReturnType()) &&
257          "invalid return type");
258   setGlobalObjectSubClassData(0);
259   SymTab = new ValueSymbolTable();
260 
261   // If the function has arguments, mark them as lazily built.
262   if (Ty->getNumParams())
263     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
264 
265   if (ParentModule)
266     ParentModule->getFunctionList().push_back(this);
267 
268   // Ensure intrinsics have the right parameter attributes.
269   // Note, the IntID field will have been set in Value::setName if this function
270   // name is a valid intrinsic ID.
271   if (IntID)
272     setAttributes(Intrinsic::getAttributes(getContext(), IntID));
273 }
274 
275 Function::~Function() {
276   dropAllReferences();    // After this it is safe to delete instructions.
277 
278   // Delete all of the method arguments and unlink from symbol table...
279   ArgumentList.clear();
280   delete SymTab;
281 
282   // Remove the function from the on-the-side GC table.
283   clearGC();
284 }
285 
286 void Function::BuildLazyArguments() const {
287   // Create the arguments vector, all arguments start out unnamed.
288   FunctionType *FT = getFunctionType();
289   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
290     assert(!FT->getParamType(i)->isVoidTy() &&
291            "Cannot have void typed arguments!");
292     ArgumentList.push_back(new Argument(FT->getParamType(i)));
293   }
294 
295   // Clear the lazy arguments bit.
296   unsigned SDC = getSubclassDataFromValue();
297   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
298 }
299 
300 size_t Function::arg_size() const {
301   return getFunctionType()->getNumParams();
302 }
303 bool Function::arg_empty() const {
304   return getFunctionType()->getNumParams() == 0;
305 }
306 
307 void Function::setParent(Module *parent) {
308   Parent = parent;
309 }
310 
311 // dropAllReferences() - This function causes all the subinstructions to "let
312 // go" of all references that they are maintaining.  This allows one to
313 // 'delete' a whole class at a time, even though there may be circular
314 // references... first all references are dropped, and all use counts go to
315 // zero.  Then everything is deleted for real.  Note that no operations are
316 // valid on an object that has "dropped all references", except operator
317 // delete.
318 //
319 void Function::dropAllReferences() {
320   setIsMaterializable(false);
321 
322   for (iterator I = begin(), E = end(); I != E; ++I)
323     I->dropAllReferences();
324 
325   // Delete all basic blocks. They are now unused, except possibly by
326   // blockaddresses, but BasicBlock's destructor takes care of those.
327   while (!BasicBlocks.empty())
328     BasicBlocks.begin()->eraseFromParent();
329 
330   // Drop uses of any optional data (real or placeholder).
331   if (getNumOperands()) {
332     User::dropAllReferences();
333     setNumHungOffUseOperands(0);
334     setValueSubclassData(getSubclassDataFromValue() & ~0xe);
335   }
336 
337   // Metadata is stored in a side-table.
338   clearMetadata();
339 }
340 
341 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
342   AttributeSet PAL = getAttributes();
343   PAL = PAL.addAttribute(getContext(), i, attr);
344   setAttributes(PAL);
345 }
346 
347 void Function::addAttributes(unsigned i, AttributeSet attrs) {
348   AttributeSet PAL = getAttributes();
349   PAL = PAL.addAttributes(getContext(), i, attrs);
350   setAttributes(PAL);
351 }
352 
353 void Function::removeAttribute(unsigned i, Attribute::AttrKind attr) {
354   AttributeSet PAL = getAttributes();
355   PAL = PAL.removeAttribute(getContext(), i, attr);
356   setAttributes(PAL);
357 }
358 
359 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
360   AttributeSet PAL = getAttributes();
361   PAL = PAL.removeAttributes(getContext(), i, attrs);
362   setAttributes(PAL);
363 }
364 
365 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
366   AttributeSet PAL = getAttributes();
367   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
368   setAttributes(PAL);
369 }
370 
371 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
372   AttributeSet PAL = getAttributes();
373   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
374   setAttributes(PAL);
375 }
376 
377 const std::string &Function::getGC() const {
378   assert(hasGC() && "Function has no collector");
379   return getContext().getGC(*this);
380 }
381 
382 void Function::setGC(const std::string Str) {
383   setValueSubclassDataBit(14, !Str.empty());
384   getContext().setGC(*this, std::move(Str));
385 }
386 
387 void Function::clearGC() {
388   if (!hasGC())
389     return;
390   getContext().deleteGC(*this);
391   setValueSubclassDataBit(14, false);
392 }
393 
394 /// Copy all additional attributes (those not needed to create a Function) from
395 /// the Function Src to this one.
396 void Function::copyAttributesFrom(const GlobalValue *Src) {
397   GlobalObject::copyAttributesFrom(Src);
398   const Function *SrcF = dyn_cast<Function>(Src);
399   if (!SrcF)
400     return;
401 
402   setCallingConv(SrcF->getCallingConv());
403   setAttributes(SrcF->getAttributes());
404   if (SrcF->hasGC())
405     setGC(SrcF->getGC());
406   else
407     clearGC();
408   if (SrcF->hasPersonalityFn())
409     setPersonalityFn(SrcF->getPersonalityFn());
410   if (SrcF->hasPrefixData())
411     setPrefixData(SrcF->getPrefixData());
412   if (SrcF->hasPrologueData())
413     setPrologueData(SrcF->getPrologueData());
414 }
415 
416 /// Table of string intrinsic names indexed by enum value.
417 static const char * const IntrinsicNameTable[] = {
418   "not_intrinsic",
419 #define GET_INTRINSIC_NAME_TABLE
420 #include "llvm/IR/Intrinsics.gen"
421 #undef GET_INTRINSIC_NAME_TABLE
422 };
423 
424 /// \brief This does the actual lookup of an intrinsic ID which
425 /// matches the given function name.
426 static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) {
427   StringRef Name = ValName->getKey();
428 
429   ArrayRef<const char *> NameTable(&IntrinsicNameTable[1],
430                                    std::end(IntrinsicNameTable));
431   int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
432   Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + 1);
433   if (ID == Intrinsic::not_intrinsic)
434     return ID;
435 
436   // If the intrinsic is not overloaded, require an exact match. If it is
437   // overloaded, require a prefix match.
438   bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]);
439   return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic;
440 }
441 
442 void Function::recalculateIntrinsicID() {
443   const ValueName *ValName = this->getValueName();
444   if (!ValName || !isIntrinsic()) {
445     IntID = Intrinsic::not_intrinsic;
446     return;
447   }
448   IntID = lookupIntrinsicID(ValName);
449 }
450 
451 /// Returns a stable mangling for the type specified for use in the name
452 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
453 /// of named types is simply their name.  Manglings for unnamed types consist
454 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
455 /// combined with the mangling of their component types.  A vararg function
456 /// type will have a suffix of 'vararg'.  Since function types can contain
457 /// other function types, we close a function type mangling with suffix 'f'
458 /// which can't be confused with it's prefix.  This ensures we don't have
459 /// collisions between two unrelated function types. Otherwise, you might
460 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
461 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
462 /// cases) fall back to the MVT codepath, where they could be mangled to
463 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle
464 /// everything.
465 static std::string getMangledTypeStr(Type* Ty) {
466   std::string Result;
467   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
468     Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
469       getMangledTypeStr(PTyp->getElementType());
470   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
471     Result += "a" + llvm::utostr(ATyp->getNumElements()) +
472       getMangledTypeStr(ATyp->getElementType());
473   } else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
474     assert(!STyp->isLiteral() && "TODO: implement literal types");
475     Result += STyp->getName();
476   } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
477     Result += "f_" + getMangledTypeStr(FT->getReturnType());
478     for (size_t i = 0; i < FT->getNumParams(); i++)
479       Result += getMangledTypeStr(FT->getParamType(i));
480     if (FT->isVarArg())
481       Result += "vararg";
482     // Ensure nested function types are distinguishable.
483     Result += "f";
484   } else if (isa<VectorType>(Ty))
485     Result += "v" + utostr(Ty->getVectorNumElements()) +
486       getMangledTypeStr(Ty->getVectorElementType());
487   else if (Ty)
488     Result += EVT::getEVT(Ty).getEVTString();
489   return Result;
490 }
491 
492 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
493   assert(id < num_intrinsics && "Invalid intrinsic ID!");
494   if (Tys.empty())
495     return IntrinsicNameTable[id];
496   std::string Result(IntrinsicNameTable[id]);
497   for (unsigned i = 0; i < Tys.size(); ++i) {
498     Result += "." + getMangledTypeStr(Tys[i]);
499   }
500   return Result;
501 }
502 
503 
504 /// IIT_Info - These are enumerators that describe the entries returned by the
505 /// getIntrinsicInfoTableEntries function.
506 ///
507 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
508 enum IIT_Info {
509   // Common values should be encoded with 0-15.
510   IIT_Done = 0,
511   IIT_I1   = 1,
512   IIT_I8   = 2,
513   IIT_I16  = 3,
514   IIT_I32  = 4,
515   IIT_I64  = 5,
516   IIT_F16  = 6,
517   IIT_F32  = 7,
518   IIT_F64  = 8,
519   IIT_V2   = 9,
520   IIT_V4   = 10,
521   IIT_V8   = 11,
522   IIT_V16  = 12,
523   IIT_V32  = 13,
524   IIT_PTR  = 14,
525   IIT_ARG  = 15,
526 
527   // Values from 16+ are only encodable with the inefficient encoding.
528   IIT_V64  = 16,
529   IIT_MMX  = 17,
530   IIT_TOKEN = 18,
531   IIT_METADATA = 19,
532   IIT_EMPTYSTRUCT = 20,
533   IIT_STRUCT2 = 21,
534   IIT_STRUCT3 = 22,
535   IIT_STRUCT4 = 23,
536   IIT_STRUCT5 = 24,
537   IIT_EXTEND_ARG = 25,
538   IIT_TRUNC_ARG = 26,
539   IIT_ANYPTR = 27,
540   IIT_V1   = 28,
541   IIT_VARARG = 29,
542   IIT_HALF_VEC_ARG = 30,
543   IIT_SAME_VEC_WIDTH_ARG = 31,
544   IIT_PTR_TO_ARG = 32,
545   IIT_VEC_OF_PTRS_TO_ELT = 33,
546   IIT_I128 = 34,
547   IIT_V512 = 35,
548   IIT_V1024 = 36
549 };
550 
551 
552 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
553                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
554   IIT_Info Info = IIT_Info(Infos[NextElt++]);
555   unsigned StructElts = 2;
556   using namespace Intrinsic;
557 
558   switch (Info) {
559   case IIT_Done:
560     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
561     return;
562   case IIT_VARARG:
563     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
564     return;
565   case IIT_MMX:
566     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
567     return;
568   case IIT_TOKEN:
569     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
570     return;
571   case IIT_METADATA:
572     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
573     return;
574   case IIT_F16:
575     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
576     return;
577   case IIT_F32:
578     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
579     return;
580   case IIT_F64:
581     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
582     return;
583   case IIT_I1:
584     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
585     return;
586   case IIT_I8:
587     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
588     return;
589   case IIT_I16:
590     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
591     return;
592   case IIT_I32:
593     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
594     return;
595   case IIT_I64:
596     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
597     return;
598   case IIT_I128:
599     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
600     return;
601   case IIT_V1:
602     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
603     DecodeIITType(NextElt, Infos, OutputTable);
604     return;
605   case IIT_V2:
606     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
607     DecodeIITType(NextElt, Infos, OutputTable);
608     return;
609   case IIT_V4:
610     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
611     DecodeIITType(NextElt, Infos, OutputTable);
612     return;
613   case IIT_V8:
614     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
615     DecodeIITType(NextElt, Infos, OutputTable);
616     return;
617   case IIT_V16:
618     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
619     DecodeIITType(NextElt, Infos, OutputTable);
620     return;
621   case IIT_V32:
622     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
623     DecodeIITType(NextElt, Infos, OutputTable);
624     return;
625   case IIT_V64:
626     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
627     DecodeIITType(NextElt, Infos, OutputTable);
628     return;
629   case IIT_V512:
630     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
631     DecodeIITType(NextElt, Infos, OutputTable);
632     return;
633   case IIT_V1024:
634     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
635     DecodeIITType(NextElt, Infos, OutputTable);
636     return;
637   case IIT_PTR:
638     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
639     DecodeIITType(NextElt, Infos, OutputTable);
640     return;
641   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
642     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
643                                              Infos[NextElt++]));
644     DecodeIITType(NextElt, Infos, OutputTable);
645     return;
646   }
647   case IIT_ARG: {
648     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
649     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
650     return;
651   }
652   case IIT_EXTEND_ARG: {
653     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
654     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
655                                              ArgInfo));
656     return;
657   }
658   case IIT_TRUNC_ARG: {
659     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
660     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
661                                              ArgInfo));
662     return;
663   }
664   case IIT_HALF_VEC_ARG: {
665     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
666     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
667                                              ArgInfo));
668     return;
669   }
670   case IIT_SAME_VEC_WIDTH_ARG: {
671     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
672     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
673                                              ArgInfo));
674     return;
675   }
676   case IIT_PTR_TO_ARG: {
677     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
678     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
679                                              ArgInfo));
680     return;
681   }
682   case IIT_VEC_OF_PTRS_TO_ELT: {
683     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
684     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt,
685                                              ArgInfo));
686     return;
687   }
688   case IIT_EMPTYSTRUCT:
689     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
690     return;
691   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
692   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
693   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
694   case IIT_STRUCT2: {
695     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
696 
697     for (unsigned i = 0; i != StructElts; ++i)
698       DecodeIITType(NextElt, Infos, OutputTable);
699     return;
700   }
701   }
702   llvm_unreachable("unhandled");
703 }
704 
705 
706 #define GET_INTRINSIC_GENERATOR_GLOBAL
707 #include "llvm/IR/Intrinsics.gen"
708 #undef GET_INTRINSIC_GENERATOR_GLOBAL
709 
710 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
711                                              SmallVectorImpl<IITDescriptor> &T){
712   // Check to see if the intrinsic's type was expressible by the table.
713   unsigned TableVal = IIT_Table[id-1];
714 
715   // Decode the TableVal into an array of IITValues.
716   SmallVector<unsigned char, 8> IITValues;
717   ArrayRef<unsigned char> IITEntries;
718   unsigned NextElt = 0;
719   if ((TableVal >> 31) != 0) {
720     // This is an offset into the IIT_LongEncodingTable.
721     IITEntries = IIT_LongEncodingTable;
722 
723     // Strip sentinel bit.
724     NextElt = (TableVal << 1) >> 1;
725   } else {
726     // Decode the TableVal into an array of IITValues.  If the entry was encoded
727     // into a single word in the table itself, decode it now.
728     do {
729       IITValues.push_back(TableVal & 0xF);
730       TableVal >>= 4;
731     } while (TableVal);
732 
733     IITEntries = IITValues;
734     NextElt = 0;
735   }
736 
737   // Okay, decode the table into the output vector of IITDescriptors.
738   DecodeIITType(NextElt, IITEntries, T);
739   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
740     DecodeIITType(NextElt, IITEntries, T);
741 }
742 
743 
744 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
745                              ArrayRef<Type*> Tys, LLVMContext &Context) {
746   using namespace Intrinsic;
747   IITDescriptor D = Infos.front();
748   Infos = Infos.slice(1);
749 
750   switch (D.Kind) {
751   case IITDescriptor::Void: return Type::getVoidTy(Context);
752   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
753   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
754   case IITDescriptor::Token: return Type::getTokenTy(Context);
755   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
756   case IITDescriptor::Half: return Type::getHalfTy(Context);
757   case IITDescriptor::Float: return Type::getFloatTy(Context);
758   case IITDescriptor::Double: return Type::getDoubleTy(Context);
759 
760   case IITDescriptor::Integer:
761     return IntegerType::get(Context, D.Integer_Width);
762   case IITDescriptor::Vector:
763     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
764   case IITDescriptor::Pointer:
765     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
766                             D.Pointer_AddressSpace);
767   case IITDescriptor::Struct: {
768     Type *Elts[5];
769     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
770     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
771       Elts[i] = DecodeFixedType(Infos, Tys, Context);
772     return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
773   }
774 
775   case IITDescriptor::Argument:
776     return Tys[D.getArgumentNumber()];
777   case IITDescriptor::ExtendArgument: {
778     Type *Ty = Tys[D.getArgumentNumber()];
779     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
780       return VectorType::getExtendedElementVectorType(VTy);
781 
782     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
783   }
784   case IITDescriptor::TruncArgument: {
785     Type *Ty = Tys[D.getArgumentNumber()];
786     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
787       return VectorType::getTruncatedElementVectorType(VTy);
788 
789     IntegerType *ITy = cast<IntegerType>(Ty);
790     assert(ITy->getBitWidth() % 2 == 0);
791     return IntegerType::get(Context, ITy->getBitWidth() / 2);
792   }
793   case IITDescriptor::HalfVecArgument:
794     return VectorType::getHalfElementsVectorType(cast<VectorType>(
795                                                   Tys[D.getArgumentNumber()]));
796   case IITDescriptor::SameVecWidthArgument: {
797     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
798     Type *Ty = Tys[D.getArgumentNumber()];
799     if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
800       return VectorType::get(EltTy, VTy->getNumElements());
801     }
802     llvm_unreachable("unhandled");
803   }
804   case IITDescriptor::PtrToArgument: {
805     Type *Ty = Tys[D.getArgumentNumber()];
806     return PointerType::getUnqual(Ty);
807   }
808   case IITDescriptor::VecOfPtrsToElt: {
809     Type *Ty = Tys[D.getArgumentNumber()];
810     VectorType *VTy = dyn_cast<VectorType>(Ty);
811     if (!VTy)
812       llvm_unreachable("Expected an argument of Vector Type");
813     Type *EltTy = VTy->getVectorElementType();
814     return VectorType::get(PointerType::getUnqual(EltTy),
815                            VTy->getNumElements());
816   }
817  }
818   llvm_unreachable("unhandled");
819 }
820 
821 
822 
823 FunctionType *Intrinsic::getType(LLVMContext &Context,
824                                  ID id, ArrayRef<Type*> Tys) {
825   SmallVector<IITDescriptor, 8> Table;
826   getIntrinsicInfoTableEntries(id, Table);
827 
828   ArrayRef<IITDescriptor> TableRef = Table;
829   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
830 
831   SmallVector<Type*, 8> ArgTys;
832   while (!TableRef.empty())
833     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
834 
835   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
836   // If we see void type as the type of the last argument, it is vararg intrinsic
837   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
838     ArgTys.pop_back();
839     return FunctionType::get(ResultTy, ArgTys, true);
840   }
841   return FunctionType::get(ResultTy, ArgTys, false);
842 }
843 
844 bool Intrinsic::isOverloaded(ID id) {
845 #define GET_INTRINSIC_OVERLOAD_TABLE
846 #include "llvm/IR/Intrinsics.gen"
847 #undef GET_INTRINSIC_OVERLOAD_TABLE
848 }
849 
850 bool Intrinsic::isLeaf(ID id) {
851   switch (id) {
852   default:
853     return true;
854 
855   case Intrinsic::experimental_gc_statepoint:
856   case Intrinsic::experimental_patchpoint_void:
857   case Intrinsic::experimental_patchpoint_i64:
858     return false;
859   }
860 }
861 
862 /// This defines the "Intrinsic::getAttributes(ID id)" method.
863 #define GET_INTRINSIC_ATTRIBUTES
864 #include "llvm/IR/Intrinsics.gen"
865 #undef GET_INTRINSIC_ATTRIBUTES
866 
867 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
868   // There can never be multiple globals with the same name of different types,
869   // because intrinsics must be a specific type.
870   return
871     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
872                                           getType(M->getContext(), id, Tys)));
873 }
874 
875 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
876 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
877 #include "llvm/IR/Intrinsics.gen"
878 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
879 
880 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
881 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
882 #include "llvm/IR/Intrinsics.gen"
883 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
884 
885 /// hasAddressTaken - returns true if there are any uses of this function
886 /// other than direct calls or invokes to it.
887 bool Function::hasAddressTaken(const User* *PutOffender) const {
888   for (const Use &U : uses()) {
889     const User *FU = U.getUser();
890     if (isa<BlockAddress>(FU))
891       continue;
892     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) {
893       if (PutOffender)
894         *PutOffender = FU;
895       return true;
896     }
897     ImmutableCallSite CS(cast<Instruction>(FU));
898     if (!CS.isCallee(&U)) {
899       if (PutOffender)
900         *PutOffender = FU;
901       return true;
902     }
903   }
904   return false;
905 }
906 
907 bool Function::isDefTriviallyDead() const {
908   // Check the linkage
909   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
910       !hasAvailableExternallyLinkage())
911     return false;
912 
913   // Check if the function is used by anything other than a blockaddress.
914   for (const User *U : users())
915     if (!isa<BlockAddress>(U))
916       return false;
917 
918   return true;
919 }
920 
921 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
922 /// setjmp or other function that gcc recognizes as "returning twice".
923 bool Function::callsFunctionThatReturnsTwice() const {
924   for (const_inst_iterator
925          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
926     ImmutableCallSite CS(&*I);
927     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
928       return true;
929   }
930 
931   return false;
932 }
933 
934 Constant *Function::getPersonalityFn() const {
935   assert(hasPersonalityFn() && getNumOperands());
936   return cast<Constant>(Op<0>());
937 }
938 
939 void Function::setPersonalityFn(Constant *Fn) {
940   setHungoffOperand<0>(Fn);
941   setValueSubclassDataBit(3, Fn != nullptr);
942 }
943 
944 Constant *Function::getPrefixData() const {
945   assert(hasPrefixData() && getNumOperands());
946   return cast<Constant>(Op<1>());
947 }
948 
949 void Function::setPrefixData(Constant *PrefixData) {
950   setHungoffOperand<1>(PrefixData);
951   setValueSubclassDataBit(1, PrefixData != nullptr);
952 }
953 
954 Constant *Function::getPrologueData() const {
955   assert(hasPrologueData() && getNumOperands());
956   return cast<Constant>(Op<2>());
957 }
958 
959 void Function::setPrologueData(Constant *PrologueData) {
960   setHungoffOperand<2>(PrologueData);
961   setValueSubclassDataBit(2, PrologueData != nullptr);
962 }
963 
964 void Function::allocHungoffUselist() {
965   // If we've already allocated a uselist, stop here.
966   if (getNumOperands())
967     return;
968 
969   allocHungoffUses(3, /*IsPhi=*/ false);
970   setNumHungOffUseOperands(3);
971 
972   // Initialize the uselist with placeholder operands to allow traversal.
973   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
974   Op<0>().set(CPN);
975   Op<1>().set(CPN);
976   Op<2>().set(CPN);
977 }
978 
979 template <int Idx>
980 void Function::setHungoffOperand(Constant *C) {
981   if (C) {
982     allocHungoffUselist();
983     Op<Idx>().set(C);
984   } else if (getNumOperands()) {
985     Op<Idx>().set(
986         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
987   }
988 }
989 
990 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
991   assert(Bit < 16 && "SubclassData contains only 16 bits");
992   if (On)
993     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
994   else
995     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
996 }
997 
998 void Function::setEntryCount(uint64_t Count) {
999   MDBuilder MDB(getContext());
1000   setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count));
1001 }
1002 
1003 Optional<uint64_t> Function::getEntryCount() const {
1004   MDNode *MD = getMetadata(LLVMContext::MD_prof);
1005   if (MD && MD->getOperand(0))
1006     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1007       if (MDS->getString().equals("function_entry_count")) {
1008         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1009         return CI->getValue().getZExtValue();
1010       }
1011   return None;
1012 }
1013