1 //===- Function.cpp - Implement the Global object classes -----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Function class for the IR library.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/Function.h"
14 #include "SymbolTableListTraitsImpl.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/Argument.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/InstIterator.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/MDBuilder.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/SymbolTableListTraits.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Use.h"
42 #include "llvm/IR/User.h"
43 #include "llvm/IR/Value.h"
44 #include "llvm/IR/ValueSymbolTable.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/ErrorHandling.h"
56 using ProfileCount
= Function::ProfileCount
;
58 // Explicit instantiations of SymbolTableListTraits since some of the methods
59 // are not in the public header file...
60 template class llvm::SymbolTableListTraits
<BasicBlock
>;
62 //===----------------------------------------------------------------------===//
63 // Argument Implementation
64 //===----------------------------------------------------------------------===//
66 Argument::Argument(Type
*Ty
, const Twine
&Name
, Function
*Par
, unsigned ArgNo
)
67 : Value(Ty
, Value::ArgumentVal
), Parent(Par
), ArgNo(ArgNo
) {
71 void Argument::setParent(Function
*parent
) {
75 bool Argument::hasNonNullAttr() const {
76 if (!getType()->isPointerTy()) return false;
77 if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull
))
79 else if (getDereferenceableBytes() > 0 &&
80 !NullPointerIsDefined(getParent(),
81 getType()->getPointerAddressSpace()))
86 bool Argument::hasByValAttr() const {
87 if (!getType()->isPointerTy()) return false;
88 return hasAttribute(Attribute::ByVal
);
91 bool Argument::hasSwiftSelfAttr() const {
92 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf
);
95 bool Argument::hasSwiftErrorAttr() const {
96 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError
);
99 bool Argument::hasInAllocaAttr() const {
100 if (!getType()->isPointerTy()) return false;
101 return hasAttribute(Attribute::InAlloca
);
104 bool Argument::hasByValOrInAllocaAttr() const {
105 if (!getType()->isPointerTy()) return false;
106 AttributeList Attrs
= getParent()->getAttributes();
107 return Attrs
.hasParamAttribute(getArgNo(), Attribute::ByVal
) ||
108 Attrs
.hasParamAttribute(getArgNo(), Attribute::InAlloca
);
111 unsigned Argument::getParamAlignment() const {
112 assert(getType()->isPointerTy() && "Only pointers have alignments");
113 return getParent()->getParamAlignment(getArgNo());
116 Type
*Argument::getParamByValType() const {
117 assert(getType()->isPointerTy() && "Only pointers have byval types");
118 return getParent()->getParamByValType(getArgNo());
121 uint64_t Argument::getDereferenceableBytes() const {
122 assert(getType()->isPointerTy() &&
123 "Only pointers have dereferenceable bytes");
124 return getParent()->getParamDereferenceableBytes(getArgNo());
127 uint64_t Argument::getDereferenceableOrNullBytes() const {
128 assert(getType()->isPointerTy() &&
129 "Only pointers have dereferenceable bytes");
130 return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
133 bool Argument::hasNestAttr() const {
134 if (!getType()->isPointerTy()) return false;
135 return hasAttribute(Attribute::Nest
);
138 bool Argument::hasNoAliasAttr() const {
139 if (!getType()->isPointerTy()) return false;
140 return hasAttribute(Attribute::NoAlias
);
143 bool Argument::hasNoCaptureAttr() const {
144 if (!getType()->isPointerTy()) return false;
145 return hasAttribute(Attribute::NoCapture
);
148 bool Argument::hasStructRetAttr() const {
149 if (!getType()->isPointerTy()) return false;
150 return hasAttribute(Attribute::StructRet
);
153 bool Argument::hasInRegAttr() const {
154 return hasAttribute(Attribute::InReg
);
157 bool Argument::hasReturnedAttr() const {
158 return hasAttribute(Attribute::Returned
);
161 bool Argument::hasZExtAttr() const {
162 return hasAttribute(Attribute::ZExt
);
165 bool Argument::hasSExtAttr() const {
166 return hasAttribute(Attribute::SExt
);
169 bool Argument::onlyReadsMemory() const {
170 AttributeList Attrs
= getParent()->getAttributes();
171 return Attrs
.hasParamAttribute(getArgNo(), Attribute::ReadOnly
) ||
172 Attrs
.hasParamAttribute(getArgNo(), Attribute::ReadNone
);
175 void Argument::addAttrs(AttrBuilder
&B
) {
176 AttributeList AL
= getParent()->getAttributes();
177 AL
= AL
.addParamAttributes(Parent
->getContext(), getArgNo(), B
);
178 getParent()->setAttributes(AL
);
181 void Argument::addAttr(Attribute::AttrKind Kind
) {
182 getParent()->addParamAttr(getArgNo(), Kind
);
185 void Argument::addAttr(Attribute Attr
) {
186 getParent()->addParamAttr(getArgNo(), Attr
);
189 void Argument::removeAttr(Attribute::AttrKind Kind
) {
190 getParent()->removeParamAttr(getArgNo(), Kind
);
193 bool Argument::hasAttribute(Attribute::AttrKind Kind
) const {
194 return getParent()->hasParamAttribute(getArgNo(), Kind
);
197 Attribute
Argument::getAttribute(Attribute::AttrKind Kind
) const {
198 return getParent()->getParamAttribute(getArgNo(), Kind
);
201 //===----------------------------------------------------------------------===//
202 // Helper Methods in Function
203 //===----------------------------------------------------------------------===//
205 LLVMContext
&Function::getContext() const {
206 return getType()->getContext();
209 unsigned Function::getInstructionCount() const {
210 unsigned NumInstrs
= 0;
211 for (const BasicBlock
&BB
: BasicBlocks
)
212 NumInstrs
+= std::distance(BB
.instructionsWithoutDebug().begin(),
213 BB
.instructionsWithoutDebug().end());
217 Function
*Function::Create(FunctionType
*Ty
, LinkageTypes Linkage
,
218 const Twine
&N
, Module
&M
) {
219 return Create(Ty
, Linkage
, M
.getDataLayout().getProgramAddressSpace(), N
, &M
);
222 void Function::removeFromParent() {
223 getParent()->getFunctionList().remove(getIterator());
226 void Function::eraseFromParent() {
227 getParent()->getFunctionList().erase(getIterator());
230 //===----------------------------------------------------------------------===//
231 // Function Implementation
232 //===----------------------------------------------------------------------===//
234 static unsigned computeAddrSpace(unsigned AddrSpace
, Module
*M
) {
235 // If AS == -1 and we are passed a valid module pointer we place the function
236 // in the program address space. Otherwise we default to AS0.
237 if (AddrSpace
== static_cast<unsigned>(-1))
238 return M
? M
->getDataLayout().getProgramAddressSpace() : 0;
242 Function::Function(FunctionType
*Ty
, LinkageTypes Linkage
, unsigned AddrSpace
,
243 const Twine
&name
, Module
*ParentModule
)
244 : GlobalObject(Ty
, Value::FunctionVal
,
245 OperandTraits
<Function
>::op_begin(this), 0, Linkage
, name
,
246 computeAddrSpace(AddrSpace
, ParentModule
)),
247 NumArgs(Ty
->getNumParams()) {
248 assert(FunctionType::isValidReturnType(getReturnType()) &&
249 "invalid return type");
250 setGlobalObjectSubClassData(0);
252 // We only need a symbol table for a function if the context keeps value names
253 if (!getContext().shouldDiscardValueNames())
254 SymTab
= std::make_unique
<ValueSymbolTable
>();
256 // If the function has arguments, mark them as lazily built.
257 if (Ty
->getNumParams())
258 setValueSubclassData(1); // Set the "has lazy arguments" bit.
261 ParentModule
->getFunctionList().push_back(this);
263 HasLLVMReservedName
= getName().startswith("llvm.");
264 // Ensure intrinsics have the right parameter attributes.
265 // Note, the IntID field will have been set in Value::setName if this function
266 // name is a valid intrinsic ID.
268 setAttributes(Intrinsic::getAttributes(getContext(), IntID
));
271 Function::~Function() {
272 dropAllReferences(); // After this it is safe to delete instructions.
274 // Delete all of the method arguments and unlink from symbol table...
278 // Remove the function from the on-the-side GC table.
282 void Function::BuildLazyArguments() const {
283 // Create the arguments vector, all arguments start out unnamed.
284 auto *FT
= getFunctionType();
286 Arguments
= std::allocator
<Argument
>().allocate(NumArgs
);
287 for (unsigned i
= 0, e
= NumArgs
; i
!= e
; ++i
) {
288 Type
*ArgTy
= FT
->getParamType(i
);
289 assert(!ArgTy
->isVoidTy() && "Cannot have void typed arguments!");
290 new (Arguments
+ i
) Argument(ArgTy
, "", const_cast<Function
*>(this), i
);
294 // Clear the lazy arguments bit.
295 unsigned SDC
= getSubclassDataFromValue();
296 const_cast<Function
*>(this)->setValueSubclassData(SDC
&= ~(1<<0));
297 assert(!hasLazyArguments());
300 static MutableArrayRef
<Argument
> makeArgArray(Argument
*Args
, size_t Count
) {
301 return MutableArrayRef
<Argument
>(Args
, Count
);
304 void Function::clearArguments() {
305 for (Argument
&A
: makeArgArray(Arguments
, NumArgs
)) {
309 std::allocator
<Argument
>().deallocate(Arguments
, NumArgs
);
313 void Function::stealArgumentListFrom(Function
&Src
) {
314 assert(isDeclaration() && "Expected no references to current arguments");
316 // Drop the current arguments, if any, and set the lazy argument bit.
317 if (!hasLazyArguments()) {
318 assert(llvm::all_of(makeArgArray(Arguments
, NumArgs
),
319 [](const Argument
&A
) { return A
.use_empty(); }) &&
320 "Expected arguments to be unused in declaration");
322 setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
325 // Nothing to steal if Src has lazy arguments.
326 if (Src
.hasLazyArguments())
329 // Steal arguments from Src, and fix the lazy argument bits.
330 assert(arg_size() == Src
.arg_size());
331 Arguments
= Src
.Arguments
;
332 Src
.Arguments
= nullptr;
333 for (Argument
&A
: makeArgArray(Arguments
, NumArgs
)) {
334 // FIXME: This does the work of transferNodesFromList inefficiently.
335 SmallString
<128> Name
;
345 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
346 assert(!hasLazyArguments());
347 Src
.setValueSubclassData(Src
.getSubclassDataFromValue() | (1 << 0));
350 // dropAllReferences() - This function causes all the subinstructions to "let
351 // go" of all references that they are maintaining. This allows one to
352 // 'delete' a whole class at a time, even though there may be circular
353 // references... first all references are dropped, and all use counts go to
354 // zero. Then everything is deleted for real. Note that no operations are
355 // valid on an object that has "dropped all references", except operator
358 void Function::dropAllReferences() {
359 setIsMaterializable(false);
361 for (BasicBlock
&BB
: *this)
362 BB
.dropAllReferences();
364 // Delete all basic blocks. They are now unused, except possibly by
365 // blockaddresses, but BasicBlock's destructor takes care of those.
366 while (!BasicBlocks
.empty())
367 BasicBlocks
.begin()->eraseFromParent();
369 // Drop uses of any optional data (real or placeholder).
370 if (getNumOperands()) {
371 User::dropAllReferences();
372 setNumHungOffUseOperands(0);
373 setValueSubclassData(getSubclassDataFromValue() & ~0xe);
376 // Metadata is stored in a side-table.
380 void Function::addAttribute(unsigned i
, Attribute::AttrKind Kind
) {
381 AttributeList PAL
= getAttributes();
382 PAL
= PAL
.addAttribute(getContext(), i
, Kind
);
386 void Function::addAttribute(unsigned i
, Attribute Attr
) {
387 AttributeList PAL
= getAttributes();
388 PAL
= PAL
.addAttribute(getContext(), i
, Attr
);
392 void Function::addAttributes(unsigned i
, const AttrBuilder
&Attrs
) {
393 AttributeList PAL
= getAttributes();
394 PAL
= PAL
.addAttributes(getContext(), i
, Attrs
);
398 void Function::addParamAttr(unsigned ArgNo
, Attribute::AttrKind Kind
) {
399 AttributeList PAL
= getAttributes();
400 PAL
= PAL
.addParamAttribute(getContext(), ArgNo
, Kind
);
404 void Function::addParamAttr(unsigned ArgNo
, Attribute Attr
) {
405 AttributeList PAL
= getAttributes();
406 PAL
= PAL
.addParamAttribute(getContext(), ArgNo
, Attr
);
410 void Function::addParamAttrs(unsigned ArgNo
, const AttrBuilder
&Attrs
) {
411 AttributeList PAL
= getAttributes();
412 PAL
= PAL
.addParamAttributes(getContext(), ArgNo
, Attrs
);
416 void Function::removeAttribute(unsigned i
, Attribute::AttrKind Kind
) {
417 AttributeList PAL
= getAttributes();
418 PAL
= PAL
.removeAttribute(getContext(), i
, Kind
);
422 void Function::removeAttribute(unsigned i
, StringRef Kind
) {
423 AttributeList PAL
= getAttributes();
424 PAL
= PAL
.removeAttribute(getContext(), i
, Kind
);
428 void Function::removeAttributes(unsigned i
, const AttrBuilder
&Attrs
) {
429 AttributeList PAL
= getAttributes();
430 PAL
= PAL
.removeAttributes(getContext(), i
, Attrs
);
434 void Function::removeParamAttr(unsigned ArgNo
, Attribute::AttrKind Kind
) {
435 AttributeList PAL
= getAttributes();
436 PAL
= PAL
.removeParamAttribute(getContext(), ArgNo
, Kind
);
440 void Function::removeParamAttr(unsigned ArgNo
, StringRef Kind
) {
441 AttributeList PAL
= getAttributes();
442 PAL
= PAL
.removeParamAttribute(getContext(), ArgNo
, Kind
);
446 void Function::removeParamAttrs(unsigned ArgNo
, const AttrBuilder
&Attrs
) {
447 AttributeList PAL
= getAttributes();
448 PAL
= PAL
.removeParamAttributes(getContext(), ArgNo
, Attrs
);
452 void Function::addDereferenceableAttr(unsigned i
, uint64_t Bytes
) {
453 AttributeList PAL
= getAttributes();
454 PAL
= PAL
.addDereferenceableAttr(getContext(), i
, Bytes
);
458 void Function::addDereferenceableParamAttr(unsigned ArgNo
, uint64_t Bytes
) {
459 AttributeList PAL
= getAttributes();
460 PAL
= PAL
.addDereferenceableParamAttr(getContext(), ArgNo
, Bytes
);
464 void Function::addDereferenceableOrNullAttr(unsigned i
, uint64_t Bytes
) {
465 AttributeList PAL
= getAttributes();
466 PAL
= PAL
.addDereferenceableOrNullAttr(getContext(), i
, Bytes
);
470 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo
,
472 AttributeList PAL
= getAttributes();
473 PAL
= PAL
.addDereferenceableOrNullParamAttr(getContext(), ArgNo
, Bytes
);
477 const std::string
&Function::getGC() const {
478 assert(hasGC() && "Function has no collector");
479 return getContext().getGC(*this);
482 void Function::setGC(std::string Str
) {
483 setValueSubclassDataBit(14, !Str
.empty());
484 getContext().setGC(*this, std::move(Str
));
487 void Function::clearGC() {
490 getContext().deleteGC(*this);
491 setValueSubclassDataBit(14, false);
494 /// Copy all additional attributes (those not needed to create a Function) from
495 /// the Function Src to this one.
496 void Function::copyAttributesFrom(const Function
*Src
) {
497 GlobalObject::copyAttributesFrom(Src
);
498 setCallingConv(Src
->getCallingConv());
499 setAttributes(Src
->getAttributes());
504 if (Src
->hasPersonalityFn())
505 setPersonalityFn(Src
->getPersonalityFn());
506 if (Src
->hasPrefixData())
507 setPrefixData(Src
->getPrefixData());
508 if (Src
->hasPrologueData())
509 setPrologueData(Src
->getPrologueData());
512 /// Table of string intrinsic names indexed by enum value.
513 static const char * const IntrinsicNameTable
[] = {
515 #define GET_INTRINSIC_NAME_TABLE
516 #include "llvm/IR/IntrinsicImpl.inc"
517 #undef GET_INTRINSIC_NAME_TABLE
520 /// Table of per-target intrinsic name tables.
521 #define GET_INTRINSIC_TARGET_DATA
522 #include "llvm/IR/IntrinsicImpl.inc"
523 #undef GET_INTRINSIC_TARGET_DATA
525 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
526 /// target as \c Name, or the generic table if \c Name is not target specific.
528 /// Returns the relevant slice of \c IntrinsicNameTable
529 static ArrayRef
<const char *> findTargetSubtable(StringRef Name
) {
530 assert(Name
.startswith("llvm."));
532 ArrayRef
<IntrinsicTargetInfo
> Targets(TargetInfos
);
533 // Drop "llvm." and take the first dotted component. That will be the target
534 // if this is target specific.
535 StringRef Target
= Name
.drop_front(5).split('.').first
;
536 auto It
= partition_point(
537 Targets
, [=](const IntrinsicTargetInfo
&TI
) { return TI
.Name
< Target
; });
538 // We've either found the target or just fall back to the generic set, which
540 const auto &TI
= It
!= Targets
.end() && It
->Name
== Target
? *It
: Targets
[0];
541 return makeArrayRef(&IntrinsicNameTable
[1] + TI
.Offset
, TI
.Count
);
544 /// This does the actual lookup of an intrinsic ID which
545 /// matches the given function name.
546 Intrinsic::ID
Function::lookupIntrinsicID(StringRef Name
) {
547 ArrayRef
<const char *> NameTable
= findTargetSubtable(Name
);
548 int Idx
= Intrinsic::lookupLLVMIntrinsicByName(NameTable
, Name
);
550 return Intrinsic::not_intrinsic
;
552 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
553 // an index into a sub-table.
554 int Adjust
= NameTable
.data() - IntrinsicNameTable
;
555 Intrinsic::ID ID
= static_cast<Intrinsic::ID
>(Idx
+ Adjust
);
557 // If the intrinsic is not overloaded, require an exact match. If it is
558 // overloaded, require either exact or prefix match.
559 const auto MatchSize
= strlen(NameTable
[Idx
]);
560 assert(Name
.size() >= MatchSize
&& "Expected either exact or prefix match");
561 bool IsExactMatch
= Name
.size() == MatchSize
;
562 return IsExactMatch
|| isOverloaded(ID
) ? ID
: Intrinsic::not_intrinsic
;
565 void Function::recalculateIntrinsicID() {
566 StringRef Name
= getName();
567 if (!Name
.startswith("llvm.")) {
568 HasLLVMReservedName
= false;
569 IntID
= Intrinsic::not_intrinsic
;
572 HasLLVMReservedName
= true;
573 IntID
= lookupIntrinsicID(Name
);
576 /// Returns a stable mangling for the type specified for use in the name
577 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
578 /// of named types is simply their name. Manglings for unnamed types consist
579 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
580 /// combined with the mangling of their component types. A vararg function
581 /// type will have a suffix of 'vararg'. Since function types can contain
582 /// other function types, we close a function type mangling with suffix 'f'
583 /// which can't be confused with it's prefix. This ensures we don't have
584 /// collisions between two unrelated function types. Otherwise, you might
585 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
587 static std::string
getMangledTypeStr(Type
* Ty
) {
589 if (PointerType
* PTyp
= dyn_cast
<PointerType
>(Ty
)) {
590 Result
+= "p" + utostr(PTyp
->getAddressSpace()) +
591 getMangledTypeStr(PTyp
->getElementType());
592 } else if (ArrayType
* ATyp
= dyn_cast
<ArrayType
>(Ty
)) {
593 Result
+= "a" + utostr(ATyp
->getNumElements()) +
594 getMangledTypeStr(ATyp
->getElementType());
595 } else if (StructType
*STyp
= dyn_cast
<StructType
>(Ty
)) {
596 if (!STyp
->isLiteral()) {
598 Result
+= STyp
->getName();
601 for (auto Elem
: STyp
->elements())
602 Result
+= getMangledTypeStr(Elem
);
604 // Ensure nested structs are distinguishable.
606 } else if (FunctionType
*FT
= dyn_cast
<FunctionType
>(Ty
)) {
607 Result
+= "f_" + getMangledTypeStr(FT
->getReturnType());
608 for (size_t i
= 0; i
< FT
->getNumParams(); i
++)
609 Result
+= getMangledTypeStr(FT
->getParamType(i
));
612 // Ensure nested function types are distinguishable.
614 } else if (VectorType
* VTy
= dyn_cast
<VectorType
>(Ty
)) {
615 if (VTy
->isScalable())
617 Result
+= "v" + utostr(VTy
->getVectorNumElements()) +
618 getMangledTypeStr(VTy
->getVectorElementType());
620 switch (Ty
->getTypeID()) {
621 default: llvm_unreachable("Unhandled type");
622 case Type::VoidTyID
: Result
+= "isVoid"; break;
623 case Type::MetadataTyID
: Result
+= "Metadata"; break;
624 case Type::HalfTyID
: Result
+= "f16"; break;
625 case Type::FloatTyID
: Result
+= "f32"; break;
626 case Type::DoubleTyID
: Result
+= "f64"; break;
627 case Type::X86_FP80TyID
: Result
+= "f80"; break;
628 case Type::FP128TyID
: Result
+= "f128"; break;
629 case Type::PPC_FP128TyID
: Result
+= "ppcf128"; break;
630 case Type::X86_MMXTyID
: Result
+= "x86mmx"; break;
631 case Type::IntegerTyID
:
632 Result
+= "i" + utostr(cast
<IntegerType
>(Ty
)->getBitWidth());
639 StringRef
Intrinsic::getName(ID id
) {
640 assert(id
< num_intrinsics
&& "Invalid intrinsic ID!");
641 assert(!isOverloaded(id
) &&
642 "This version of getName does not support overloading");
643 return IntrinsicNameTable
[id
];
646 std::string
Intrinsic::getName(ID id
, ArrayRef
<Type
*> Tys
) {
647 assert(id
< num_intrinsics
&& "Invalid intrinsic ID!");
648 std::string
Result(IntrinsicNameTable
[id
]);
649 for (Type
*Ty
: Tys
) {
650 Result
+= "." + getMangledTypeStr(Ty
);
655 /// IIT_Info - These are enumerators that describe the entries returned by the
656 /// getIntrinsicInfoTableEntries function.
658 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
660 // Common values should be encoded with 0-15.
678 // Values from 16+ are only encodable with the inefficient encoding.
683 IIT_EMPTYSTRUCT
= 20,
693 IIT_HALF_VEC_ARG
= 30,
694 IIT_SAME_VEC_WIDTH_ARG
= 31,
697 IIT_VEC_OF_ANYPTRS_TO_ELT
= 34,
705 IIT_VEC_ELEMENT
= 42,
706 IIT_SCALABLE_VEC
= 43
709 static void DecodeIITType(unsigned &NextElt
, ArrayRef
<unsigned char> Infos
,
710 SmallVectorImpl
<Intrinsic::IITDescriptor
> &OutputTable
) {
711 using namespace Intrinsic
;
713 IIT_Info Info
= IIT_Info(Infos
[NextElt
++]);
714 unsigned StructElts
= 2;
718 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Void
, 0));
721 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::VarArg
, 0));
724 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::MMX
, 0));
727 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Token
, 0));
730 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Metadata
, 0));
733 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Half
, 0));
736 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Float
, 0));
739 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Double
, 0));
742 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Quad
, 0));
745 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Integer
, 1));
748 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Integer
, 8));
751 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Integer
,16));
754 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Integer
, 32));
757 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Integer
, 64));
760 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Integer
, 128));
763 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Vector
, 1));
764 DecodeIITType(NextElt
, Infos
, OutputTable
);
767 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Vector
, 2));
768 DecodeIITType(NextElt
, Infos
, OutputTable
);
771 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Vector
, 4));
772 DecodeIITType(NextElt
, Infos
, OutputTable
);
775 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Vector
, 8));
776 DecodeIITType(NextElt
, Infos
, OutputTable
);
779 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Vector
, 16));
780 DecodeIITType(NextElt
, Infos
, OutputTable
);
783 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Vector
, 32));
784 DecodeIITType(NextElt
, Infos
, OutputTable
);
787 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Vector
, 64));
788 DecodeIITType(NextElt
, Infos
, OutputTable
);
791 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Vector
, 512));
792 DecodeIITType(NextElt
, Infos
, OutputTable
);
795 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Vector
, 1024));
796 DecodeIITType(NextElt
, Infos
, OutputTable
);
799 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Pointer
, 0));
800 DecodeIITType(NextElt
, Infos
, OutputTable
);
802 case IIT_ANYPTR
: { // [ANYPTR addrspace, subtype]
803 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Pointer
,
805 DecodeIITType(NextElt
, Infos
, OutputTable
);
809 unsigned ArgInfo
= (NextElt
== Infos
.size() ? 0 : Infos
[NextElt
++]);
810 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Argument
, ArgInfo
));
813 case IIT_EXTEND_ARG
: {
814 unsigned ArgInfo
= (NextElt
== Infos
.size() ? 0 : Infos
[NextElt
++]);
815 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument
,
819 case IIT_TRUNC_ARG
: {
820 unsigned ArgInfo
= (NextElt
== Infos
.size() ? 0 : Infos
[NextElt
++]);
821 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::TruncArgument
,
825 case IIT_HALF_VEC_ARG
: {
826 unsigned ArgInfo
= (NextElt
== Infos
.size() ? 0 : Infos
[NextElt
++]);
827 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument
,
831 case IIT_SAME_VEC_WIDTH_ARG
: {
832 unsigned ArgInfo
= (NextElt
== Infos
.size() ? 0 : Infos
[NextElt
++]);
833 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument
,
837 case IIT_PTR_TO_ARG
: {
838 unsigned ArgInfo
= (NextElt
== Infos
.size() ? 0 : Infos
[NextElt
++]);
839 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument
,
843 case IIT_PTR_TO_ELT
: {
844 unsigned ArgInfo
= (NextElt
== Infos
.size() ? 0 : Infos
[NextElt
++]);
845 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::PtrToElt
, ArgInfo
));
848 case IIT_VEC_OF_ANYPTRS_TO_ELT
: {
849 unsigned short ArgNo
= (NextElt
== Infos
.size() ? 0 : Infos
[NextElt
++]);
850 unsigned short RefNo
= (NextElt
== Infos
.size() ? 0 : Infos
[NextElt
++]);
851 OutputTable
.push_back(
852 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt
, ArgNo
, RefNo
));
855 case IIT_EMPTYSTRUCT
:
856 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Struct
, 0));
858 case IIT_STRUCT8
: ++StructElts
; LLVM_FALLTHROUGH
;
859 case IIT_STRUCT7
: ++StructElts
; LLVM_FALLTHROUGH
;
860 case IIT_STRUCT6
: ++StructElts
; LLVM_FALLTHROUGH
;
861 case IIT_STRUCT5
: ++StructElts
; LLVM_FALLTHROUGH
;
862 case IIT_STRUCT4
: ++StructElts
; LLVM_FALLTHROUGH
;
863 case IIT_STRUCT3
: ++StructElts
; LLVM_FALLTHROUGH
;
865 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::Struct
,StructElts
));
867 for (unsigned i
= 0; i
!= StructElts
; ++i
)
868 DecodeIITType(NextElt
, Infos
, OutputTable
);
871 case IIT_VEC_ELEMENT
: {
872 unsigned ArgInfo
= (NextElt
== Infos
.size() ? 0 : Infos
[NextElt
++]);
873 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument
,
877 case IIT_SCALABLE_VEC
: {
878 OutputTable
.push_back(IITDescriptor::get(IITDescriptor::ScalableVecArgument
,
880 DecodeIITType(NextElt
, Infos
, OutputTable
);
884 llvm_unreachable("unhandled");
887 #define GET_INTRINSIC_GENERATOR_GLOBAL
888 #include "llvm/IR/IntrinsicImpl.inc"
889 #undef GET_INTRINSIC_GENERATOR_GLOBAL
891 void Intrinsic::getIntrinsicInfoTableEntries(ID id
,
892 SmallVectorImpl
<IITDescriptor
> &T
){
893 // Check to see if the intrinsic's type was expressible by the table.
894 unsigned TableVal
= IIT_Table
[id
-1];
896 // Decode the TableVal into an array of IITValues.
897 SmallVector
<unsigned char, 8> IITValues
;
898 ArrayRef
<unsigned char> IITEntries
;
899 unsigned NextElt
= 0;
900 if ((TableVal
>> 31) != 0) {
901 // This is an offset into the IIT_LongEncodingTable.
902 IITEntries
= IIT_LongEncodingTable
;
904 // Strip sentinel bit.
905 NextElt
= (TableVal
<< 1) >> 1;
907 // Decode the TableVal into an array of IITValues. If the entry was encoded
908 // into a single word in the table itself, decode it now.
910 IITValues
.push_back(TableVal
& 0xF);
914 IITEntries
= IITValues
;
918 // Okay, decode the table into the output vector of IITDescriptors.
919 DecodeIITType(NextElt
, IITEntries
, T
);
920 while (NextElt
!= IITEntries
.size() && IITEntries
[NextElt
] != 0)
921 DecodeIITType(NextElt
, IITEntries
, T
);
924 static Type
*DecodeFixedType(ArrayRef
<Intrinsic::IITDescriptor
> &Infos
,
925 ArrayRef
<Type
*> Tys
, LLVMContext
&Context
) {
926 using namespace Intrinsic
;
928 IITDescriptor D
= Infos
.front();
929 Infos
= Infos
.slice(1);
932 case IITDescriptor::Void
: return Type::getVoidTy(Context
);
933 case IITDescriptor::VarArg
: return Type::getVoidTy(Context
);
934 case IITDescriptor::MMX
: return Type::getX86_MMXTy(Context
);
935 case IITDescriptor::Token
: return Type::getTokenTy(Context
);
936 case IITDescriptor::Metadata
: return Type::getMetadataTy(Context
);
937 case IITDescriptor::Half
: return Type::getHalfTy(Context
);
938 case IITDescriptor::Float
: return Type::getFloatTy(Context
);
939 case IITDescriptor::Double
: return Type::getDoubleTy(Context
);
940 case IITDescriptor::Quad
: return Type::getFP128Ty(Context
);
942 case IITDescriptor::Integer
:
943 return IntegerType::get(Context
, D
.Integer_Width
);
944 case IITDescriptor::Vector
:
945 return VectorType::get(DecodeFixedType(Infos
, Tys
, Context
),D
.Vector_Width
);
946 case IITDescriptor::Pointer
:
947 return PointerType::get(DecodeFixedType(Infos
, Tys
, Context
),
948 D
.Pointer_AddressSpace
);
949 case IITDescriptor::Struct
: {
950 SmallVector
<Type
*, 8> Elts
;
951 for (unsigned i
= 0, e
= D
.Struct_NumElements
; i
!= e
; ++i
)
952 Elts
.push_back(DecodeFixedType(Infos
, Tys
, Context
));
953 return StructType::get(Context
, Elts
);
955 case IITDescriptor::Argument
:
956 return Tys
[D
.getArgumentNumber()];
957 case IITDescriptor::ExtendArgument
: {
958 Type
*Ty
= Tys
[D
.getArgumentNumber()];
959 if (VectorType
*VTy
= dyn_cast
<VectorType
>(Ty
))
960 return VectorType::getExtendedElementVectorType(VTy
);
962 return IntegerType::get(Context
, 2 * cast
<IntegerType
>(Ty
)->getBitWidth());
964 case IITDescriptor::TruncArgument
: {
965 Type
*Ty
= Tys
[D
.getArgumentNumber()];
966 if (VectorType
*VTy
= dyn_cast
<VectorType
>(Ty
))
967 return VectorType::getTruncatedElementVectorType(VTy
);
969 IntegerType
*ITy
= cast
<IntegerType
>(Ty
);
970 assert(ITy
->getBitWidth() % 2 == 0);
971 return IntegerType::get(Context
, ITy
->getBitWidth() / 2);
973 case IITDescriptor::HalfVecArgument
:
974 return VectorType::getHalfElementsVectorType(cast
<VectorType
>(
975 Tys
[D
.getArgumentNumber()]));
976 case IITDescriptor::SameVecWidthArgument
: {
977 Type
*EltTy
= DecodeFixedType(Infos
, Tys
, Context
);
978 Type
*Ty
= Tys
[D
.getArgumentNumber()];
979 if (auto *VTy
= dyn_cast
<VectorType
>(Ty
))
980 return VectorType::get(EltTy
, VTy
->getElementCount());
983 case IITDescriptor::PtrToArgument
: {
984 Type
*Ty
= Tys
[D
.getArgumentNumber()];
985 return PointerType::getUnqual(Ty
);
987 case IITDescriptor::PtrToElt
: {
988 Type
*Ty
= Tys
[D
.getArgumentNumber()];
989 VectorType
*VTy
= dyn_cast
<VectorType
>(Ty
);
991 llvm_unreachable("Expected an argument of Vector Type");
992 Type
*EltTy
= VTy
->getVectorElementType();
993 return PointerType::getUnqual(EltTy
);
995 case IITDescriptor::VecElementArgument
: {
996 Type
*Ty
= Tys
[D
.getArgumentNumber()];
997 if (VectorType
*VTy
= dyn_cast
<VectorType
>(Ty
))
998 return VTy
->getElementType();
999 llvm_unreachable("Expected an argument of Vector Type");
1001 case IITDescriptor::VecOfAnyPtrsToElt
:
1002 // Return the overloaded type (which determines the pointers address space)
1003 return Tys
[D
.getOverloadArgNumber()];
1004 case IITDescriptor::ScalableVecArgument
: {
1005 Type
*Ty
= DecodeFixedType(Infos
, Tys
, Context
);
1006 return VectorType::get(Ty
->getVectorElementType(),
1007 { Ty
->getVectorNumElements(), true });
1010 llvm_unreachable("unhandled");
1013 FunctionType
*Intrinsic::getType(LLVMContext
&Context
,
1014 ID id
, ArrayRef
<Type
*> Tys
) {
1015 SmallVector
<IITDescriptor
, 8> Table
;
1016 getIntrinsicInfoTableEntries(id
, Table
);
1018 ArrayRef
<IITDescriptor
> TableRef
= Table
;
1019 Type
*ResultTy
= DecodeFixedType(TableRef
, Tys
, Context
);
1021 SmallVector
<Type
*, 8> ArgTys
;
1022 while (!TableRef
.empty())
1023 ArgTys
.push_back(DecodeFixedType(TableRef
, Tys
, Context
));
1025 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
1026 // If we see void type as the type of the last argument, it is vararg intrinsic
1027 if (!ArgTys
.empty() && ArgTys
.back()->isVoidTy()) {
1029 return FunctionType::get(ResultTy
, ArgTys
, true);
1031 return FunctionType::get(ResultTy
, ArgTys
, false);
1034 bool Intrinsic::isOverloaded(ID id
) {
1035 #define GET_INTRINSIC_OVERLOAD_TABLE
1036 #include "llvm/IR/IntrinsicImpl.inc"
1037 #undef GET_INTRINSIC_OVERLOAD_TABLE
1040 bool Intrinsic::isLeaf(ID id
) {
1045 case Intrinsic::experimental_gc_statepoint
:
1046 case Intrinsic::experimental_patchpoint_void
:
1047 case Intrinsic::experimental_patchpoint_i64
:
1052 /// This defines the "Intrinsic::getAttributes(ID id)" method.
1053 #define GET_INTRINSIC_ATTRIBUTES
1054 #include "llvm/IR/IntrinsicImpl.inc"
1055 #undef GET_INTRINSIC_ATTRIBUTES
1057 Function
*Intrinsic::getDeclaration(Module
*M
, ID id
, ArrayRef
<Type
*> Tys
) {
1058 // There can never be multiple globals with the same name of different types,
1059 // because intrinsics must be a specific type.
1060 return cast
<Function
>(
1061 M
->getOrInsertFunction(getName(id
, Tys
),
1062 getType(M
->getContext(), id
, Tys
))
1066 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
1067 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1068 #include "llvm/IR/IntrinsicImpl.inc"
1069 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1071 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
1072 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1073 #include "llvm/IR/IntrinsicImpl.inc"
1074 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1076 using DeferredIntrinsicMatchPair
=
1077 std::pair
<Type
*, ArrayRef
<Intrinsic::IITDescriptor
>>;
1079 static bool matchIntrinsicType(
1080 Type
*Ty
, ArrayRef
<Intrinsic::IITDescriptor
> &Infos
,
1081 SmallVectorImpl
<Type
*> &ArgTys
,
1082 SmallVectorImpl
<DeferredIntrinsicMatchPair
> &DeferredChecks
,
1083 bool IsDeferredCheck
) {
1084 using namespace Intrinsic
;
1086 // If we ran out of descriptors, there are too many arguments.
1087 if (Infos
.empty()) return true;
1089 // Do this before slicing off the 'front' part
1090 auto InfosRef
= Infos
;
1091 auto DeferCheck
= [&DeferredChecks
, &InfosRef
](Type
*T
) {
1092 DeferredChecks
.emplace_back(T
, InfosRef
);
1096 IITDescriptor D
= Infos
.front();
1097 Infos
= Infos
.slice(1);
1100 case IITDescriptor::Void
: return !Ty
->isVoidTy();
1101 case IITDescriptor::VarArg
: return true;
1102 case IITDescriptor::MMX
: return !Ty
->isX86_MMXTy();
1103 case IITDescriptor::Token
: return !Ty
->isTokenTy();
1104 case IITDescriptor::Metadata
: return !Ty
->isMetadataTy();
1105 case IITDescriptor::Half
: return !Ty
->isHalfTy();
1106 case IITDescriptor::Float
: return !Ty
->isFloatTy();
1107 case IITDescriptor::Double
: return !Ty
->isDoubleTy();
1108 case IITDescriptor::Quad
: return !Ty
->isFP128Ty();
1109 case IITDescriptor::Integer
: return !Ty
->isIntegerTy(D
.Integer_Width
);
1110 case IITDescriptor::Vector
: {
1111 VectorType
*VT
= dyn_cast
<VectorType
>(Ty
);
1112 return !VT
|| VT
->getNumElements() != D
.Vector_Width
||
1113 matchIntrinsicType(VT
->getElementType(), Infos
, ArgTys
,
1114 DeferredChecks
, IsDeferredCheck
);
1116 case IITDescriptor::Pointer
: {
1117 PointerType
*PT
= dyn_cast
<PointerType
>(Ty
);
1118 return !PT
|| PT
->getAddressSpace() != D
.Pointer_AddressSpace
||
1119 matchIntrinsicType(PT
->getElementType(), Infos
, ArgTys
,
1120 DeferredChecks
, IsDeferredCheck
);
1123 case IITDescriptor::Struct
: {
1124 StructType
*ST
= dyn_cast
<StructType
>(Ty
);
1125 if (!ST
|| ST
->getNumElements() != D
.Struct_NumElements
)
1128 for (unsigned i
= 0, e
= D
.Struct_NumElements
; i
!= e
; ++i
)
1129 if (matchIntrinsicType(ST
->getElementType(i
), Infos
, ArgTys
,
1130 DeferredChecks
, IsDeferredCheck
))
1135 case IITDescriptor::Argument
:
1136 // If this is the second occurrence of an argument,
1137 // verify that the later instance matches the previous instance.
1138 if (D
.getArgumentNumber() < ArgTys
.size())
1139 return Ty
!= ArgTys
[D
.getArgumentNumber()];
1141 if (D
.getArgumentNumber() > ArgTys
.size() ||
1142 D
.getArgumentKind() == IITDescriptor::AK_MatchType
)
1143 return IsDeferredCheck
|| DeferCheck(Ty
);
1145 assert(D
.getArgumentNumber() == ArgTys
.size() && !IsDeferredCheck
&&
1146 "Table consistency error");
1147 ArgTys
.push_back(Ty
);
1149 switch (D
.getArgumentKind()) {
1150 case IITDescriptor::AK_Any
: return false; // Success
1151 case IITDescriptor::AK_AnyInteger
: return !Ty
->isIntOrIntVectorTy();
1152 case IITDescriptor::AK_AnyFloat
: return !Ty
->isFPOrFPVectorTy();
1153 case IITDescriptor::AK_AnyVector
: return !isa
<VectorType
>(Ty
);
1154 case IITDescriptor::AK_AnyPointer
: return !isa
<PointerType
>(Ty
);
1157 llvm_unreachable("all argument kinds not covered");
1159 case IITDescriptor::ExtendArgument
: {
1160 // If this is a forward reference, defer the check for later.
1161 if (D
.getArgumentNumber() >= ArgTys
.size())
1162 return IsDeferredCheck
|| DeferCheck(Ty
);
1164 Type
*NewTy
= ArgTys
[D
.getArgumentNumber()];
1165 if (VectorType
*VTy
= dyn_cast
<VectorType
>(NewTy
))
1166 NewTy
= VectorType::getExtendedElementVectorType(VTy
);
1167 else if (IntegerType
*ITy
= dyn_cast
<IntegerType
>(NewTy
))
1168 NewTy
= IntegerType::get(ITy
->getContext(), 2 * ITy
->getBitWidth());
1174 case IITDescriptor::TruncArgument
: {
1175 // If this is a forward reference, defer the check for later.
1176 if (D
.getArgumentNumber() >= ArgTys
.size())
1177 return IsDeferredCheck
|| DeferCheck(Ty
);
1179 Type
*NewTy
= ArgTys
[D
.getArgumentNumber()];
1180 if (VectorType
*VTy
= dyn_cast
<VectorType
>(NewTy
))
1181 NewTy
= VectorType::getTruncatedElementVectorType(VTy
);
1182 else if (IntegerType
*ITy
= dyn_cast
<IntegerType
>(NewTy
))
1183 NewTy
= IntegerType::get(ITy
->getContext(), ITy
->getBitWidth() / 2);
1189 case IITDescriptor::HalfVecArgument
:
1190 // If this is a forward reference, defer the check for later.
1191 return D
.getArgumentNumber() >= ArgTys
.size() ||
1192 !isa
<VectorType
>(ArgTys
[D
.getArgumentNumber()]) ||
1193 VectorType::getHalfElementsVectorType(
1194 cast
<VectorType
>(ArgTys
[D
.getArgumentNumber()])) != Ty
;
1195 case IITDescriptor::SameVecWidthArgument
: {
1196 if (D
.getArgumentNumber() >= ArgTys
.size()) {
1197 // Defer check and subsequent check for the vector element type.
1198 Infos
= Infos
.slice(1);
1199 return IsDeferredCheck
|| DeferCheck(Ty
);
1201 auto *ReferenceType
= dyn_cast
<VectorType
>(ArgTys
[D
.getArgumentNumber()]);
1202 auto *ThisArgType
= dyn_cast
<VectorType
>(Ty
);
1203 // Both must be vectors of the same number of elements or neither.
1204 if ((ReferenceType
!= nullptr) != (ThisArgType
!= nullptr))
1208 if (ReferenceType
->getElementCount() !=
1209 ThisArgType
->getElementCount())
1211 EltTy
= ThisArgType
->getVectorElementType();
1213 return matchIntrinsicType(EltTy
, Infos
, ArgTys
, DeferredChecks
,
1216 case IITDescriptor::PtrToArgument
: {
1217 if (D
.getArgumentNumber() >= ArgTys
.size())
1218 return IsDeferredCheck
|| DeferCheck(Ty
);
1219 Type
* ReferenceType
= ArgTys
[D
.getArgumentNumber()];
1220 PointerType
*ThisArgType
= dyn_cast
<PointerType
>(Ty
);
1221 return (!ThisArgType
|| ThisArgType
->getElementType() != ReferenceType
);
1223 case IITDescriptor::PtrToElt
: {
1224 if (D
.getArgumentNumber() >= ArgTys
.size())
1225 return IsDeferredCheck
|| DeferCheck(Ty
);
1226 VectorType
* ReferenceType
=
1227 dyn_cast
<VectorType
> (ArgTys
[D
.getArgumentNumber()]);
1228 PointerType
*ThisArgType
= dyn_cast
<PointerType
>(Ty
);
1230 return (!ThisArgType
|| !ReferenceType
||
1231 ThisArgType
->getElementType() != ReferenceType
->getElementType());
1233 case IITDescriptor::VecOfAnyPtrsToElt
: {
1234 unsigned RefArgNumber
= D
.getRefArgNumber();
1235 if (RefArgNumber
>= ArgTys
.size()) {
1236 if (IsDeferredCheck
)
1238 // If forward referencing, already add the pointer-vector type and
1239 // defer the checks for later.
1240 ArgTys
.push_back(Ty
);
1241 return DeferCheck(Ty
);
1244 if (!IsDeferredCheck
){
1245 assert(D
.getOverloadArgNumber() == ArgTys
.size() &&
1246 "Table consistency error");
1247 ArgTys
.push_back(Ty
);
1250 // Verify the overloaded type "matches" the Ref type.
1251 // i.e. Ty is a vector with the same width as Ref.
1252 // Composed of pointers to the same element type as Ref.
1253 VectorType
*ReferenceType
= dyn_cast
<VectorType
>(ArgTys
[RefArgNumber
]);
1254 VectorType
*ThisArgVecTy
= dyn_cast
<VectorType
>(Ty
);
1255 if (!ThisArgVecTy
|| !ReferenceType
||
1256 (ReferenceType
->getVectorNumElements() !=
1257 ThisArgVecTy
->getVectorNumElements()))
1259 PointerType
*ThisArgEltTy
=
1260 dyn_cast
<PointerType
>(ThisArgVecTy
->getVectorElementType());
1263 return ThisArgEltTy
->getElementType() !=
1264 ReferenceType
->getVectorElementType();
1266 case IITDescriptor::VecElementArgument
: {
1267 if (D
.getArgumentNumber() >= ArgTys
.size())
1268 return IsDeferredCheck
? true : DeferCheck(Ty
);
1269 auto *ReferenceType
= dyn_cast
<VectorType
>(ArgTys
[D
.getArgumentNumber()]);
1270 return !ReferenceType
|| Ty
!= ReferenceType
->getElementType();
1272 case IITDescriptor::ScalableVecArgument
: {
1273 VectorType
*VTy
= dyn_cast
<VectorType
>(Ty
);
1274 if (!VTy
|| !VTy
->isScalable())
1276 return matchIntrinsicType(VTy
, Infos
, ArgTys
, DeferredChecks
,
1280 llvm_unreachable("unhandled");
1283 Intrinsic::MatchIntrinsicTypesResult
1284 Intrinsic::matchIntrinsicSignature(FunctionType
*FTy
,
1285 ArrayRef
<Intrinsic::IITDescriptor
> &Infos
,
1286 SmallVectorImpl
<Type
*> &ArgTys
) {
1287 SmallVector
<DeferredIntrinsicMatchPair
, 2> DeferredChecks
;
1288 if (matchIntrinsicType(FTy
->getReturnType(), Infos
, ArgTys
, DeferredChecks
,
1290 return MatchIntrinsicTypes_NoMatchRet
;
1292 unsigned NumDeferredReturnChecks
= DeferredChecks
.size();
1294 for (auto Ty
: FTy
->params())
1295 if (matchIntrinsicType(Ty
, Infos
, ArgTys
, DeferredChecks
, false))
1296 return MatchIntrinsicTypes_NoMatchArg
;
1298 for (unsigned I
= 0, E
= DeferredChecks
.size(); I
!= E
; ++I
) {
1299 DeferredIntrinsicMatchPair
&Check
= DeferredChecks
[I
];
1300 if (matchIntrinsicType(Check
.first
, Check
.second
, ArgTys
, DeferredChecks
,
1302 return I
< NumDeferredReturnChecks
? MatchIntrinsicTypes_NoMatchRet
1303 : MatchIntrinsicTypes_NoMatchArg
;
1306 return MatchIntrinsicTypes_Match
;
1310 Intrinsic::matchIntrinsicVarArg(bool isVarArg
,
1311 ArrayRef
<Intrinsic::IITDescriptor
> &Infos
) {
1312 // If there are no descriptors left, then it can't be a vararg.
1316 // There should be only one descriptor remaining at this point.
1317 if (Infos
.size() != 1)
1320 // Check and verify the descriptor.
1321 IITDescriptor D
= Infos
.front();
1322 Infos
= Infos
.slice(1);
1323 if (D
.Kind
== IITDescriptor::VarArg
)
1329 Optional
<Function
*> Intrinsic::remangleIntrinsicFunction(Function
*F
) {
1330 Intrinsic::ID ID
= F
->getIntrinsicID();
1334 FunctionType
*FTy
= F
->getFunctionType();
1335 // Accumulate an array of overloaded types for the given intrinsic
1336 SmallVector
<Type
*, 4> ArgTys
;
1338 SmallVector
<Intrinsic::IITDescriptor
, 8> Table
;
1339 getIntrinsicInfoTableEntries(ID
, Table
);
1340 ArrayRef
<Intrinsic::IITDescriptor
> TableRef
= Table
;
1342 if (Intrinsic::matchIntrinsicSignature(FTy
, TableRef
, ArgTys
))
1344 if (Intrinsic::matchIntrinsicVarArg(FTy
->isVarArg(), TableRef
))
1348 StringRef Name
= F
->getName();
1349 if (Name
== Intrinsic::getName(ID
, ArgTys
))
1352 auto NewDecl
= Intrinsic::getDeclaration(F
->getParent(), ID
, ArgTys
);
1353 NewDecl
->setCallingConv(F
->getCallingConv());
1354 assert(NewDecl
->getFunctionType() == FTy
&& "Shouldn't change the signature");
1358 /// hasAddressTaken - returns true if there are any uses of this function
1359 /// other than direct calls or invokes to it.
1360 bool Function::hasAddressTaken(const User
* *PutOffender
) const {
1361 for (const Use
&U
: uses()) {
1362 const User
*FU
= U
.getUser();
1363 if (isa
<BlockAddress
>(FU
))
1365 const auto *Call
= dyn_cast
<CallBase
>(FU
);
1371 if (!Call
->isCallee(&U
)) {
1380 bool Function::isDefTriviallyDead() const {
1381 // Check the linkage
1382 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1383 !hasAvailableExternallyLinkage())
1386 // Check if the function is used by anything other than a blockaddress.
1387 for (const User
*U
: users())
1388 if (!isa
<BlockAddress
>(U
))
1394 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1395 /// setjmp or other function that gcc recognizes as "returning twice".
1396 bool Function::callsFunctionThatReturnsTwice() const {
1397 for (const Instruction
&I
: instructions(this))
1398 if (const auto *Call
= dyn_cast
<CallBase
>(&I
))
1399 if (Call
->hasFnAttr(Attribute::ReturnsTwice
))
1405 Constant
*Function::getPersonalityFn() const {
1406 assert(hasPersonalityFn() && getNumOperands());
1407 return cast
<Constant
>(Op
<0>());
1410 void Function::setPersonalityFn(Constant
*Fn
) {
1411 setHungoffOperand
<0>(Fn
);
1412 setValueSubclassDataBit(3, Fn
!= nullptr);
1415 Constant
*Function::getPrefixData() const {
1416 assert(hasPrefixData() && getNumOperands());
1417 return cast
<Constant
>(Op
<1>());
1420 void Function::setPrefixData(Constant
*PrefixData
) {
1421 setHungoffOperand
<1>(PrefixData
);
1422 setValueSubclassDataBit(1, PrefixData
!= nullptr);
1425 Constant
*Function::getPrologueData() const {
1426 assert(hasPrologueData() && getNumOperands());
1427 return cast
<Constant
>(Op
<2>());
1430 void Function::setPrologueData(Constant
*PrologueData
) {
1431 setHungoffOperand
<2>(PrologueData
);
1432 setValueSubclassDataBit(2, PrologueData
!= nullptr);
1435 void Function::allocHungoffUselist() {
1436 // If we've already allocated a uselist, stop here.
1437 if (getNumOperands())
1440 allocHungoffUses(3, /*IsPhi=*/ false);
1441 setNumHungOffUseOperands(3);
1443 // Initialize the uselist with placeholder operands to allow traversal.
1444 auto *CPN
= ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
1451 void Function::setHungoffOperand(Constant
*C
) {
1453 allocHungoffUselist();
1455 } else if (getNumOperands()) {
1457 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
1461 void Function::setValueSubclassDataBit(unsigned Bit
, bool On
) {
1462 assert(Bit
< 16 && "SubclassData contains only 16 bits");
1464 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit
));
1466 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit
));
1469 void Function::setEntryCount(ProfileCount Count
,
1470 const DenseSet
<GlobalValue::GUID
> *S
) {
1471 assert(Count
.hasValue());
1472 #if !defined(NDEBUG)
1473 auto PrevCount
= getEntryCount();
1474 assert(!PrevCount
.hasValue() || PrevCount
.getType() == Count
.getType());
1476 MDBuilder
MDB(getContext());
1478 LLVMContext::MD_prof
,
1479 MDB
.createFunctionEntryCount(Count
.getCount(), Count
.isSynthetic(), S
));
1482 void Function::setEntryCount(uint64_t Count
, Function::ProfileCountType Type
,
1483 const DenseSet
<GlobalValue::GUID
> *Imports
) {
1484 setEntryCount(ProfileCount(Count
, Type
), Imports
);
1487 ProfileCount
Function::getEntryCount(bool AllowSynthetic
) const {
1488 MDNode
*MD
= getMetadata(LLVMContext::MD_prof
);
1489 if (MD
&& MD
->getOperand(0))
1490 if (MDString
*MDS
= dyn_cast
<MDString
>(MD
->getOperand(0))) {
1491 if (MDS
->getString().equals("function_entry_count")) {
1492 ConstantInt
*CI
= mdconst::extract
<ConstantInt
>(MD
->getOperand(1));
1493 uint64_t Count
= CI
->getValue().getZExtValue();
1494 // A value of -1 is used for SamplePGO when there were no samples.
1495 // Treat this the same as unknown.
1496 if (Count
== (uint64_t)-1)
1497 return ProfileCount::getInvalid();
1498 return ProfileCount(Count
, PCT_Real
);
1499 } else if (AllowSynthetic
&&
1500 MDS
->getString().equals("synthetic_function_entry_count")) {
1501 ConstantInt
*CI
= mdconst::extract
<ConstantInt
>(MD
->getOperand(1));
1502 uint64_t Count
= CI
->getValue().getZExtValue();
1503 return ProfileCount(Count
, PCT_Synthetic
);
1506 return ProfileCount::getInvalid();
1509 DenseSet
<GlobalValue::GUID
> Function::getImportGUIDs() const {
1510 DenseSet
<GlobalValue::GUID
> R
;
1511 if (MDNode
*MD
= getMetadata(LLVMContext::MD_prof
))
1512 if (MDString
*MDS
= dyn_cast
<MDString
>(MD
->getOperand(0)))
1513 if (MDS
->getString().equals("function_entry_count"))
1514 for (unsigned i
= 2; i
< MD
->getNumOperands(); i
++)
1515 R
.insert(mdconst::extract
<ConstantInt
>(MD
->getOperand(i
))
1521 void Function::setSectionPrefix(StringRef Prefix
) {
1522 MDBuilder
MDB(getContext());
1523 setMetadata(LLVMContext::MD_section_prefix
,
1524 MDB
.createFunctionSectionPrefix(Prefix
));
1527 Optional
<StringRef
> Function::getSectionPrefix() const {
1528 if (MDNode
*MD
= getMetadata(LLVMContext::MD_section_prefix
)) {
1529 assert(cast
<MDString
>(MD
->getOperand(0))
1531 .equals("function_section_prefix") &&
1532 "Metadata not match");
1533 return cast
<MDString
>(MD
->getOperand(1))->getString();
1538 bool Function::nullPointerIsDefined() const {
1539 return getFnAttribute("null-pointer-is-valid")
1544 bool llvm::NullPointerIsDefined(const Function
*F
, unsigned AS
) {
1545 if (F
&& F
->nullPointerIsDefined())