xref: /llvm-project/llvm/lib/IR/Function.cpp (revision 413577a8790407d75ba834fa5668c2632fe1851e)
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 };
839 
840 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
841                       IIT_Info LastInfo,
842                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
843   using namespace Intrinsic;
844 
845   bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
846 
847   IIT_Info Info = IIT_Info(Infos[NextElt++]);
848   unsigned StructElts = 2;
849 
850   switch (Info) {
851   case IIT_Done:
852     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
853     return;
854   case IIT_VARARG:
855     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
856     return;
857   case IIT_MMX:
858     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
859     return;
860   case IIT_TOKEN:
861     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
862     return;
863   case IIT_METADATA:
864     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
865     return;
866   case IIT_F16:
867     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
868     return;
869   case IIT_BF16:
870     OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
871     return;
872   case IIT_F32:
873     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
874     return;
875   case IIT_F64:
876     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
877     return;
878   case IIT_F128:
879     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
880     return;
881   case IIT_I1:
882     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
883     return;
884   case IIT_I8:
885     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
886     return;
887   case IIT_I16:
888     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
889     return;
890   case IIT_I32:
891     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
892     return;
893   case IIT_I64:
894     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
895     return;
896   case IIT_I128:
897     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
898     return;
899   case IIT_V1:
900     OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));
901     DecodeIITType(NextElt, Infos, Info, OutputTable);
902     return;
903   case IIT_V2:
904     OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));
905     DecodeIITType(NextElt, Infos, Info, OutputTable);
906     return;
907   case IIT_V4:
908     OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));
909     DecodeIITType(NextElt, Infos, Info, OutputTable);
910     return;
911   case IIT_V8:
912     OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));
913     DecodeIITType(NextElt, Infos, Info, OutputTable);
914     return;
915   case IIT_V16:
916     OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));
917     DecodeIITType(NextElt, Infos, Info, OutputTable);
918     return;
919   case IIT_V32:
920     OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));
921     DecodeIITType(NextElt, Infos, Info, OutputTable);
922     return;
923   case IIT_V64:
924     OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));
925     DecodeIITType(NextElt, Infos, Info, OutputTable);
926     return;
927   case IIT_V128:
928     OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));
929     DecodeIITType(NextElt, Infos, Info, OutputTable);
930     return;
931   case IIT_V512:
932     OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));
933     DecodeIITType(NextElt, Infos, Info, OutputTable);
934     return;
935   case IIT_V1024:
936     OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));
937     DecodeIITType(NextElt, Infos, Info, OutputTable);
938     return;
939   case IIT_PTR:
940     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
941     DecodeIITType(NextElt, Infos, Info, OutputTable);
942     return;
943   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
944     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
945                                              Infos[NextElt++]));
946     DecodeIITType(NextElt, Infos, Info, OutputTable);
947     return;
948   }
949   case IIT_ARG: {
950     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
951     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
952     return;
953   }
954   case IIT_EXTEND_ARG: {
955     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
956     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
957                                              ArgInfo));
958     return;
959   }
960   case IIT_TRUNC_ARG: {
961     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
962     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
963                                              ArgInfo));
964     return;
965   }
966   case IIT_HALF_VEC_ARG: {
967     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
968     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
969                                              ArgInfo));
970     return;
971   }
972   case IIT_SAME_VEC_WIDTH_ARG: {
973     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
974     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
975                                              ArgInfo));
976     return;
977   }
978   case IIT_PTR_TO_ARG: {
979     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
980     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
981                                              ArgInfo));
982     return;
983   }
984   case IIT_PTR_TO_ELT: {
985     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
986     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
987     return;
988   }
989   case IIT_VEC_OF_ANYPTRS_TO_ELT: {
990     unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
991     unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
992     OutputTable.push_back(
993         IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
994     return;
995   }
996   case IIT_EMPTYSTRUCT:
997     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
998     return;
999   case IIT_STRUCT9: ++StructElts; LLVM_FALLTHROUGH;
1000   case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
1001   case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
1002   case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
1003   case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
1004   case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
1005   case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
1006   case IIT_STRUCT2: {
1007     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
1008 
1009     for (unsigned i = 0; i != StructElts; ++i)
1010       DecodeIITType(NextElt, Infos, Info, OutputTable);
1011     return;
1012   }
1013   case IIT_SUBDIVIDE2_ARG: {
1014     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1015     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,
1016                                              ArgInfo));
1017     return;
1018   }
1019   case IIT_SUBDIVIDE4_ARG: {
1020     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1021     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,
1022                                              ArgInfo));
1023     return;
1024   }
1025   case IIT_VEC_ELEMENT: {
1026     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1027     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
1028                                              ArgInfo));
1029     return;
1030   }
1031   case IIT_SCALABLE_VEC: {
1032     DecodeIITType(NextElt, Infos, Info, OutputTable);
1033     return;
1034   }
1035   case IIT_VEC_OF_BITCASTS_TO_INT: {
1036     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1037     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
1038                                              ArgInfo));
1039     return;
1040   }
1041   }
1042   llvm_unreachable("unhandled");
1043 }
1044 
1045 #define GET_INTRINSIC_GENERATOR_GLOBAL
1046 #include "llvm/IR/IntrinsicImpl.inc"
1047 #undef GET_INTRINSIC_GENERATOR_GLOBAL
1048 
1049 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
1050                                              SmallVectorImpl<IITDescriptor> &T){
1051   // Check to see if the intrinsic's type was expressible by the table.
1052   unsigned TableVal = IIT_Table[id-1];
1053 
1054   // Decode the TableVal into an array of IITValues.
1055   SmallVector<unsigned char, 8> IITValues;
1056   ArrayRef<unsigned char> IITEntries;
1057   unsigned NextElt = 0;
1058   if ((TableVal >> 31) != 0) {
1059     // This is an offset into the IIT_LongEncodingTable.
1060     IITEntries = IIT_LongEncodingTable;
1061 
1062     // Strip sentinel bit.
1063     NextElt = (TableVal << 1) >> 1;
1064   } else {
1065     // Decode the TableVal into an array of IITValues.  If the entry was encoded
1066     // into a single word in the table itself, decode it now.
1067     do {
1068       IITValues.push_back(TableVal & 0xF);
1069       TableVal >>= 4;
1070     } while (TableVal);
1071 
1072     IITEntries = IITValues;
1073     NextElt = 0;
1074   }
1075 
1076   // Okay, decode the table into the output vector of IITDescriptors.
1077   DecodeIITType(NextElt, IITEntries, IIT_Done, T);
1078   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
1079     DecodeIITType(NextElt, IITEntries, IIT_Done, T);
1080 }
1081 
1082 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
1083                              ArrayRef<Type*> Tys, LLVMContext &Context) {
1084   using namespace Intrinsic;
1085 
1086   IITDescriptor D = Infos.front();
1087   Infos = Infos.slice(1);
1088 
1089   switch (D.Kind) {
1090   case IITDescriptor::Void: return Type::getVoidTy(Context);
1091   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
1092   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
1093   case IITDescriptor::Token: return Type::getTokenTy(Context);
1094   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
1095   case IITDescriptor::Half: return Type::getHalfTy(Context);
1096   case IITDescriptor::BFloat: return Type::getBFloatTy(Context);
1097   case IITDescriptor::Float: return Type::getFloatTy(Context);
1098   case IITDescriptor::Double: return Type::getDoubleTy(Context);
1099   case IITDescriptor::Quad: return Type::getFP128Ty(Context);
1100 
1101   case IITDescriptor::Integer:
1102     return IntegerType::get(Context, D.Integer_Width);
1103   case IITDescriptor::Vector:
1104     return VectorType::get(DecodeFixedType(Infos, Tys, Context),
1105                            D.Vector_Width);
1106   case IITDescriptor::Pointer:
1107     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
1108                             D.Pointer_AddressSpace);
1109   case IITDescriptor::Struct: {
1110     SmallVector<Type *, 8> Elts;
1111     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1112       Elts.push_back(DecodeFixedType(Infos, Tys, Context));
1113     return StructType::get(Context, Elts);
1114   }
1115   case IITDescriptor::Argument:
1116     return Tys[D.getArgumentNumber()];
1117   case IITDescriptor::ExtendArgument: {
1118     Type *Ty = Tys[D.getArgumentNumber()];
1119     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1120       return VectorType::getExtendedElementVectorType(VTy);
1121 
1122     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
1123   }
1124   case IITDescriptor::TruncArgument: {
1125     Type *Ty = Tys[D.getArgumentNumber()];
1126     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1127       return VectorType::getTruncatedElementVectorType(VTy);
1128 
1129     IntegerType *ITy = cast<IntegerType>(Ty);
1130     assert(ITy->getBitWidth() % 2 == 0);
1131     return IntegerType::get(Context, ITy->getBitWidth() / 2);
1132   }
1133   case IITDescriptor::Subdivide2Argument:
1134   case IITDescriptor::Subdivide4Argument: {
1135     Type *Ty = Tys[D.getArgumentNumber()];
1136     VectorType *VTy = dyn_cast<VectorType>(Ty);
1137     assert(VTy && "Expected an argument of Vector Type");
1138     int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1139     return VectorType::getSubdividedVectorType(VTy, SubDivs);
1140   }
1141   case IITDescriptor::HalfVecArgument:
1142     return VectorType::getHalfElementsVectorType(cast<VectorType>(
1143                                                   Tys[D.getArgumentNumber()]));
1144   case IITDescriptor::SameVecWidthArgument: {
1145     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
1146     Type *Ty = Tys[D.getArgumentNumber()];
1147     if (auto *VTy = dyn_cast<VectorType>(Ty))
1148       return VectorType::get(EltTy, VTy->getElementCount());
1149     return EltTy;
1150   }
1151   case IITDescriptor::PtrToArgument: {
1152     Type *Ty = Tys[D.getArgumentNumber()];
1153     return PointerType::getUnqual(Ty);
1154   }
1155   case IITDescriptor::PtrToElt: {
1156     Type *Ty = Tys[D.getArgumentNumber()];
1157     VectorType *VTy = dyn_cast<VectorType>(Ty);
1158     if (!VTy)
1159       llvm_unreachable("Expected an argument of Vector Type");
1160     Type *EltTy = VTy->getElementType();
1161     return PointerType::getUnqual(EltTy);
1162   }
1163   case IITDescriptor::VecElementArgument: {
1164     Type *Ty = Tys[D.getArgumentNumber()];
1165     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1166       return VTy->getElementType();
1167     llvm_unreachable("Expected an argument of Vector Type");
1168   }
1169   case IITDescriptor::VecOfBitcastsToInt: {
1170     Type *Ty = Tys[D.getArgumentNumber()];
1171     VectorType *VTy = dyn_cast<VectorType>(Ty);
1172     assert(VTy && "Expected an argument of Vector Type");
1173     return VectorType::getInteger(VTy);
1174   }
1175   case IITDescriptor::VecOfAnyPtrsToElt:
1176     // Return the overloaded type (which determines the pointers address space)
1177     return Tys[D.getOverloadArgNumber()];
1178   }
1179   llvm_unreachable("unhandled");
1180 }
1181 
1182 FunctionType *Intrinsic::getType(LLVMContext &Context,
1183                                  ID id, ArrayRef<Type*> Tys) {
1184   SmallVector<IITDescriptor, 8> Table;
1185   getIntrinsicInfoTableEntries(id, Table);
1186 
1187   ArrayRef<IITDescriptor> TableRef = Table;
1188   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
1189 
1190   SmallVector<Type*, 8> ArgTys;
1191   while (!TableRef.empty())
1192     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
1193 
1194   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
1195   // If we see void type as the type of the last argument, it is vararg intrinsic
1196   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
1197     ArgTys.pop_back();
1198     return FunctionType::get(ResultTy, ArgTys, true);
1199   }
1200   return FunctionType::get(ResultTy, ArgTys, false);
1201 }
1202 
1203 bool Intrinsic::isOverloaded(ID id) {
1204 #define GET_INTRINSIC_OVERLOAD_TABLE
1205 #include "llvm/IR/IntrinsicImpl.inc"
1206 #undef GET_INTRINSIC_OVERLOAD_TABLE
1207 }
1208 
1209 bool Intrinsic::isLeaf(ID id) {
1210   switch (id) {
1211   default:
1212     return true;
1213 
1214   case Intrinsic::experimental_gc_statepoint:
1215   case Intrinsic::experimental_patchpoint_void:
1216   case Intrinsic::experimental_patchpoint_i64:
1217     return false;
1218   }
1219 }
1220 
1221 /// This defines the "Intrinsic::getAttributes(ID id)" method.
1222 #define GET_INTRINSIC_ATTRIBUTES
1223 #include "llvm/IR/IntrinsicImpl.inc"
1224 #undef GET_INTRINSIC_ATTRIBUTES
1225 
1226 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
1227   // There can never be multiple globals with the same name of different types,
1228   // because intrinsics must be a specific type.
1229   return cast<Function>(
1230       M->getOrInsertFunction(getName(id, Tys),
1231                              getType(M->getContext(), id, Tys))
1232           .getCallee());
1233 }
1234 
1235 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
1236 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1237 #include "llvm/IR/IntrinsicImpl.inc"
1238 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1239 
1240 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
1241 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1242 #include "llvm/IR/IntrinsicImpl.inc"
1243 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1244 
1245 using DeferredIntrinsicMatchPair =
1246     std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
1247 
1248 static bool matchIntrinsicType(
1249     Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
1250     SmallVectorImpl<Type *> &ArgTys,
1251     SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
1252     bool IsDeferredCheck) {
1253   using namespace Intrinsic;
1254 
1255   // If we ran out of descriptors, there are too many arguments.
1256   if (Infos.empty()) return true;
1257 
1258   // Do this before slicing off the 'front' part
1259   auto InfosRef = Infos;
1260   auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
1261     DeferredChecks.emplace_back(T, InfosRef);
1262     return false;
1263   };
1264 
1265   IITDescriptor D = Infos.front();
1266   Infos = Infos.slice(1);
1267 
1268   switch (D.Kind) {
1269     case IITDescriptor::Void: return !Ty->isVoidTy();
1270     case IITDescriptor::VarArg: return true;
1271     case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
1272     case IITDescriptor::Token: return !Ty->isTokenTy();
1273     case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1274     case IITDescriptor::Half: return !Ty->isHalfTy();
1275     case IITDescriptor::BFloat: return !Ty->isBFloatTy();
1276     case IITDescriptor::Float: return !Ty->isFloatTy();
1277     case IITDescriptor::Double: return !Ty->isDoubleTy();
1278     case IITDescriptor::Quad: return !Ty->isFP128Ty();
1279     case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1280     case IITDescriptor::Vector: {
1281       VectorType *VT = dyn_cast<VectorType>(Ty);
1282       return !VT || VT->getElementCount() != D.Vector_Width ||
1283              matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
1284                                 DeferredChecks, IsDeferredCheck);
1285     }
1286     case IITDescriptor::Pointer: {
1287       PointerType *PT = dyn_cast<PointerType>(Ty);
1288       return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1289              matchIntrinsicType(PT->getElementType(), Infos, ArgTys,
1290                                 DeferredChecks, IsDeferredCheck);
1291     }
1292 
1293     case IITDescriptor::Struct: {
1294       StructType *ST = dyn_cast<StructType>(Ty);
1295       if (!ST || ST->getNumElements() != D.Struct_NumElements)
1296         return true;
1297 
1298       for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1299         if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
1300                                DeferredChecks, IsDeferredCheck))
1301           return true;
1302       return false;
1303     }
1304 
1305     case IITDescriptor::Argument:
1306       // If this is the second occurrence of an argument,
1307       // verify that the later instance matches the previous instance.
1308       if (D.getArgumentNumber() < ArgTys.size())
1309         return Ty != ArgTys[D.getArgumentNumber()];
1310 
1311       if (D.getArgumentNumber() > ArgTys.size() ||
1312           D.getArgumentKind() == IITDescriptor::AK_MatchType)
1313         return IsDeferredCheck || DeferCheck(Ty);
1314 
1315       assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
1316              "Table consistency error");
1317       ArgTys.push_back(Ty);
1318 
1319       switch (D.getArgumentKind()) {
1320         case IITDescriptor::AK_Any:        return false; // Success
1321         case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1322         case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
1323         case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
1324         case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1325         default:                           break;
1326       }
1327       llvm_unreachable("all argument kinds not covered");
1328 
1329     case IITDescriptor::ExtendArgument: {
1330       // If this is a forward reference, defer the check for later.
1331       if (D.getArgumentNumber() >= ArgTys.size())
1332         return IsDeferredCheck || DeferCheck(Ty);
1333 
1334       Type *NewTy = ArgTys[D.getArgumentNumber()];
1335       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1336         NewTy = VectorType::getExtendedElementVectorType(VTy);
1337       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1338         NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
1339       else
1340         return true;
1341 
1342       return Ty != NewTy;
1343     }
1344     case IITDescriptor::TruncArgument: {
1345       // If this is a forward reference, defer the check for later.
1346       if (D.getArgumentNumber() >= ArgTys.size())
1347         return IsDeferredCheck || DeferCheck(Ty);
1348 
1349       Type *NewTy = ArgTys[D.getArgumentNumber()];
1350       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1351         NewTy = VectorType::getTruncatedElementVectorType(VTy);
1352       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1353         NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
1354       else
1355         return true;
1356 
1357       return Ty != NewTy;
1358     }
1359     case IITDescriptor::HalfVecArgument:
1360       // If this is a forward reference, defer the check for later.
1361       if (D.getArgumentNumber() >= ArgTys.size())
1362         return IsDeferredCheck || DeferCheck(Ty);
1363       return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1364              VectorType::getHalfElementsVectorType(
1365                      cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1366     case IITDescriptor::SameVecWidthArgument: {
1367       if (D.getArgumentNumber() >= ArgTys.size()) {
1368         // Defer check and subsequent check for the vector element type.
1369         Infos = Infos.slice(1);
1370         return IsDeferredCheck || DeferCheck(Ty);
1371       }
1372       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1373       auto *ThisArgType = dyn_cast<VectorType>(Ty);
1374       // Both must be vectors of the same number of elements or neither.
1375       if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
1376         return true;
1377       Type *EltTy = Ty;
1378       if (ThisArgType) {
1379         if (ReferenceType->getElementCount() !=
1380             ThisArgType->getElementCount())
1381           return true;
1382         EltTy = ThisArgType->getElementType();
1383       }
1384       return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
1385                                 IsDeferredCheck);
1386     }
1387     case IITDescriptor::PtrToArgument: {
1388       if (D.getArgumentNumber() >= ArgTys.size())
1389         return IsDeferredCheck || DeferCheck(Ty);
1390       Type * ReferenceType = ArgTys[D.getArgumentNumber()];
1391       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1392       return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
1393     }
1394     case IITDescriptor::PtrToElt: {
1395       if (D.getArgumentNumber() >= ArgTys.size())
1396         return IsDeferredCheck || DeferCheck(Ty);
1397       VectorType * ReferenceType =
1398         dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
1399       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1400 
1401       return (!ThisArgType || !ReferenceType ||
1402               ThisArgType->getElementType() != ReferenceType->getElementType());
1403     }
1404     case IITDescriptor::VecOfAnyPtrsToElt: {
1405       unsigned RefArgNumber = D.getRefArgNumber();
1406       if (RefArgNumber >= ArgTys.size()) {
1407         if (IsDeferredCheck)
1408           return true;
1409         // If forward referencing, already add the pointer-vector type and
1410         // defer the checks for later.
1411         ArgTys.push_back(Ty);
1412         return DeferCheck(Ty);
1413       }
1414 
1415       if (!IsDeferredCheck){
1416         assert(D.getOverloadArgNumber() == ArgTys.size() &&
1417                "Table consistency error");
1418         ArgTys.push_back(Ty);
1419       }
1420 
1421       // Verify the overloaded type "matches" the Ref type.
1422       // i.e. Ty is a vector with the same width as Ref.
1423       // Composed of pointers to the same element type as Ref.
1424       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
1425       auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1426       if (!ThisArgVecTy || !ReferenceType ||
1427           (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))
1428         return true;
1429       PointerType *ThisArgEltTy =
1430           dyn_cast<PointerType>(ThisArgVecTy->getElementType());
1431       if (!ThisArgEltTy)
1432         return true;
1433       return ThisArgEltTy->getElementType() != ReferenceType->getElementType();
1434     }
1435     case IITDescriptor::VecElementArgument: {
1436       if (D.getArgumentNumber() >= ArgTys.size())
1437         return IsDeferredCheck ? true : DeferCheck(Ty);
1438       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1439       return !ReferenceType || Ty != ReferenceType->getElementType();
1440     }
1441     case IITDescriptor::Subdivide2Argument:
1442     case IITDescriptor::Subdivide4Argument: {
1443       // If this is a forward reference, defer the check for later.
1444       if (D.getArgumentNumber() >= ArgTys.size())
1445         return IsDeferredCheck || DeferCheck(Ty);
1446 
1447       Type *NewTy = ArgTys[D.getArgumentNumber()];
1448       if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
1449         int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1450         NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
1451         return Ty != NewTy;
1452       }
1453       return true;
1454     }
1455     case IITDescriptor::VecOfBitcastsToInt: {
1456       if (D.getArgumentNumber() >= ArgTys.size())
1457         return IsDeferredCheck || DeferCheck(Ty);
1458       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1459       auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1460       if (!ThisArgVecTy || !ReferenceType)
1461         return true;
1462       return ThisArgVecTy != VectorType::getInteger(ReferenceType);
1463     }
1464   }
1465   llvm_unreachable("unhandled");
1466 }
1467 
1468 Intrinsic::MatchIntrinsicTypesResult
1469 Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
1470                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
1471                                    SmallVectorImpl<Type *> &ArgTys) {
1472   SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
1473   if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
1474                          false))
1475     return MatchIntrinsicTypes_NoMatchRet;
1476 
1477   unsigned NumDeferredReturnChecks = DeferredChecks.size();
1478 
1479   for (auto Ty : FTy->params())
1480     if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
1481       return MatchIntrinsicTypes_NoMatchArg;
1482 
1483   for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
1484     DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
1485     if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
1486                            true))
1487       return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
1488                                          : MatchIntrinsicTypes_NoMatchArg;
1489   }
1490 
1491   return MatchIntrinsicTypes_Match;
1492 }
1493 
1494 bool
1495 Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1496                                 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1497   // If there are no descriptors left, then it can't be a vararg.
1498   if (Infos.empty())
1499     return isVarArg;
1500 
1501   // There should be only one descriptor remaining at this point.
1502   if (Infos.size() != 1)
1503     return true;
1504 
1505   // Check and verify the descriptor.
1506   IITDescriptor D = Infos.front();
1507   Infos = Infos.slice(1);
1508   if (D.Kind == IITDescriptor::VarArg)
1509     return !isVarArg;
1510 
1511   return true;
1512 }
1513 
1514 bool Intrinsic::getIntrinsicSignature(Function *F,
1515                                       SmallVectorImpl<Type *> &ArgTys) {
1516   Intrinsic::ID ID = F->getIntrinsicID();
1517   if (!ID)
1518     return false;
1519 
1520   SmallVector<Intrinsic::IITDescriptor, 8> Table;
1521   getIntrinsicInfoTableEntries(ID, Table);
1522   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1523 
1524   if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef,
1525                                          ArgTys) !=
1526       Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {
1527     return false;
1528   }
1529   if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(),
1530                                       TableRef))
1531     return false;
1532   return true;
1533 }
1534 
1535 Optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {
1536   SmallVector<Type *, 4> ArgTys;
1537   if (!getIntrinsicSignature(F, ArgTys))
1538     return None;
1539 
1540   Intrinsic::ID ID = F->getIntrinsicID();
1541   StringRef Name = F->getName();
1542   if (Name == Intrinsic::getName(ID, ArgTys))
1543     return None;
1544 
1545   auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
1546   NewDecl->setCallingConv(F->getCallingConv());
1547   assert(NewDecl->getFunctionType() == F->getFunctionType() &&
1548          "Shouldn't change the signature");
1549   return NewDecl;
1550 }
1551 
1552 /// hasAddressTaken - returns true if there are any uses of this function
1553 /// other than direct calls or invokes to it. Optionally ignores callback
1554 /// uses.
1555 bool Function::hasAddressTaken(const User **PutOffender,
1556                                bool IgnoreCallbackUses) const {
1557   for (const Use &U : uses()) {
1558     const User *FU = U.getUser();
1559     if (isa<BlockAddress>(FU))
1560       continue;
1561 
1562     if (IgnoreCallbackUses) {
1563       AbstractCallSite ACS(&U);
1564       if (ACS && ACS.isCallbackCall())
1565         continue;
1566     }
1567 
1568     const auto *Call = dyn_cast<CallBase>(FU);
1569     if (!Call) {
1570       if (PutOffender)
1571         *PutOffender = FU;
1572       return true;
1573     }
1574     if (!Call->isCallee(&U)) {
1575       if (PutOffender)
1576         *PutOffender = FU;
1577       return true;
1578     }
1579   }
1580   return false;
1581 }
1582 
1583 bool Function::isDefTriviallyDead() const {
1584   // Check the linkage
1585   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1586       !hasAvailableExternallyLinkage())
1587     return false;
1588 
1589   // Check if the function is used by anything other than a blockaddress.
1590   for (const User *U : users())
1591     if (!isa<BlockAddress>(U))
1592       return false;
1593 
1594   return true;
1595 }
1596 
1597 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1598 /// setjmp or other function that gcc recognizes as "returning twice".
1599 bool Function::callsFunctionThatReturnsTwice() const {
1600   for (const Instruction &I : instructions(this))
1601     if (const auto *Call = dyn_cast<CallBase>(&I))
1602       if (Call->hasFnAttr(Attribute::ReturnsTwice))
1603         return true;
1604 
1605   return false;
1606 }
1607 
1608 Constant *Function::getPersonalityFn() const {
1609   assert(hasPersonalityFn() && getNumOperands());
1610   return cast<Constant>(Op<0>());
1611 }
1612 
1613 void Function::setPersonalityFn(Constant *Fn) {
1614   setHungoffOperand<0>(Fn);
1615   setValueSubclassDataBit(3, Fn != nullptr);
1616 }
1617 
1618 Constant *Function::getPrefixData() const {
1619   assert(hasPrefixData() && getNumOperands());
1620   return cast<Constant>(Op<1>());
1621 }
1622 
1623 void Function::setPrefixData(Constant *PrefixData) {
1624   setHungoffOperand<1>(PrefixData);
1625   setValueSubclassDataBit(1, PrefixData != nullptr);
1626 }
1627 
1628 Constant *Function::getPrologueData() const {
1629   assert(hasPrologueData() && getNumOperands());
1630   return cast<Constant>(Op<2>());
1631 }
1632 
1633 void Function::setPrologueData(Constant *PrologueData) {
1634   setHungoffOperand<2>(PrologueData);
1635   setValueSubclassDataBit(2, PrologueData != nullptr);
1636 }
1637 
1638 void Function::allocHungoffUselist() {
1639   // If we've already allocated a uselist, stop here.
1640   if (getNumOperands())
1641     return;
1642 
1643   allocHungoffUses(3, /*IsPhi=*/ false);
1644   setNumHungOffUseOperands(3);
1645 
1646   // Initialize the uselist with placeholder operands to allow traversal.
1647   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
1648   Op<0>().set(CPN);
1649   Op<1>().set(CPN);
1650   Op<2>().set(CPN);
1651 }
1652 
1653 template <int Idx>
1654 void Function::setHungoffOperand(Constant *C) {
1655   if (C) {
1656     allocHungoffUselist();
1657     Op<Idx>().set(C);
1658   } else if (getNumOperands()) {
1659     Op<Idx>().set(
1660         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
1661   }
1662 }
1663 
1664 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1665   assert(Bit < 16 && "SubclassData contains only 16 bits");
1666   if (On)
1667     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1668   else
1669     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1670 }
1671 
1672 void Function::setEntryCount(ProfileCount Count,
1673                              const DenseSet<GlobalValue::GUID> *S) {
1674   assert(Count.hasValue());
1675 #if !defined(NDEBUG)
1676   auto PrevCount = getEntryCount();
1677   assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType());
1678 #endif
1679 
1680   auto ImportGUIDs = getImportGUIDs();
1681   if (S == nullptr && ImportGUIDs.size())
1682     S = &ImportGUIDs;
1683 
1684   MDBuilder MDB(getContext());
1685   setMetadata(
1686       LLVMContext::MD_prof,
1687       MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
1688 }
1689 
1690 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
1691                              const DenseSet<GlobalValue::GUID> *Imports) {
1692   setEntryCount(ProfileCount(Count, Type), Imports);
1693 }
1694 
1695 ProfileCount Function::getEntryCount(bool AllowSynthetic) const {
1696   MDNode *MD = getMetadata(LLVMContext::MD_prof);
1697   if (MD && MD->getOperand(0))
1698     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
1699       if (MDS->getString().equals("function_entry_count")) {
1700         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1701         uint64_t Count = CI->getValue().getZExtValue();
1702         // A value of -1 is used for SamplePGO when there were no samples.
1703         // Treat this the same as unknown.
1704         if (Count == (uint64_t)-1)
1705           return ProfileCount::getInvalid();
1706         return ProfileCount(Count, PCT_Real);
1707       } else if (AllowSynthetic &&
1708                  MDS->getString().equals("synthetic_function_entry_count")) {
1709         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1710         uint64_t Count = CI->getValue().getZExtValue();
1711         return ProfileCount(Count, PCT_Synthetic);
1712       }
1713     }
1714   return ProfileCount::getInvalid();
1715 }
1716 
1717 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
1718   DenseSet<GlobalValue::GUID> R;
1719   if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1720     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1721       if (MDS->getString().equals("function_entry_count"))
1722         for (unsigned i = 2; i < MD->getNumOperands(); i++)
1723           R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
1724                        ->getValue()
1725                        .getZExtValue());
1726   return R;
1727 }
1728 
1729 void Function::setSectionPrefix(StringRef Prefix) {
1730   MDBuilder MDB(getContext());
1731   setMetadata(LLVMContext::MD_section_prefix,
1732               MDB.createFunctionSectionPrefix(Prefix));
1733 }
1734 
1735 Optional<StringRef> Function::getSectionPrefix() const {
1736   if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
1737     assert(cast<MDString>(MD->getOperand(0))
1738                ->getString()
1739                .equals("function_section_prefix") &&
1740            "Metadata not match");
1741     return cast<MDString>(MD->getOperand(1))->getString();
1742   }
1743   return None;
1744 }
1745 
1746 bool Function::nullPointerIsDefined() const {
1747   return hasFnAttribute(Attribute::NullPointerIsValid);
1748 }
1749 
1750 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
1751   if (F && F->nullPointerIsDefined())
1752     return true;
1753 
1754   if (AS != 0)
1755     return true;
1756 
1757   return false;
1758 }
1759