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