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