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