xref: /llvm-project/llvm/lib/IR/Function.cpp (revision 6f5d9136b27eefc981333d8c23ea9c0a38033d7b)
1 //===- Function.cpp - Implement the Global object classes -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Function class for the IR library.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/Function.h"
14 #include "SymbolTableListTraitsImpl.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/Argument.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/InstIterator.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/IntrinsicsAArch64.h"
35 #include "llvm/IR/IntrinsicsAMDGPU.h"
36 #include "llvm/IR/IntrinsicsARM.h"
37 #include "llvm/IR/IntrinsicsBPF.h"
38 #include "llvm/IR/IntrinsicsHexagon.h"
39 #include "llvm/IR/IntrinsicsMips.h"
40 #include "llvm/IR/IntrinsicsNVPTX.h"
41 #include "llvm/IR/IntrinsicsPowerPC.h"
42 #include "llvm/IR/IntrinsicsR600.h"
43 #include "llvm/IR/IntrinsicsRISCV.h"
44 #include "llvm/IR/IntrinsicsS390.h"
45 #include "llvm/IR/IntrinsicsWebAssembly.h"
46 #include "llvm/IR/IntrinsicsX86.h"
47 #include "llvm/IR/IntrinsicsXCore.h"
48 #include "llvm/IR/LLVMContext.h"
49 #include "llvm/IR/MDBuilder.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/SymbolTableListTraits.h"
53 #include "llvm/IR/Type.h"
54 #include "llvm/IR/Use.h"
55 #include "llvm/IR/User.h"
56 #include "llvm/IR/Value.h"
57 #include "llvm/IR/ValueSymbolTable.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/Compiler.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include <algorithm>
62 #include <cassert>
63 #include <cstddef>
64 #include <cstdint>
65 #include <cstring>
66 #include <string>
67 
68 using namespace llvm;
69 using ProfileCount = Function::ProfileCount;
70 
71 // Explicit instantiations of SymbolTableListTraits since some of the methods
72 // are not in the public header file...
73 template class llvm::SymbolTableListTraits<BasicBlock>;
74 
75 //===----------------------------------------------------------------------===//
76 // Argument Implementation
77 //===----------------------------------------------------------------------===//
78 
79 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
80     : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
81   setName(Name);
82 }
83 
84 void Argument::setParent(Function *parent) {
85   Parent = parent;
86 }
87 
88 bool Argument::hasNonNullAttr() const {
89   if (!getType()->isPointerTy()) return false;
90   if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull))
91     return true;
92   else if (getDereferenceableBytes() > 0 &&
93            !NullPointerIsDefined(getParent(),
94                                  getType()->getPointerAddressSpace()))
95     return true;
96   return false;
97 }
98 
99 bool Argument::hasByValAttr() const {
100   if (!getType()->isPointerTy()) return false;
101   return hasAttribute(Attribute::ByVal);
102 }
103 
104 bool Argument::hasSwiftSelfAttr() const {
105   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
106 }
107 
108 bool Argument::hasSwiftErrorAttr() const {
109   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
110 }
111 
112 bool Argument::hasInAllocaAttr() const {
113   if (!getType()->isPointerTy()) return false;
114   return hasAttribute(Attribute::InAlloca);
115 }
116 
117 bool Argument::hasPreallocatedAttr() const {
118   if (!getType()->isPointerTy())
119     return false;
120   return hasAttribute(Attribute::Preallocated);
121 }
122 
123 bool Argument::hasPassPointeeByValueAttr() const {
124   if (!getType()->isPointerTy()) return false;
125   AttributeList Attrs = getParent()->getAttributes();
126   return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
127          Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) ||
128          Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated);
129 }
130 
131 uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const {
132   AttributeSet ParamAttrs
133     = getParent()->getAttributes().getParamAttributes(getArgNo());
134 
135   // FIXME: All the type carrying attributes are mutually exclusive, so there
136   // should be a single query to get the stored type that handles any of them.
137   if (Type *ByValTy = ParamAttrs.getByValType())
138     return DL.getTypeAllocSize(ByValTy);
139   if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
140     return DL.getTypeAllocSize(PreAllocTy);
141 
142   // FIXME: inalloca always depends on pointee element type. It's also possible
143   // for byval to miss it.
144   if (ParamAttrs.hasAttribute(Attribute::InAlloca) ||
145       ParamAttrs.hasAttribute(Attribute::ByVal) ||
146       ParamAttrs.hasAttribute(Attribute::Preallocated))
147     return DL.getTypeAllocSize(cast<PointerType>(getType())->getElementType());
148 
149   return 0;
150 }
151 
152 unsigned Argument::getParamAlignment() const {
153   assert(getType()->isPointerTy() && "Only pointers have alignments");
154   return getParent()->getParamAlignment(getArgNo());
155 }
156 
157 MaybeAlign Argument::getParamAlign() const {
158   assert(getType()->isPointerTy() && "Only pointers have alignments");
159   return getParent()->getParamAlign(getArgNo());
160 }
161 
162 Type *Argument::getParamByValType() const {
163   assert(getType()->isPointerTy() && "Only pointers have byval types");
164   return getParent()->getParamByValType(getArgNo());
165 }
166 
167 uint64_t Argument::getDereferenceableBytes() const {
168   assert(getType()->isPointerTy() &&
169          "Only pointers have dereferenceable bytes");
170   return getParent()->getParamDereferenceableBytes(getArgNo());
171 }
172 
173 uint64_t Argument::getDereferenceableOrNullBytes() const {
174   assert(getType()->isPointerTy() &&
175          "Only pointers have dereferenceable bytes");
176   return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
177 }
178 
179 bool Argument::hasNestAttr() const {
180   if (!getType()->isPointerTy()) return false;
181   return hasAttribute(Attribute::Nest);
182 }
183 
184 bool Argument::hasNoAliasAttr() const {
185   if (!getType()->isPointerTy()) return false;
186   return hasAttribute(Attribute::NoAlias);
187 }
188 
189 bool Argument::hasNoCaptureAttr() const {
190   if (!getType()->isPointerTy()) return false;
191   return hasAttribute(Attribute::NoCapture);
192 }
193 
194 bool Argument::hasStructRetAttr() const {
195   if (!getType()->isPointerTy()) return false;
196   return hasAttribute(Attribute::StructRet);
197 }
198 
199 bool Argument::hasInRegAttr() const {
200   return hasAttribute(Attribute::InReg);
201 }
202 
203 bool Argument::hasReturnedAttr() const {
204   return hasAttribute(Attribute::Returned);
205 }
206 
207 bool Argument::hasZExtAttr() const {
208   return hasAttribute(Attribute::ZExt);
209 }
210 
211 bool Argument::hasSExtAttr() const {
212   return hasAttribute(Attribute::SExt);
213 }
214 
215 bool Argument::onlyReadsMemory() const {
216   AttributeList Attrs = getParent()->getAttributes();
217   return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
218          Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
219 }
220 
221 void Argument::addAttrs(AttrBuilder &B) {
222   AttributeList AL = getParent()->getAttributes();
223   AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
224   getParent()->setAttributes(AL);
225 }
226 
227 void Argument::addAttr(Attribute::AttrKind Kind) {
228   getParent()->addParamAttr(getArgNo(), Kind);
229 }
230 
231 void Argument::addAttr(Attribute Attr) {
232   getParent()->addParamAttr(getArgNo(), Attr);
233 }
234 
235 void Argument::removeAttr(Attribute::AttrKind Kind) {
236   getParent()->removeParamAttr(getArgNo(), Kind);
237 }
238 
239 bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
240   return getParent()->hasParamAttribute(getArgNo(), Kind);
241 }
242 
243 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
244   return getParent()->getParamAttribute(getArgNo(), Kind);
245 }
246 
247 //===----------------------------------------------------------------------===//
248 // Helper Methods in Function
249 //===----------------------------------------------------------------------===//
250 
251 LLVMContext &Function::getContext() const {
252   return getType()->getContext();
253 }
254 
255 unsigned Function::getInstructionCount() const {
256   unsigned NumInstrs = 0;
257   for (const BasicBlock &BB : BasicBlocks)
258     NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
259                                BB.instructionsWithoutDebug().end());
260   return NumInstrs;
261 }
262 
263 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
264                            const Twine &N, Module &M) {
265   return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
266 }
267 
268 void Function::removeFromParent() {
269   getParent()->getFunctionList().remove(getIterator());
270 }
271 
272 void Function::eraseFromParent() {
273   getParent()->getFunctionList().erase(getIterator());
274 }
275 
276 //===----------------------------------------------------------------------===//
277 // Function Implementation
278 //===----------------------------------------------------------------------===//
279 
280 static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
281   // If AS == -1 and we are passed a valid module pointer we place the function
282   // in the program address space. Otherwise we default to AS0.
283   if (AddrSpace == static_cast<unsigned>(-1))
284     return M ? M->getDataLayout().getProgramAddressSpace() : 0;
285   return AddrSpace;
286 }
287 
288 Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
289                    const Twine &name, Module *ParentModule)
290     : GlobalObject(Ty, Value::FunctionVal,
291                    OperandTraits<Function>::op_begin(this), 0, Linkage, name,
292                    computeAddrSpace(AddrSpace, ParentModule)),
293       NumArgs(Ty->getNumParams()) {
294   assert(FunctionType::isValidReturnType(getReturnType()) &&
295          "invalid return type");
296   setGlobalObjectSubClassData(0);
297 
298   // We only need a symbol table for a function if the context keeps value names
299   if (!getContext().shouldDiscardValueNames())
300     SymTab = std::make_unique<ValueSymbolTable>();
301 
302   // If the function has arguments, mark them as lazily built.
303   if (Ty->getNumParams())
304     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
305 
306   if (ParentModule)
307     ParentModule->getFunctionList().push_back(this);
308 
309   HasLLVMReservedName = getName().startswith("llvm.");
310   // Ensure intrinsics have the right parameter attributes.
311   // Note, the IntID field will have been set in Value::setName if this function
312   // name is a valid intrinsic ID.
313   if (IntID)
314     setAttributes(Intrinsic::getAttributes(getContext(), IntID));
315 }
316 
317 Function::~Function() {
318   dropAllReferences();    // After this it is safe to delete instructions.
319 
320   // Delete all of the method arguments and unlink from symbol table...
321   if (Arguments)
322     clearArguments();
323 
324   // Remove the function from the on-the-side GC table.
325   clearGC();
326 }
327 
328 void Function::BuildLazyArguments() const {
329   // Create the arguments vector, all arguments start out unnamed.
330   auto *FT = getFunctionType();
331   if (NumArgs > 0) {
332     Arguments = std::allocator<Argument>().allocate(NumArgs);
333     for (unsigned i = 0, e = NumArgs; i != e; ++i) {
334       Type *ArgTy = FT->getParamType(i);
335       assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
336       new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
337     }
338   }
339 
340   // Clear the lazy arguments bit.
341   unsigned SDC = getSubclassDataFromValue();
342   SDC &= ~(1 << 0);
343   const_cast<Function*>(this)->setValueSubclassData(SDC);
344   assert(!hasLazyArguments());
345 }
346 
347 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
348   return MutableArrayRef<Argument>(Args, Count);
349 }
350 
351 bool Function::isConstrainedFPIntrinsic() const {
352   switch (getIntrinsicID()) {
353 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
354   case Intrinsic::INTRINSIC:
355 #include "llvm/IR/ConstrainedOps.def"
356     return true;
357 #undef INSTRUCTION
358   default:
359     return false;
360   }
361 }
362 
363 void Function::clearArguments() {
364   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
365     A.setName("");
366     A.~Argument();
367   }
368   std::allocator<Argument>().deallocate(Arguments, NumArgs);
369   Arguments = nullptr;
370 }
371 
372 void Function::stealArgumentListFrom(Function &Src) {
373   assert(isDeclaration() && "Expected no references to current arguments");
374 
375   // Drop the current arguments, if any, and set the lazy argument bit.
376   if (!hasLazyArguments()) {
377     assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
378                         [](const Argument &A) { return A.use_empty(); }) &&
379            "Expected arguments to be unused in declaration");
380     clearArguments();
381     setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
382   }
383 
384   // Nothing to steal if Src has lazy arguments.
385   if (Src.hasLazyArguments())
386     return;
387 
388   // Steal arguments from Src, and fix the lazy argument bits.
389   assert(arg_size() == Src.arg_size());
390   Arguments = Src.Arguments;
391   Src.Arguments = nullptr;
392   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
393     // FIXME: This does the work of transferNodesFromList inefficiently.
394     SmallString<128> Name;
395     if (A.hasName())
396       Name = A.getName();
397     if (!Name.empty())
398       A.setName("");
399     A.setParent(this);
400     if (!Name.empty())
401       A.setName(Name);
402   }
403 
404   setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
405   assert(!hasLazyArguments());
406   Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
407 }
408 
409 // dropAllReferences() - This function causes all the subinstructions to "let
410 // go" of all references that they are maintaining.  This allows one to
411 // 'delete' a whole class at a time, even though there may be circular
412 // references... first all references are dropped, and all use counts go to
413 // zero.  Then everything is deleted for real.  Note that no operations are
414 // valid on an object that has "dropped all references", except operator
415 // delete.
416 //
417 void Function::dropAllReferences() {
418   setIsMaterializable(false);
419 
420   for (BasicBlock &BB : *this)
421     BB.dropAllReferences();
422 
423   // Delete all basic blocks. They are now unused, except possibly by
424   // blockaddresses, but BasicBlock's destructor takes care of those.
425   while (!BasicBlocks.empty())
426     BasicBlocks.begin()->eraseFromParent();
427 
428   // Drop uses of any optional data (real or placeholder).
429   if (getNumOperands()) {
430     User::dropAllReferences();
431     setNumHungOffUseOperands(0);
432     setValueSubclassData(getSubclassDataFromValue() & ~0xe);
433   }
434 
435   // Metadata is stored in a side-table.
436   clearMetadata();
437 }
438 
439 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
440   AttributeList PAL = getAttributes();
441   PAL = PAL.addAttribute(getContext(), i, Kind);
442   setAttributes(PAL);
443 }
444 
445 void Function::addAttribute(unsigned i, Attribute Attr) {
446   AttributeList PAL = getAttributes();
447   PAL = PAL.addAttribute(getContext(), i, Attr);
448   setAttributes(PAL);
449 }
450 
451 void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
452   AttributeList PAL = getAttributes();
453   PAL = PAL.addAttributes(getContext(), i, Attrs);
454   setAttributes(PAL);
455 }
456 
457 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
458   AttributeList PAL = getAttributes();
459   PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
460   setAttributes(PAL);
461 }
462 
463 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
464   AttributeList PAL = getAttributes();
465   PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
466   setAttributes(PAL);
467 }
468 
469 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
470   AttributeList PAL = getAttributes();
471   PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs);
472   setAttributes(PAL);
473 }
474 
475 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
476   AttributeList PAL = getAttributes();
477   PAL = PAL.removeAttribute(getContext(), i, Kind);
478   setAttributes(PAL);
479 }
480 
481 void Function::removeAttribute(unsigned i, StringRef Kind) {
482   AttributeList PAL = getAttributes();
483   PAL = PAL.removeAttribute(getContext(), i, Kind);
484   setAttributes(PAL);
485 }
486 
487 void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
488   AttributeList PAL = getAttributes();
489   PAL = PAL.removeAttributes(getContext(), i, Attrs);
490   setAttributes(PAL);
491 }
492 
493 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
494   AttributeList PAL = getAttributes();
495   PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
496   setAttributes(PAL);
497 }
498 
499 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
500   AttributeList PAL = getAttributes();
501   PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
502   setAttributes(PAL);
503 }
504 
505 void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
506   AttributeList PAL = getAttributes();
507   PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs);
508   setAttributes(PAL);
509 }
510 
511 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
512   AttributeList PAL = getAttributes();
513   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
514   setAttributes(PAL);
515 }
516 
517 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
518   AttributeList PAL = getAttributes();
519   PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
520   setAttributes(PAL);
521 }
522 
523 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
524   AttributeList PAL = getAttributes();
525   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
526   setAttributes(PAL);
527 }
528 
529 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
530                                                  uint64_t Bytes) {
531   AttributeList PAL = getAttributes();
532   PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes);
533   setAttributes(PAL);
534 }
535 
536 const std::string &Function::getGC() const {
537   assert(hasGC() && "Function has no collector");
538   return getContext().getGC(*this);
539 }
540 
541 void Function::setGC(std::string Str) {
542   setValueSubclassDataBit(14, !Str.empty());
543   getContext().setGC(*this, std::move(Str));
544 }
545 
546 void Function::clearGC() {
547   if (!hasGC())
548     return;
549   getContext().deleteGC(*this);
550   setValueSubclassDataBit(14, false);
551 }
552 
553 /// Copy all additional attributes (those not needed to create a Function) from
554 /// the Function Src to this one.
555 void Function::copyAttributesFrom(const Function *Src) {
556   GlobalObject::copyAttributesFrom(Src);
557   setCallingConv(Src->getCallingConv());
558   setAttributes(Src->getAttributes());
559   if (Src->hasGC())
560     setGC(Src->getGC());
561   else
562     clearGC();
563   if (Src->hasPersonalityFn())
564     setPersonalityFn(Src->getPersonalityFn());
565   if (Src->hasPrefixData())
566     setPrefixData(Src->getPrefixData());
567   if (Src->hasPrologueData())
568     setPrologueData(Src->getPrologueData());
569 }
570 
571 /// Table of string intrinsic names indexed by enum value.
572 static const char * const IntrinsicNameTable[] = {
573   "not_intrinsic",
574 #define GET_INTRINSIC_NAME_TABLE
575 #include "llvm/IR/IntrinsicImpl.inc"
576 #undef GET_INTRINSIC_NAME_TABLE
577 };
578 
579 /// Table of per-target intrinsic name tables.
580 #define GET_INTRINSIC_TARGET_DATA
581 #include "llvm/IR/IntrinsicImpl.inc"
582 #undef GET_INTRINSIC_TARGET_DATA
583 
584 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
585 /// target as \c Name, or the generic table if \c Name is not target specific.
586 ///
587 /// Returns the relevant slice of \c IntrinsicNameTable
588 static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
589   assert(Name.startswith("llvm."));
590 
591   ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
592   // Drop "llvm." and take the first dotted component. That will be the target
593   // if this is target specific.
594   StringRef Target = Name.drop_front(5).split('.').first;
595   auto It = partition_point(
596       Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
597   // We've either found the target or just fall back to the generic set, which
598   // is always first.
599   const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
600   return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
601 }
602 
603 /// This does the actual lookup of an intrinsic ID which
604 /// matches the given function name.
605 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
606   ArrayRef<const char *> NameTable = findTargetSubtable(Name);
607   int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
608   if (Idx == -1)
609     return Intrinsic::not_intrinsic;
610 
611   // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
612   // an index into a sub-table.
613   int Adjust = NameTable.data() - IntrinsicNameTable;
614   Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
615 
616   // If the intrinsic is not overloaded, require an exact match. If it is
617   // overloaded, require either exact or prefix match.
618   const auto MatchSize = strlen(NameTable[Idx]);
619   assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
620   bool IsExactMatch = Name.size() == MatchSize;
621   return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
622                                                      : Intrinsic::not_intrinsic;
623 }
624 
625 void Function::recalculateIntrinsicID() {
626   StringRef Name = getName();
627   if (!Name.startswith("llvm.")) {
628     HasLLVMReservedName = false;
629     IntID = Intrinsic::not_intrinsic;
630     return;
631   }
632   HasLLVMReservedName = true;
633   IntID = lookupIntrinsicID(Name);
634 }
635 
636 /// Returns a stable mangling for the type specified for use in the name
637 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
638 /// of named types is simply their name.  Manglings for unnamed types consist
639 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
640 /// combined with the mangling of their component types.  A vararg function
641 /// type will have a suffix of 'vararg'.  Since function types can contain
642 /// other function types, we close a function type mangling with suffix 'f'
643 /// which can't be confused with it's prefix.  This ensures we don't have
644 /// collisions between two unrelated function types. Otherwise, you might
645 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
646 ///
647 static std::string getMangledTypeStr(Type* Ty) {
648   std::string Result;
649   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
650     Result += "p" + utostr(PTyp->getAddressSpace()) +
651       getMangledTypeStr(PTyp->getElementType());
652   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
653     Result += "a" + utostr(ATyp->getNumElements()) +
654       getMangledTypeStr(ATyp->getElementType());
655   } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
656     if (!STyp->isLiteral()) {
657       Result += "s_";
658       Result += STyp->getName();
659     } else {
660       Result += "sl_";
661       for (auto Elem : STyp->elements())
662         Result += getMangledTypeStr(Elem);
663     }
664     // Ensure nested structs are distinguishable.
665     Result += "s";
666   } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
667     Result += "f_" + getMangledTypeStr(FT->getReturnType());
668     for (size_t i = 0; i < FT->getNumParams(); i++)
669       Result += getMangledTypeStr(FT->getParamType(i));
670     if (FT->isVarArg())
671       Result += "vararg";
672     // Ensure nested function types are distinguishable.
673     Result += "f";
674   } else if (VectorType* VTy = dyn_cast<VectorType>(Ty)) {
675     ElementCount EC = VTy->getElementCount();
676     if (EC.Scalable)
677       Result += "nx";
678     Result += "v" + utostr(EC.Min) + getMangledTypeStr(VTy->getElementType());
679   } else if (Ty) {
680     switch (Ty->getTypeID()) {
681     default: llvm_unreachable("Unhandled type");
682     case Type::VoidTyID:      Result += "isVoid";   break;
683     case Type::MetadataTyID:  Result += "Metadata"; break;
684     case Type::HalfTyID:      Result += "f16";      break;
685     case Type::BFloatTyID:    Result += "bf16";     break;
686     case Type::FloatTyID:     Result += "f32";      break;
687     case Type::DoubleTyID:    Result += "f64";      break;
688     case Type::X86_FP80TyID:  Result += "f80";      break;
689     case Type::FP128TyID:     Result += "f128";     break;
690     case Type::PPC_FP128TyID: Result += "ppcf128";  break;
691     case Type::X86_MMXTyID:   Result += "x86mmx";   break;
692     case Type::IntegerTyID:
693       Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
694       break;
695     }
696   }
697   return Result;
698 }
699 
700 StringRef Intrinsic::getName(ID id) {
701   assert(id < num_intrinsics && "Invalid intrinsic ID!");
702   assert(!Intrinsic::isOverloaded(id) &&
703          "This version of getName does not support overloading");
704   return IntrinsicNameTable[id];
705 }
706 
707 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
708   assert(id < num_intrinsics && "Invalid intrinsic ID!");
709   std::string Result(IntrinsicNameTable[id]);
710   for (Type *Ty : Tys) {
711     Result += "." + getMangledTypeStr(Ty);
712   }
713   return Result;
714 }
715 
716 /// IIT_Info - These are enumerators that describe the entries returned by the
717 /// getIntrinsicInfoTableEntries function.
718 ///
719 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
720 enum IIT_Info {
721   // Common values should be encoded with 0-15.
722   IIT_Done = 0,
723   IIT_I1   = 1,
724   IIT_I8   = 2,
725   IIT_I16  = 3,
726   IIT_I32  = 4,
727   IIT_I64  = 5,
728   IIT_F16  = 6,
729   IIT_F32  = 7,
730   IIT_F64  = 8,
731   IIT_V2   = 9,
732   IIT_V4   = 10,
733   IIT_V8   = 11,
734   IIT_V16  = 12,
735   IIT_V32  = 13,
736   IIT_PTR  = 14,
737   IIT_ARG  = 15,
738 
739   // Values from 16+ are only encodable with the inefficient encoding.
740   IIT_V64  = 16,
741   IIT_MMX  = 17,
742   IIT_TOKEN = 18,
743   IIT_METADATA = 19,
744   IIT_EMPTYSTRUCT = 20,
745   IIT_STRUCT2 = 21,
746   IIT_STRUCT3 = 22,
747   IIT_STRUCT4 = 23,
748   IIT_STRUCT5 = 24,
749   IIT_EXTEND_ARG = 25,
750   IIT_TRUNC_ARG = 26,
751   IIT_ANYPTR = 27,
752   IIT_V1   = 28,
753   IIT_VARARG = 29,
754   IIT_HALF_VEC_ARG = 30,
755   IIT_SAME_VEC_WIDTH_ARG = 31,
756   IIT_PTR_TO_ARG = 32,
757   IIT_PTR_TO_ELT = 33,
758   IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
759   IIT_I128 = 35,
760   IIT_V512 = 36,
761   IIT_V1024 = 37,
762   IIT_STRUCT6 = 38,
763   IIT_STRUCT7 = 39,
764   IIT_STRUCT8 = 40,
765   IIT_F128 = 41,
766   IIT_VEC_ELEMENT = 42,
767   IIT_SCALABLE_VEC = 43,
768   IIT_SUBDIVIDE2_ARG = 44,
769   IIT_SUBDIVIDE4_ARG = 45,
770   IIT_VEC_OF_BITCASTS_TO_INT = 46,
771   IIT_V128 = 47,
772   IIT_BF16 = 48
773 };
774 
775 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
776                       IIT_Info LastInfo,
777                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
778   using namespace Intrinsic;
779 
780   bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
781 
782   IIT_Info Info = IIT_Info(Infos[NextElt++]);
783   unsigned StructElts = 2;
784 
785   switch (Info) {
786   case IIT_Done:
787     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
788     return;
789   case IIT_VARARG:
790     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
791     return;
792   case IIT_MMX:
793     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
794     return;
795   case IIT_TOKEN:
796     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
797     return;
798   case IIT_METADATA:
799     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
800     return;
801   case IIT_F16:
802     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
803     return;
804   case IIT_BF16:
805     OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
806     return;
807   case IIT_F32:
808     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
809     return;
810   case IIT_F64:
811     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
812     return;
813   case IIT_F128:
814     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
815     return;
816   case IIT_I1:
817     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
818     return;
819   case IIT_I8:
820     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
821     return;
822   case IIT_I16:
823     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
824     return;
825   case IIT_I32:
826     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
827     return;
828   case IIT_I64:
829     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
830     return;
831   case IIT_I128:
832     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
833     return;
834   case IIT_V1:
835     OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));
836     DecodeIITType(NextElt, Infos, Info, OutputTable);
837     return;
838   case IIT_V2:
839     OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));
840     DecodeIITType(NextElt, Infos, Info, OutputTable);
841     return;
842   case IIT_V4:
843     OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));
844     DecodeIITType(NextElt, Infos, Info, OutputTable);
845     return;
846   case IIT_V8:
847     OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));
848     DecodeIITType(NextElt, Infos, Info, OutputTable);
849     return;
850   case IIT_V16:
851     OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));
852     DecodeIITType(NextElt, Infos, Info, OutputTable);
853     return;
854   case IIT_V32:
855     OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));
856     DecodeIITType(NextElt, Infos, Info, OutputTable);
857     return;
858   case IIT_V64:
859     OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));
860     DecodeIITType(NextElt, Infos, Info, OutputTable);
861     return;
862   case IIT_V128:
863     OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));
864     DecodeIITType(NextElt, Infos, Info, OutputTable);
865     return;
866   case IIT_V512:
867     OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));
868     DecodeIITType(NextElt, Infos, Info, OutputTable);
869     return;
870   case IIT_V1024:
871     OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));
872     DecodeIITType(NextElt, Infos, Info, OutputTable);
873     return;
874   case IIT_PTR:
875     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
876     DecodeIITType(NextElt, Infos, Info, OutputTable);
877     return;
878   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
879     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
880                                              Infos[NextElt++]));
881     DecodeIITType(NextElt, Infos, Info, OutputTable);
882     return;
883   }
884   case IIT_ARG: {
885     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
886     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
887     return;
888   }
889   case IIT_EXTEND_ARG: {
890     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
891     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
892                                              ArgInfo));
893     return;
894   }
895   case IIT_TRUNC_ARG: {
896     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
897     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
898                                              ArgInfo));
899     return;
900   }
901   case IIT_HALF_VEC_ARG: {
902     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
903     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
904                                              ArgInfo));
905     return;
906   }
907   case IIT_SAME_VEC_WIDTH_ARG: {
908     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
909     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
910                                              ArgInfo));
911     return;
912   }
913   case IIT_PTR_TO_ARG: {
914     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
915     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
916                                              ArgInfo));
917     return;
918   }
919   case IIT_PTR_TO_ELT: {
920     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
921     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
922     return;
923   }
924   case IIT_VEC_OF_ANYPTRS_TO_ELT: {
925     unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
926     unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
927     OutputTable.push_back(
928         IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
929     return;
930   }
931   case IIT_EMPTYSTRUCT:
932     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
933     return;
934   case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
935   case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
936   case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
937   case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
938   case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
939   case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
940   case IIT_STRUCT2: {
941     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
942 
943     for (unsigned i = 0; i != StructElts; ++i)
944       DecodeIITType(NextElt, Infos, Info, OutputTable);
945     return;
946   }
947   case IIT_SUBDIVIDE2_ARG: {
948     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
949     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,
950                                              ArgInfo));
951     return;
952   }
953   case IIT_SUBDIVIDE4_ARG: {
954     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
955     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,
956                                              ArgInfo));
957     return;
958   }
959   case IIT_VEC_ELEMENT: {
960     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
961     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
962                                              ArgInfo));
963     return;
964   }
965   case IIT_SCALABLE_VEC: {
966     DecodeIITType(NextElt, Infos, Info, OutputTable);
967     return;
968   }
969   case IIT_VEC_OF_BITCASTS_TO_INT: {
970     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
971     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
972                                              ArgInfo));
973     return;
974   }
975   }
976   llvm_unreachable("unhandled");
977 }
978 
979 #define GET_INTRINSIC_GENERATOR_GLOBAL
980 #include "llvm/IR/IntrinsicImpl.inc"
981 #undef GET_INTRINSIC_GENERATOR_GLOBAL
982 
983 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
984                                              SmallVectorImpl<IITDescriptor> &T){
985   // Check to see if the intrinsic's type was expressible by the table.
986   unsigned TableVal = IIT_Table[id-1];
987 
988   // Decode the TableVal into an array of IITValues.
989   SmallVector<unsigned char, 8> IITValues;
990   ArrayRef<unsigned char> IITEntries;
991   unsigned NextElt = 0;
992   if ((TableVal >> 31) != 0) {
993     // This is an offset into the IIT_LongEncodingTable.
994     IITEntries = IIT_LongEncodingTable;
995 
996     // Strip sentinel bit.
997     NextElt = (TableVal << 1) >> 1;
998   } else {
999     // Decode the TableVal into an array of IITValues.  If the entry was encoded
1000     // into a single word in the table itself, decode it now.
1001     do {
1002       IITValues.push_back(TableVal & 0xF);
1003       TableVal >>= 4;
1004     } while (TableVal);
1005 
1006     IITEntries = IITValues;
1007     NextElt = 0;
1008   }
1009 
1010   // Okay, decode the table into the output vector of IITDescriptors.
1011   DecodeIITType(NextElt, IITEntries, IIT_Done, T);
1012   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
1013     DecodeIITType(NextElt, IITEntries, IIT_Done, T);
1014 }
1015 
1016 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
1017                              ArrayRef<Type*> Tys, LLVMContext &Context) {
1018   using namespace Intrinsic;
1019 
1020   IITDescriptor D = Infos.front();
1021   Infos = Infos.slice(1);
1022 
1023   switch (D.Kind) {
1024   case IITDescriptor::Void: return Type::getVoidTy(Context);
1025   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
1026   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
1027   case IITDescriptor::Token: return Type::getTokenTy(Context);
1028   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
1029   case IITDescriptor::Half: return Type::getHalfTy(Context);
1030   case IITDescriptor::BFloat: return Type::getBFloatTy(Context);
1031   case IITDescriptor::Float: return Type::getFloatTy(Context);
1032   case IITDescriptor::Double: return Type::getDoubleTy(Context);
1033   case IITDescriptor::Quad: return Type::getFP128Ty(Context);
1034 
1035   case IITDescriptor::Integer:
1036     return IntegerType::get(Context, D.Integer_Width);
1037   case IITDescriptor::Vector:
1038     return VectorType::get(DecodeFixedType(Infos, Tys, Context),
1039                            D.Vector_Width);
1040   case IITDescriptor::Pointer:
1041     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
1042                             D.Pointer_AddressSpace);
1043   case IITDescriptor::Struct: {
1044     SmallVector<Type *, 8> Elts;
1045     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1046       Elts.push_back(DecodeFixedType(Infos, Tys, Context));
1047     return StructType::get(Context, Elts);
1048   }
1049   case IITDescriptor::Argument:
1050     return Tys[D.getArgumentNumber()];
1051   case IITDescriptor::ExtendArgument: {
1052     Type *Ty = Tys[D.getArgumentNumber()];
1053     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1054       return VectorType::getExtendedElementVectorType(VTy);
1055 
1056     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
1057   }
1058   case IITDescriptor::TruncArgument: {
1059     Type *Ty = Tys[D.getArgumentNumber()];
1060     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1061       return VectorType::getTruncatedElementVectorType(VTy);
1062 
1063     IntegerType *ITy = cast<IntegerType>(Ty);
1064     assert(ITy->getBitWidth() % 2 == 0);
1065     return IntegerType::get(Context, ITy->getBitWidth() / 2);
1066   }
1067   case IITDescriptor::Subdivide2Argument:
1068   case IITDescriptor::Subdivide4Argument: {
1069     Type *Ty = Tys[D.getArgumentNumber()];
1070     VectorType *VTy = dyn_cast<VectorType>(Ty);
1071     assert(VTy && "Expected an argument of Vector Type");
1072     int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1073     return VectorType::getSubdividedVectorType(VTy, SubDivs);
1074   }
1075   case IITDescriptor::HalfVecArgument:
1076     return VectorType::getHalfElementsVectorType(cast<VectorType>(
1077                                                   Tys[D.getArgumentNumber()]));
1078   case IITDescriptor::SameVecWidthArgument: {
1079     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
1080     Type *Ty = Tys[D.getArgumentNumber()];
1081     if (auto *VTy = dyn_cast<VectorType>(Ty))
1082       return VectorType::get(EltTy, VTy->getElementCount());
1083     return EltTy;
1084   }
1085   case IITDescriptor::PtrToArgument: {
1086     Type *Ty = Tys[D.getArgumentNumber()];
1087     return PointerType::getUnqual(Ty);
1088   }
1089   case IITDescriptor::PtrToElt: {
1090     Type *Ty = Tys[D.getArgumentNumber()];
1091     VectorType *VTy = dyn_cast<VectorType>(Ty);
1092     if (!VTy)
1093       llvm_unreachable("Expected an argument of Vector Type");
1094     Type *EltTy = VTy->getElementType();
1095     return PointerType::getUnqual(EltTy);
1096   }
1097   case IITDescriptor::VecElementArgument: {
1098     Type *Ty = Tys[D.getArgumentNumber()];
1099     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1100       return VTy->getElementType();
1101     llvm_unreachable("Expected an argument of Vector Type");
1102   }
1103   case IITDescriptor::VecOfBitcastsToInt: {
1104     Type *Ty = Tys[D.getArgumentNumber()];
1105     VectorType *VTy = dyn_cast<VectorType>(Ty);
1106     assert(VTy && "Expected an argument of Vector Type");
1107     return VectorType::getInteger(VTy);
1108   }
1109   case IITDescriptor::VecOfAnyPtrsToElt:
1110     // Return the overloaded type (which determines the pointers address space)
1111     return Tys[D.getOverloadArgNumber()];
1112   }
1113   llvm_unreachable("unhandled");
1114 }
1115 
1116 FunctionType *Intrinsic::getType(LLVMContext &Context,
1117                                  ID id, ArrayRef<Type*> Tys) {
1118   SmallVector<IITDescriptor, 8> Table;
1119   getIntrinsicInfoTableEntries(id, Table);
1120 
1121   ArrayRef<IITDescriptor> TableRef = Table;
1122   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
1123 
1124   SmallVector<Type*, 8> ArgTys;
1125   while (!TableRef.empty())
1126     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
1127 
1128   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
1129   // If we see void type as the type of the last argument, it is vararg intrinsic
1130   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
1131     ArgTys.pop_back();
1132     return FunctionType::get(ResultTy, ArgTys, true);
1133   }
1134   return FunctionType::get(ResultTy, ArgTys, false);
1135 }
1136 
1137 bool Intrinsic::isOverloaded(ID id) {
1138 #define GET_INTRINSIC_OVERLOAD_TABLE
1139 #include "llvm/IR/IntrinsicImpl.inc"
1140 #undef GET_INTRINSIC_OVERLOAD_TABLE
1141 }
1142 
1143 bool Intrinsic::isLeaf(ID id) {
1144   switch (id) {
1145   default:
1146     return true;
1147 
1148   case Intrinsic::experimental_gc_statepoint:
1149   case Intrinsic::experimental_patchpoint_void:
1150   case Intrinsic::experimental_patchpoint_i64:
1151     return false;
1152   }
1153 }
1154 
1155 /// This defines the "Intrinsic::getAttributes(ID id)" method.
1156 #define GET_INTRINSIC_ATTRIBUTES
1157 #include "llvm/IR/IntrinsicImpl.inc"
1158 #undef GET_INTRINSIC_ATTRIBUTES
1159 
1160 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
1161   // There can never be multiple globals with the same name of different types,
1162   // because intrinsics must be a specific type.
1163   return cast<Function>(
1164       M->getOrInsertFunction(getName(id, Tys),
1165                              getType(M->getContext(), id, Tys))
1166           .getCallee());
1167 }
1168 
1169 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
1170 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1171 #include "llvm/IR/IntrinsicImpl.inc"
1172 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1173 
1174 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
1175 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1176 #include "llvm/IR/IntrinsicImpl.inc"
1177 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1178 
1179 using DeferredIntrinsicMatchPair =
1180     std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
1181 
1182 static bool matchIntrinsicType(
1183     Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
1184     SmallVectorImpl<Type *> &ArgTys,
1185     SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
1186     bool IsDeferredCheck) {
1187   using namespace Intrinsic;
1188 
1189   // If we ran out of descriptors, there are too many arguments.
1190   if (Infos.empty()) return true;
1191 
1192   // Do this before slicing off the 'front' part
1193   auto InfosRef = Infos;
1194   auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
1195     DeferredChecks.emplace_back(T, InfosRef);
1196     return false;
1197   };
1198 
1199   IITDescriptor D = Infos.front();
1200   Infos = Infos.slice(1);
1201 
1202   switch (D.Kind) {
1203     case IITDescriptor::Void: return !Ty->isVoidTy();
1204     case IITDescriptor::VarArg: return true;
1205     case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
1206     case IITDescriptor::Token: return !Ty->isTokenTy();
1207     case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1208     case IITDescriptor::Half: return !Ty->isHalfTy();
1209     case IITDescriptor::BFloat: return !Ty->isBFloatTy();
1210     case IITDescriptor::Float: return !Ty->isFloatTy();
1211     case IITDescriptor::Double: return !Ty->isDoubleTy();
1212     case IITDescriptor::Quad: return !Ty->isFP128Ty();
1213     case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1214     case IITDescriptor::Vector: {
1215       VectorType *VT = dyn_cast<VectorType>(Ty);
1216       return !VT || VT->getElementCount() != D.Vector_Width ||
1217              matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
1218                                 DeferredChecks, IsDeferredCheck);
1219     }
1220     case IITDescriptor::Pointer: {
1221       PointerType *PT = dyn_cast<PointerType>(Ty);
1222       return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1223              matchIntrinsicType(PT->getElementType(), Infos, ArgTys,
1224                                 DeferredChecks, IsDeferredCheck);
1225     }
1226 
1227     case IITDescriptor::Struct: {
1228       StructType *ST = dyn_cast<StructType>(Ty);
1229       if (!ST || ST->getNumElements() != D.Struct_NumElements)
1230         return true;
1231 
1232       for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1233         if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
1234                                DeferredChecks, IsDeferredCheck))
1235           return true;
1236       return false;
1237     }
1238 
1239     case IITDescriptor::Argument:
1240       // If this is the second occurrence of an argument,
1241       // verify that the later instance matches the previous instance.
1242       if (D.getArgumentNumber() < ArgTys.size())
1243         return Ty != ArgTys[D.getArgumentNumber()];
1244 
1245       if (D.getArgumentNumber() > ArgTys.size() ||
1246           D.getArgumentKind() == IITDescriptor::AK_MatchType)
1247         return IsDeferredCheck || DeferCheck(Ty);
1248 
1249       assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
1250              "Table consistency error");
1251       ArgTys.push_back(Ty);
1252 
1253       switch (D.getArgumentKind()) {
1254         case IITDescriptor::AK_Any:        return false; // Success
1255         case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1256         case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
1257         case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
1258         case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1259         default:                           break;
1260       }
1261       llvm_unreachable("all argument kinds not covered");
1262 
1263     case IITDescriptor::ExtendArgument: {
1264       // If this is a forward reference, defer the check for later.
1265       if (D.getArgumentNumber() >= ArgTys.size())
1266         return IsDeferredCheck || DeferCheck(Ty);
1267 
1268       Type *NewTy = ArgTys[D.getArgumentNumber()];
1269       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1270         NewTy = VectorType::getExtendedElementVectorType(VTy);
1271       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1272         NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
1273       else
1274         return true;
1275 
1276       return Ty != NewTy;
1277     }
1278     case IITDescriptor::TruncArgument: {
1279       // If this is a forward reference, defer the check for later.
1280       if (D.getArgumentNumber() >= ArgTys.size())
1281         return IsDeferredCheck || DeferCheck(Ty);
1282 
1283       Type *NewTy = ArgTys[D.getArgumentNumber()];
1284       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1285         NewTy = VectorType::getTruncatedElementVectorType(VTy);
1286       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1287         NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
1288       else
1289         return true;
1290 
1291       return Ty != NewTy;
1292     }
1293     case IITDescriptor::HalfVecArgument:
1294       // If this is a forward reference, defer the check for later.
1295       if (D.getArgumentNumber() >= ArgTys.size())
1296         return IsDeferredCheck || DeferCheck(Ty);
1297       return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1298              VectorType::getHalfElementsVectorType(
1299                      cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1300     case IITDescriptor::SameVecWidthArgument: {
1301       if (D.getArgumentNumber() >= ArgTys.size()) {
1302         // Defer check and subsequent check for the vector element type.
1303         Infos = Infos.slice(1);
1304         return IsDeferredCheck || DeferCheck(Ty);
1305       }
1306       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1307       auto *ThisArgType = dyn_cast<VectorType>(Ty);
1308       // Both must be vectors of the same number of elements or neither.
1309       if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
1310         return true;
1311       Type *EltTy = Ty;
1312       if (ThisArgType) {
1313         if (ReferenceType->getElementCount() !=
1314             ThisArgType->getElementCount())
1315           return true;
1316         EltTy = ThisArgType->getElementType();
1317       }
1318       return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
1319                                 IsDeferredCheck);
1320     }
1321     case IITDescriptor::PtrToArgument: {
1322       if (D.getArgumentNumber() >= ArgTys.size())
1323         return IsDeferredCheck || DeferCheck(Ty);
1324       Type * ReferenceType = ArgTys[D.getArgumentNumber()];
1325       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1326       return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
1327     }
1328     case IITDescriptor::PtrToElt: {
1329       if (D.getArgumentNumber() >= ArgTys.size())
1330         return IsDeferredCheck || DeferCheck(Ty);
1331       VectorType * ReferenceType =
1332         dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
1333       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1334 
1335       return (!ThisArgType || !ReferenceType ||
1336               ThisArgType->getElementType() != ReferenceType->getElementType());
1337     }
1338     case IITDescriptor::VecOfAnyPtrsToElt: {
1339       unsigned RefArgNumber = D.getRefArgNumber();
1340       if (RefArgNumber >= ArgTys.size()) {
1341         if (IsDeferredCheck)
1342           return true;
1343         // If forward referencing, already add the pointer-vector type and
1344         // defer the checks for later.
1345         ArgTys.push_back(Ty);
1346         return DeferCheck(Ty);
1347       }
1348 
1349       if (!IsDeferredCheck){
1350         assert(D.getOverloadArgNumber() == ArgTys.size() &&
1351                "Table consistency error");
1352         ArgTys.push_back(Ty);
1353       }
1354 
1355       // Verify the overloaded type "matches" the Ref type.
1356       // i.e. Ty is a vector with the same width as Ref.
1357       // Composed of pointers to the same element type as Ref.
1358       VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
1359       VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1360       if (!ThisArgVecTy || !ReferenceType ||
1361           (ReferenceType->getNumElements() != ThisArgVecTy->getNumElements()))
1362         return true;
1363       PointerType *ThisArgEltTy =
1364           dyn_cast<PointerType>(ThisArgVecTy->getElementType());
1365       if (!ThisArgEltTy)
1366         return true;
1367       return ThisArgEltTy->getElementType() != ReferenceType->getElementType();
1368     }
1369     case IITDescriptor::VecElementArgument: {
1370       if (D.getArgumentNumber() >= ArgTys.size())
1371         return IsDeferredCheck ? true : DeferCheck(Ty);
1372       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1373       return !ReferenceType || Ty != ReferenceType->getElementType();
1374     }
1375     case IITDescriptor::Subdivide2Argument:
1376     case IITDescriptor::Subdivide4Argument: {
1377       // If this is a forward reference, defer the check for later.
1378       if (D.getArgumentNumber() >= ArgTys.size())
1379         return IsDeferredCheck || DeferCheck(Ty);
1380 
1381       Type *NewTy = ArgTys[D.getArgumentNumber()];
1382       if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
1383         int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1384         NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
1385         return Ty != NewTy;
1386       }
1387       return true;
1388     }
1389     case IITDescriptor::VecOfBitcastsToInt: {
1390       if (D.getArgumentNumber() >= ArgTys.size())
1391         return IsDeferredCheck || DeferCheck(Ty);
1392       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1393       auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1394       if (!ThisArgVecTy || !ReferenceType)
1395         return true;
1396       return ThisArgVecTy != VectorType::getInteger(ReferenceType);
1397     }
1398   }
1399   llvm_unreachable("unhandled");
1400 }
1401 
1402 Intrinsic::MatchIntrinsicTypesResult
1403 Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
1404                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
1405                                    SmallVectorImpl<Type *> &ArgTys) {
1406   SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
1407   if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
1408                          false))
1409     return MatchIntrinsicTypes_NoMatchRet;
1410 
1411   unsigned NumDeferredReturnChecks = DeferredChecks.size();
1412 
1413   for (auto Ty : FTy->params())
1414     if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
1415       return MatchIntrinsicTypes_NoMatchArg;
1416 
1417   for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
1418     DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
1419     if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
1420                            true))
1421       return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
1422                                          : MatchIntrinsicTypes_NoMatchArg;
1423   }
1424 
1425   return MatchIntrinsicTypes_Match;
1426 }
1427 
1428 bool
1429 Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1430                                 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1431   // If there are no descriptors left, then it can't be a vararg.
1432   if (Infos.empty())
1433     return isVarArg;
1434 
1435   // There should be only one descriptor remaining at this point.
1436   if (Infos.size() != 1)
1437     return true;
1438 
1439   // Check and verify the descriptor.
1440   IITDescriptor D = Infos.front();
1441   Infos = Infos.slice(1);
1442   if (D.Kind == IITDescriptor::VarArg)
1443     return !isVarArg;
1444 
1445   return true;
1446 }
1447 
1448 bool Intrinsic::getIntrinsicSignature(Function *F,
1449                                       SmallVectorImpl<Type *> &ArgTys) {
1450   Intrinsic::ID ID = F->getIntrinsicID();
1451   if (!ID)
1452     return false;
1453 
1454   SmallVector<Intrinsic::IITDescriptor, 8> Table;
1455   getIntrinsicInfoTableEntries(ID, Table);
1456   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1457 
1458   if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef,
1459                                          ArgTys) !=
1460       Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {
1461     return false;
1462   }
1463   if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(),
1464                                       TableRef))
1465     return false;
1466   return true;
1467 }
1468 
1469 Optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {
1470   SmallVector<Type *, 4> ArgTys;
1471   if (!getIntrinsicSignature(F, ArgTys))
1472     return None;
1473 
1474   Intrinsic::ID ID = F->getIntrinsicID();
1475   StringRef Name = F->getName();
1476   if (Name == Intrinsic::getName(ID, ArgTys))
1477     return None;
1478 
1479   auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
1480   NewDecl->setCallingConv(F->getCallingConv());
1481   assert(NewDecl->getFunctionType() == F->getFunctionType() &&
1482          "Shouldn't change the signature");
1483   return NewDecl;
1484 }
1485 
1486 /// hasAddressTaken - returns true if there are any uses of this function
1487 /// other than direct calls or invokes to it.
1488 bool Function::hasAddressTaken(const User* *PutOffender) const {
1489   for (const Use &U : uses()) {
1490     const User *FU = U.getUser();
1491     if (isa<BlockAddress>(FU))
1492       continue;
1493     const auto *Call = dyn_cast<CallBase>(FU);
1494     if (!Call) {
1495       if (PutOffender)
1496         *PutOffender = FU;
1497       return true;
1498     }
1499     if (!Call->isCallee(&U)) {
1500       if (PutOffender)
1501         *PutOffender = FU;
1502       return true;
1503     }
1504   }
1505   return false;
1506 }
1507 
1508 bool Function::isDefTriviallyDead() const {
1509   // Check the linkage
1510   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1511       !hasAvailableExternallyLinkage())
1512     return false;
1513 
1514   // Check if the function is used by anything other than a blockaddress.
1515   for (const User *U : users())
1516     if (!isa<BlockAddress>(U))
1517       return false;
1518 
1519   return true;
1520 }
1521 
1522 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1523 /// setjmp or other function that gcc recognizes as "returning twice".
1524 bool Function::callsFunctionThatReturnsTwice() const {
1525   for (const Instruction &I : instructions(this))
1526     if (const auto *Call = dyn_cast<CallBase>(&I))
1527       if (Call->hasFnAttr(Attribute::ReturnsTwice))
1528         return true;
1529 
1530   return false;
1531 }
1532 
1533 Constant *Function::getPersonalityFn() const {
1534   assert(hasPersonalityFn() && getNumOperands());
1535   return cast<Constant>(Op<0>());
1536 }
1537 
1538 void Function::setPersonalityFn(Constant *Fn) {
1539   setHungoffOperand<0>(Fn);
1540   setValueSubclassDataBit(3, Fn != nullptr);
1541 }
1542 
1543 Constant *Function::getPrefixData() const {
1544   assert(hasPrefixData() && getNumOperands());
1545   return cast<Constant>(Op<1>());
1546 }
1547 
1548 void Function::setPrefixData(Constant *PrefixData) {
1549   setHungoffOperand<1>(PrefixData);
1550   setValueSubclassDataBit(1, PrefixData != nullptr);
1551 }
1552 
1553 Constant *Function::getPrologueData() const {
1554   assert(hasPrologueData() && getNumOperands());
1555   return cast<Constant>(Op<2>());
1556 }
1557 
1558 void Function::setPrologueData(Constant *PrologueData) {
1559   setHungoffOperand<2>(PrologueData);
1560   setValueSubclassDataBit(2, PrologueData != nullptr);
1561 }
1562 
1563 void Function::allocHungoffUselist() {
1564   // If we've already allocated a uselist, stop here.
1565   if (getNumOperands())
1566     return;
1567 
1568   allocHungoffUses(3, /*IsPhi=*/ false);
1569   setNumHungOffUseOperands(3);
1570 
1571   // Initialize the uselist with placeholder operands to allow traversal.
1572   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
1573   Op<0>().set(CPN);
1574   Op<1>().set(CPN);
1575   Op<2>().set(CPN);
1576 }
1577 
1578 template <int Idx>
1579 void Function::setHungoffOperand(Constant *C) {
1580   if (C) {
1581     allocHungoffUselist();
1582     Op<Idx>().set(C);
1583   } else if (getNumOperands()) {
1584     Op<Idx>().set(
1585         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
1586   }
1587 }
1588 
1589 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1590   assert(Bit < 16 && "SubclassData contains only 16 bits");
1591   if (On)
1592     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1593   else
1594     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1595 }
1596 
1597 void Function::setEntryCount(ProfileCount Count,
1598                              const DenseSet<GlobalValue::GUID> *S) {
1599   assert(Count.hasValue());
1600 #if !defined(NDEBUG)
1601   auto PrevCount = getEntryCount();
1602   assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType());
1603 #endif
1604 
1605   auto ImportGUIDs = getImportGUIDs();
1606   if (S == nullptr && ImportGUIDs.size())
1607     S = &ImportGUIDs;
1608 
1609   MDBuilder MDB(getContext());
1610   setMetadata(
1611       LLVMContext::MD_prof,
1612       MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
1613 }
1614 
1615 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
1616                              const DenseSet<GlobalValue::GUID> *Imports) {
1617   setEntryCount(ProfileCount(Count, Type), Imports);
1618 }
1619 
1620 ProfileCount Function::getEntryCount(bool AllowSynthetic) const {
1621   MDNode *MD = getMetadata(LLVMContext::MD_prof);
1622   if (MD && MD->getOperand(0))
1623     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
1624       if (MDS->getString().equals("function_entry_count")) {
1625         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1626         uint64_t Count = CI->getValue().getZExtValue();
1627         // A value of -1 is used for SamplePGO when there were no samples.
1628         // Treat this the same as unknown.
1629         if (Count == (uint64_t)-1)
1630           return ProfileCount::getInvalid();
1631         return ProfileCount(Count, PCT_Real);
1632       } else if (AllowSynthetic &&
1633                  MDS->getString().equals("synthetic_function_entry_count")) {
1634         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1635         uint64_t Count = CI->getValue().getZExtValue();
1636         return ProfileCount(Count, PCT_Synthetic);
1637       }
1638     }
1639   return ProfileCount::getInvalid();
1640 }
1641 
1642 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
1643   DenseSet<GlobalValue::GUID> R;
1644   if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1645     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1646       if (MDS->getString().equals("function_entry_count"))
1647         for (unsigned i = 2; i < MD->getNumOperands(); i++)
1648           R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
1649                        ->getValue()
1650                        .getZExtValue());
1651   return R;
1652 }
1653 
1654 void Function::setSectionPrefix(StringRef Prefix) {
1655   MDBuilder MDB(getContext());
1656   setMetadata(LLVMContext::MD_section_prefix,
1657               MDB.createFunctionSectionPrefix(Prefix));
1658 }
1659 
1660 Optional<StringRef> Function::getSectionPrefix() const {
1661   if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
1662     assert(cast<MDString>(MD->getOperand(0))
1663                ->getString()
1664                .equals("function_section_prefix") &&
1665            "Metadata not match");
1666     return cast<MDString>(MD->getOperand(1))->getString();
1667   }
1668   return None;
1669 }
1670 
1671 bool Function::nullPointerIsDefined() const {
1672   return hasFnAttribute(Attribute::NullPointerIsValid);
1673 }
1674 
1675 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
1676   if (F && F->nullPointerIsDefined())
1677     return true;
1678 
1679   if (AS != 0)
1680     return true;
1681 
1682   return false;
1683 }
1684