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