1 //===-- Function.cpp - Implement the Global object classes ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Function class for the IR library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Function.h"
15 #include "LLVMContextImpl.h"
16 #include "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/CodeGen/ValueTypes.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/MDBuilder.h"
27 #include "llvm/IR/Metadata.h"
28 #include "llvm/IR/Module.h"
31 // Explicit instantiations of SymbolTableListTraits since some of the methods
32 // are not in the public header file...
33 template class llvm::SymbolTableListTraits<BasicBlock>;
35 //===----------------------------------------------------------------------===//
36 // Argument Implementation
37 //===----------------------------------------------------------------------===//
39 void Argument::anchor() { }
41 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
42 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
46 void Argument::setParent(Function *parent) {
50 bool Argument::hasNonNullAttr() const {
51 if (!getType()->isPointerTy()) return false;
52 if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull))
54 else if (getDereferenceableBytes() > 0 &&
55 getType()->getPointerAddressSpace() == 0)
60 bool Argument::hasByValAttr() const {
61 if (!getType()->isPointerTy()) return false;
62 return hasAttribute(Attribute::ByVal);
65 bool Argument::hasSwiftSelfAttr() const {
66 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
69 bool Argument::hasSwiftErrorAttr() const {
70 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
73 bool Argument::hasInAllocaAttr() const {
74 if (!getType()->isPointerTy()) return false;
75 return hasAttribute(Attribute::InAlloca);
78 bool Argument::hasByValOrInAllocaAttr() const {
79 if (!getType()->isPointerTy()) return false;
80 AttributeList Attrs = getParent()->getAttributes();
81 return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
82 Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca);
85 unsigned Argument::getParamAlignment() const {
86 assert(getType()->isPointerTy() && "Only pointers have alignments");
87 return getParent()->getParamAlignment(getArgNo());
90 uint64_t Argument::getDereferenceableBytes() const {
91 assert(getType()->isPointerTy() &&
92 "Only pointers have dereferenceable bytes");
93 return getParent()->getDereferenceableBytes(getArgNo() +
94 AttributeList::FirstArgIndex);
97 uint64_t Argument::getDereferenceableOrNullBytes() const {
98 assert(getType()->isPointerTy() &&
99 "Only pointers have dereferenceable bytes");
100 return getParent()->getDereferenceableOrNullBytes(
101 getArgNo() + AttributeList::FirstArgIndex);
104 bool Argument::hasNestAttr() const {
105 if (!getType()->isPointerTy()) return false;
106 return hasAttribute(Attribute::Nest);
109 bool Argument::hasNoAliasAttr() const {
110 if (!getType()->isPointerTy()) return false;
111 return hasAttribute(Attribute::NoAlias);
114 bool Argument::hasNoCaptureAttr() const {
115 if (!getType()->isPointerTy()) return false;
116 return hasAttribute(Attribute::NoCapture);
119 bool Argument::hasStructRetAttr() const {
120 if (!getType()->isPointerTy()) return false;
121 return hasAttribute(Attribute::StructRet);
124 bool Argument::hasReturnedAttr() const {
125 return hasAttribute(Attribute::Returned);
128 bool Argument::hasZExtAttr() const {
129 return hasAttribute(Attribute::ZExt);
132 bool Argument::hasSExtAttr() const {
133 return hasAttribute(Attribute::SExt);
136 bool Argument::onlyReadsMemory() const {
137 AttributeList Attrs = getParent()->getAttributes();
138 return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
139 Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
142 void Argument::addAttrs(AttrBuilder &B) {
143 AttributeList AL = getParent()->getAttributes();
144 AL = AL.addAttributes(Parent->getContext(),
145 getArgNo() + AttributeList::FirstArgIndex, B);
146 getParent()->setAttributes(AL);
149 void Argument::addAttr(Attribute::AttrKind Kind) {
150 getParent()->addAttribute(getArgNo() + AttributeList::FirstArgIndex, Kind);
153 void Argument::addAttr(Attribute Attr) {
154 getParent()->addAttribute(getArgNo() + AttributeList::FirstArgIndex, Attr);
157 void Argument::removeAttr(Attribute::AttrKind Kind) {
158 getParent()->removeAttribute(getArgNo() + AttributeList::FirstArgIndex, Kind);
161 bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
162 return getParent()->hasParamAttribute(getArgNo(), Kind);
165 //===----------------------------------------------------------------------===//
166 // Helper Methods in Function
167 //===----------------------------------------------------------------------===//
169 LLVMContext &Function::getContext() const {
170 return getType()->getContext();
173 void Function::removeFromParent() {
174 getParent()->getFunctionList().remove(getIterator());
177 void Function::eraseFromParent() {
178 getParent()->getFunctionList().erase(getIterator());
181 //===----------------------------------------------------------------------===//
182 // Function Implementation
183 //===----------------------------------------------------------------------===//
185 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
186 Module *ParentModule)
187 : GlobalObject(Ty, Value::FunctionVal,
188 OperandTraits<Function>::op_begin(this), 0, Linkage, name),
189 Arguments(nullptr), NumArgs(Ty->getNumParams()) {
190 assert(FunctionType::isValidReturnType(getReturnType()) &&
191 "invalid return type");
192 setGlobalObjectSubClassData(0);
194 // We only need a symbol table for a function if the context keeps value names
195 if (!getContext().shouldDiscardValueNames())
196 SymTab = make_unique<ValueSymbolTable>();
198 // If the function has arguments, mark them as lazily built.
199 if (Ty->getNumParams())
200 setValueSubclassData(1); // Set the "has lazy arguments" bit.
203 ParentModule->getFunctionList().push_back(this);
205 HasLLVMReservedName = getName().startswith("llvm.");
206 // Ensure intrinsics have the right parameter attributes.
207 // Note, the IntID field will have been set in Value::setName if this function
208 // name is a valid intrinsic ID.
210 setAttributes(Intrinsic::getAttributes(getContext(), IntID));
213 Function::~Function() {
214 dropAllReferences(); // After this it is safe to delete instructions.
216 // Delete all of the method arguments and unlink from symbol table...
220 // Remove the function from the on-the-side GC table.
224 void Function::BuildLazyArguments() const {
225 // Create the arguments vector, all arguments start out unnamed.
226 auto *FT = getFunctionType();
228 Arguments = std::allocator<Argument>().allocate(NumArgs);
229 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
230 Type *ArgTy = FT->getParamType(i);
231 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
232 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
236 // Clear the lazy arguments bit.
237 unsigned SDC = getSubclassDataFromValue();
238 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
239 assert(!hasLazyArguments());
242 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
243 return MutableArrayRef<Argument>(Args, Count);
246 void Function::clearArguments() {
247 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
251 std::allocator<Argument>().deallocate(Arguments, NumArgs);
255 void Function::stealArgumentListFrom(Function &Src) {
256 assert(isDeclaration() && "Expected no references to current arguments");
258 // Drop the current arguments, if any, and set the lazy argument bit.
259 if (!hasLazyArguments()) {
260 assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
261 [](const Argument &A) { return A.use_empty(); }) &&
262 "Expected arguments to be unused in declaration");
264 setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
267 // Nothing to steal if Src has lazy arguments.
268 if (Src.hasLazyArguments())
271 // Steal arguments from Src, and fix the lazy argument bits.
272 assert(arg_size() == Src.arg_size());
273 Arguments = Src.Arguments;
274 Src.Arguments = nullptr;
275 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
276 // FIXME: This does the work of transferNodesFromList inefficiently.
277 SmallString<128> Name;
287 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
288 assert(!hasLazyArguments());
289 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
292 // dropAllReferences() - This function causes all the subinstructions to "let
293 // go" of all references that they are maintaining. This allows one to
294 // 'delete' a whole class at a time, even though there may be circular
295 // references... first all references are dropped, and all use counts go to
296 // zero. Then everything is deleted for real. Note that no operations are
297 // valid on an object that has "dropped all references", except operator
300 void Function::dropAllReferences() {
301 setIsMaterializable(false);
303 for (BasicBlock &BB : *this)
304 BB.dropAllReferences();
306 // Delete all basic blocks. They are now unused, except possibly by
307 // blockaddresses, but BasicBlock's destructor takes care of those.
308 while (!BasicBlocks.empty())
309 BasicBlocks.begin()->eraseFromParent();
311 // Drop uses of any optional data (real or placeholder).
312 if (getNumOperands()) {
313 User::dropAllReferences();
314 setNumHungOffUseOperands(0);
315 setValueSubclassData(getSubclassDataFromValue() & ~0xe);
318 // Metadata is stored in a side-table.
322 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
323 AttributeList PAL = getAttributes();
324 PAL = PAL.addAttribute(getContext(), i, Kind);
328 void Function::addAttribute(unsigned i, Attribute Attr) {
329 AttributeList PAL = getAttributes();
330 PAL = PAL.addAttribute(getContext(), i, Attr);
334 void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
335 AttributeList PAL = getAttributes();
336 PAL = PAL.addAttributes(getContext(), i, Attrs);
340 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
341 AttributeList PAL = getAttributes();
342 PAL = PAL.removeAttribute(getContext(), i, Kind);
346 void Function::removeAttribute(unsigned i, StringRef Kind) {
347 AttributeList PAL = getAttributes();
348 PAL = PAL.removeAttribute(getContext(), i, Kind);
352 void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
353 AttributeList PAL = getAttributes();
354 PAL = PAL.removeAttributes(getContext(), i, Attrs);
358 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
359 AttributeList PAL = getAttributes();
360 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
364 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
365 AttributeList PAL = getAttributes();
366 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
370 const std::string &Function::getGC() const {
371 assert(hasGC() && "Function has no collector");
372 return getContext().getGC(*this);
375 void Function::setGC(std::string Str) {
376 setValueSubclassDataBit(14, !Str.empty());
377 getContext().setGC(*this, std::move(Str));
380 void Function::clearGC() {
383 getContext().deleteGC(*this);
384 setValueSubclassDataBit(14, false);
387 /// Copy all additional attributes (those not needed to create a Function) from
388 /// the Function Src to this one.
389 void Function::copyAttributesFrom(const GlobalValue *Src) {
390 GlobalObject::copyAttributesFrom(Src);
391 const Function *SrcF = dyn_cast<Function>(Src);
395 setCallingConv(SrcF->getCallingConv());
396 setAttributes(SrcF->getAttributes());
398 setGC(SrcF->getGC());
401 if (SrcF->hasPersonalityFn())
402 setPersonalityFn(SrcF->getPersonalityFn());
403 if (SrcF->hasPrefixData())
404 setPrefixData(SrcF->getPrefixData());
405 if (SrcF->hasPrologueData())
406 setPrologueData(SrcF->getPrologueData());
409 /// Table of string intrinsic names indexed by enum value.
410 static const char * const IntrinsicNameTable[] = {
412 #define GET_INTRINSIC_NAME_TABLE
413 #include "llvm/IR/Intrinsics.gen"
414 #undef GET_INTRINSIC_NAME_TABLE
417 /// Table of per-target intrinsic name tables.
418 #define GET_INTRINSIC_TARGET_DATA
419 #include "llvm/IR/Intrinsics.gen"
420 #undef GET_INTRINSIC_TARGET_DATA
422 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
423 /// target as \c Name, or the generic table if \c Name is not target specific.
425 /// Returns the relevant slice of \c IntrinsicNameTable
426 static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
427 assert(Name.startswith("llvm."));
429 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
430 // Drop "llvm." and take the first dotted component. That will be the target
431 // if this is target specific.
432 StringRef Target = Name.drop_front(5).split('.').first;
433 auto It = std::lower_bound(Targets.begin(), Targets.end(), Target,
434 [](const IntrinsicTargetInfo &TI,
435 StringRef Target) { return TI.Name < Target; });
436 // We've either found the target or just fall back to the generic set, which
438 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
439 return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
442 /// \brief This does the actual lookup of an intrinsic ID which
443 /// matches the given function name.
444 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
445 ArrayRef<const char *> NameTable = findTargetSubtable(Name);
446 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
448 return Intrinsic::not_intrinsic;
450 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
451 // an index into a sub-table.
452 int Adjust = NameTable.data() - IntrinsicNameTable;
453 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
455 // If the intrinsic is not overloaded, require an exact match. If it is
456 // overloaded, require a prefix match.
457 bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]);
458 return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic;
461 void Function::recalculateIntrinsicID() {
462 StringRef Name = getName();
463 if (!Name.startswith("llvm.")) {
464 HasLLVMReservedName = false;
465 IntID = Intrinsic::not_intrinsic;
468 HasLLVMReservedName = true;
469 IntID = lookupIntrinsicID(Name);
472 /// Returns a stable mangling for the type specified for use in the name
473 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
474 /// of named types is simply their name. Manglings for unnamed types consist
475 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
476 /// combined with the mangling of their component types. A vararg function
477 /// type will have a suffix of 'vararg'. Since function types can contain
478 /// other function types, we close a function type mangling with suffix 'f'
479 /// which can't be confused with it's prefix. This ensures we don't have
480 /// collisions between two unrelated function types. Otherwise, you might
481 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
482 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
483 /// cases) fall back to the MVT codepath, where they could be mangled to
484 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle
486 static std::string getMangledTypeStr(Type* Ty) {
488 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
489 Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
490 getMangledTypeStr(PTyp->getElementType());
491 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
492 Result += "a" + llvm::utostr(ATyp->getNumElements()) +
493 getMangledTypeStr(ATyp->getElementType());
494 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
495 if (!STyp->isLiteral()) {
497 Result += STyp->getName();
500 for (auto Elem : STyp->elements())
501 Result += getMangledTypeStr(Elem);
503 // Ensure nested structs are distinguishable.
505 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
506 Result += "f_" + getMangledTypeStr(FT->getReturnType());
507 for (size_t i = 0; i < FT->getNumParams(); i++)
508 Result += getMangledTypeStr(FT->getParamType(i));
511 // Ensure nested function types are distinguishable.
513 } else if (isa<VectorType>(Ty))
514 Result += "v" + utostr(Ty->getVectorNumElements()) +
515 getMangledTypeStr(Ty->getVectorElementType());
517 Result += EVT::getEVT(Ty).getEVTString();
521 StringRef Intrinsic::getName(ID id) {
522 assert(id < num_intrinsics && "Invalid intrinsic ID!");
523 assert(!isOverloaded(id) &&
524 "This version of getName does not support overloading");
525 return IntrinsicNameTable[id];
528 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
529 assert(id < num_intrinsics && "Invalid intrinsic ID!");
530 std::string Result(IntrinsicNameTable[id]);
531 for (Type *Ty : Tys) {
532 Result += "." + getMangledTypeStr(Ty);
538 /// IIT_Info - These are enumerators that describe the entries returned by the
539 /// getIntrinsicInfoTableEntries function.
541 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
543 // Common values should be encoded with 0-15.
561 // Values from 16+ are only encodable with the inefficient encoding.
566 IIT_EMPTYSTRUCT = 20,
576 IIT_HALF_VEC_ARG = 30,
577 IIT_SAME_VEC_WIDTH_ARG = 31,
580 IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
586 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
587 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
588 IIT_Info Info = IIT_Info(Infos[NextElt++]);
589 unsigned StructElts = 2;
590 using namespace Intrinsic;
594 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
597 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
600 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
603 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
606 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
609 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
612 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
615 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
618 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
621 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
624 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
627 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
630 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
633 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
636 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
637 DecodeIITType(NextElt, Infos, OutputTable);
640 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
641 DecodeIITType(NextElt, Infos, OutputTable);
644 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
645 DecodeIITType(NextElt, Infos, OutputTable);
648 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
649 DecodeIITType(NextElt, Infos, OutputTable);
652 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
653 DecodeIITType(NextElt, Infos, OutputTable);
656 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
657 DecodeIITType(NextElt, Infos, OutputTable);
660 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
661 DecodeIITType(NextElt, Infos, OutputTable);
664 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
665 DecodeIITType(NextElt, Infos, OutputTable);
668 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
669 DecodeIITType(NextElt, Infos, OutputTable);
672 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
673 DecodeIITType(NextElt, Infos, OutputTable);
675 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
676 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
678 DecodeIITType(NextElt, Infos, OutputTable);
682 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
683 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
686 case IIT_EXTEND_ARG: {
687 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
688 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
692 case IIT_TRUNC_ARG: {
693 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
694 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
698 case IIT_HALF_VEC_ARG: {
699 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
700 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
704 case IIT_SAME_VEC_WIDTH_ARG: {
705 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
706 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
710 case IIT_PTR_TO_ARG: {
711 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
712 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
716 case IIT_PTR_TO_ELT: {
717 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
718 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
721 case IIT_VEC_OF_ANYPTRS_TO_ELT: {
722 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
723 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
724 OutputTable.push_back(
725 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
728 case IIT_EMPTYSTRUCT:
729 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
731 case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
732 case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
733 case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
735 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
737 for (unsigned i = 0; i != StructElts; ++i)
738 DecodeIITType(NextElt, Infos, OutputTable);
742 llvm_unreachable("unhandled");
746 #define GET_INTRINSIC_GENERATOR_GLOBAL
747 #include "llvm/IR/Intrinsics.gen"
748 #undef GET_INTRINSIC_GENERATOR_GLOBAL
750 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
751 SmallVectorImpl<IITDescriptor> &T){
752 // Check to see if the intrinsic's type was expressible by the table.
753 unsigned TableVal = IIT_Table[id-1];
755 // Decode the TableVal into an array of IITValues.
756 SmallVector<unsigned char, 8> IITValues;
757 ArrayRef<unsigned char> IITEntries;
758 unsigned NextElt = 0;
759 if ((TableVal >> 31) != 0) {
760 // This is an offset into the IIT_LongEncodingTable.
761 IITEntries = IIT_LongEncodingTable;
763 // Strip sentinel bit.
764 NextElt = (TableVal << 1) >> 1;
766 // Decode the TableVal into an array of IITValues. If the entry was encoded
767 // into a single word in the table itself, decode it now.
769 IITValues.push_back(TableVal & 0xF);
773 IITEntries = IITValues;
777 // Okay, decode the table into the output vector of IITDescriptors.
778 DecodeIITType(NextElt, IITEntries, T);
779 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
780 DecodeIITType(NextElt, IITEntries, T);
784 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
785 ArrayRef<Type*> Tys, LLVMContext &Context) {
786 using namespace Intrinsic;
787 IITDescriptor D = Infos.front();
788 Infos = Infos.slice(1);
791 case IITDescriptor::Void: return Type::getVoidTy(Context);
792 case IITDescriptor::VarArg: return Type::getVoidTy(Context);
793 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
794 case IITDescriptor::Token: return Type::getTokenTy(Context);
795 case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
796 case IITDescriptor::Half: return Type::getHalfTy(Context);
797 case IITDescriptor::Float: return Type::getFloatTy(Context);
798 case IITDescriptor::Double: return Type::getDoubleTy(Context);
800 case IITDescriptor::Integer:
801 return IntegerType::get(Context, D.Integer_Width);
802 case IITDescriptor::Vector:
803 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
804 case IITDescriptor::Pointer:
805 return PointerType::get(DecodeFixedType(Infos, Tys, Context),
806 D.Pointer_AddressSpace);
807 case IITDescriptor::Struct: {
809 assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
810 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
811 Elts[i] = DecodeFixedType(Infos, Tys, Context);
812 return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
814 case IITDescriptor::Argument:
815 return Tys[D.getArgumentNumber()];
816 case IITDescriptor::ExtendArgument: {
817 Type *Ty = Tys[D.getArgumentNumber()];
818 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
819 return VectorType::getExtendedElementVectorType(VTy);
821 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
823 case IITDescriptor::TruncArgument: {
824 Type *Ty = Tys[D.getArgumentNumber()];
825 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
826 return VectorType::getTruncatedElementVectorType(VTy);
828 IntegerType *ITy = cast<IntegerType>(Ty);
829 assert(ITy->getBitWidth() % 2 == 0);
830 return IntegerType::get(Context, ITy->getBitWidth() / 2);
832 case IITDescriptor::HalfVecArgument:
833 return VectorType::getHalfElementsVectorType(cast<VectorType>(
834 Tys[D.getArgumentNumber()]));
835 case IITDescriptor::SameVecWidthArgument: {
836 Type *EltTy = DecodeFixedType(Infos, Tys, Context);
837 Type *Ty = Tys[D.getArgumentNumber()];
838 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
839 return VectorType::get(EltTy, VTy->getNumElements());
841 llvm_unreachable("unhandled");
843 case IITDescriptor::PtrToArgument: {
844 Type *Ty = Tys[D.getArgumentNumber()];
845 return PointerType::getUnqual(Ty);
847 case IITDescriptor::PtrToElt: {
848 Type *Ty = Tys[D.getArgumentNumber()];
849 VectorType *VTy = dyn_cast<VectorType>(Ty);
851 llvm_unreachable("Expected an argument of Vector Type");
852 Type *EltTy = VTy->getVectorElementType();
853 return PointerType::getUnqual(EltTy);
855 case IITDescriptor::VecOfAnyPtrsToElt:
856 // Return the overloaded type (which determines the pointers address space)
857 return Tys[D.getOverloadArgNumber()];
859 llvm_unreachable("unhandled");
864 FunctionType *Intrinsic::getType(LLVMContext &Context,
865 ID id, ArrayRef<Type*> Tys) {
866 SmallVector<IITDescriptor, 8> Table;
867 getIntrinsicInfoTableEntries(id, Table);
869 ArrayRef<IITDescriptor> TableRef = Table;
870 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
872 SmallVector<Type*, 8> ArgTys;
873 while (!TableRef.empty())
874 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
876 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
877 // If we see void type as the type of the last argument, it is vararg intrinsic
878 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
880 return FunctionType::get(ResultTy, ArgTys, true);
882 return FunctionType::get(ResultTy, ArgTys, false);
885 bool Intrinsic::isOverloaded(ID id) {
886 #define GET_INTRINSIC_OVERLOAD_TABLE
887 #include "llvm/IR/Intrinsics.gen"
888 #undef GET_INTRINSIC_OVERLOAD_TABLE
891 bool Intrinsic::isLeaf(ID id) {
896 case Intrinsic::experimental_gc_statepoint:
897 case Intrinsic::experimental_patchpoint_void:
898 case Intrinsic::experimental_patchpoint_i64:
903 /// This defines the "Intrinsic::getAttributes(ID id)" method.
904 #define GET_INTRINSIC_ATTRIBUTES
905 #include "llvm/IR/Intrinsics.gen"
906 #undef GET_INTRINSIC_ATTRIBUTES
908 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
909 // There can never be multiple globals with the same name of different types,
910 // because intrinsics must be a specific type.
912 cast<Function>(M->getOrInsertFunction(getName(id, Tys),
913 getType(M->getContext(), id, Tys)));
916 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
917 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
918 #include "llvm/IR/Intrinsics.gen"
919 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
921 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
922 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
923 #include "llvm/IR/Intrinsics.gen"
924 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
926 bool Intrinsic::matchIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
927 SmallVectorImpl<Type*> &ArgTys) {
928 using namespace Intrinsic;
930 // If we ran out of descriptors, there are too many arguments.
931 if (Infos.empty()) return true;
932 IITDescriptor D = Infos.front();
933 Infos = Infos.slice(1);
936 case IITDescriptor::Void: return !Ty->isVoidTy();
937 case IITDescriptor::VarArg: return true;
938 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
939 case IITDescriptor::Token: return !Ty->isTokenTy();
940 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
941 case IITDescriptor::Half: return !Ty->isHalfTy();
942 case IITDescriptor::Float: return !Ty->isFloatTy();
943 case IITDescriptor::Double: return !Ty->isDoubleTy();
944 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
945 case IITDescriptor::Vector: {
946 VectorType *VT = dyn_cast<VectorType>(Ty);
947 return !VT || VT->getNumElements() != D.Vector_Width ||
948 matchIntrinsicType(VT->getElementType(), Infos, ArgTys);
950 case IITDescriptor::Pointer: {
951 PointerType *PT = dyn_cast<PointerType>(Ty);
952 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
953 matchIntrinsicType(PT->getElementType(), Infos, ArgTys);
956 case IITDescriptor::Struct: {
957 StructType *ST = dyn_cast<StructType>(Ty);
958 if (!ST || ST->getNumElements() != D.Struct_NumElements)
961 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
962 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys))
967 case IITDescriptor::Argument:
968 // Two cases here - If this is the second occurrence of an argument, verify
969 // that the later instance matches the previous instance.
970 if (D.getArgumentNumber() < ArgTys.size())
971 return Ty != ArgTys[D.getArgumentNumber()];
973 // Otherwise, if this is the first instance of an argument, record it and
974 // verify the "Any" kind.
975 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
976 ArgTys.push_back(Ty);
978 switch (D.getArgumentKind()) {
979 case IITDescriptor::AK_Any: return false; // Success
980 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
981 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
982 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
983 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
985 llvm_unreachable("all argument kinds not covered");
987 case IITDescriptor::ExtendArgument: {
988 // This may only be used when referring to a previous vector argument.
989 if (D.getArgumentNumber() >= ArgTys.size())
992 Type *NewTy = ArgTys[D.getArgumentNumber()];
993 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
994 NewTy = VectorType::getExtendedElementVectorType(VTy);
995 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
996 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
1002 case IITDescriptor::TruncArgument: {
1003 // This may only be used when referring to a previous vector argument.
1004 if (D.getArgumentNumber() >= ArgTys.size())
1007 Type *NewTy = ArgTys[D.getArgumentNumber()];
1008 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1009 NewTy = VectorType::getTruncatedElementVectorType(VTy);
1010 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1011 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
1017 case IITDescriptor::HalfVecArgument:
1018 // This may only be used when referring to a previous vector argument.
1019 return D.getArgumentNumber() >= ArgTys.size() ||
1020 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1021 VectorType::getHalfElementsVectorType(
1022 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1023 case IITDescriptor::SameVecWidthArgument: {
1024 if (D.getArgumentNumber() >= ArgTys.size())
1026 VectorType * ReferenceType =
1027 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1028 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
1029 if (!ThisArgType || !ReferenceType ||
1030 (ReferenceType->getVectorNumElements() !=
1031 ThisArgType->getVectorNumElements()))
1033 return matchIntrinsicType(ThisArgType->getVectorElementType(),
1036 case IITDescriptor::PtrToArgument: {
1037 if (D.getArgumentNumber() >= ArgTys.size())
1039 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
1040 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1041 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
1043 case IITDescriptor::PtrToElt: {
1044 if (D.getArgumentNumber() >= ArgTys.size())
1046 VectorType * ReferenceType =
1047 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
1048 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1050 return (!ThisArgType || !ReferenceType ||
1051 ThisArgType->getElementType() != ReferenceType->getElementType());
1053 case IITDescriptor::VecOfAnyPtrsToElt: {
1054 unsigned RefArgNumber = D.getRefArgNumber();
1056 // This may only be used when referring to a previous argument.
1057 if (RefArgNumber >= ArgTys.size())
1060 // Record the overloaded type
1061 assert(D.getOverloadArgNumber() == ArgTys.size() &&
1062 "Table consistency error");
1063 ArgTys.push_back(Ty);
1065 // Verify the overloaded type "matches" the Ref type.
1066 // i.e. Ty is a vector with the same width as Ref.
1067 // Composed of pointers to the same element type as Ref.
1068 VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
1069 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1070 if (!ThisArgVecTy || !ReferenceType ||
1071 (ReferenceType->getVectorNumElements() !=
1072 ThisArgVecTy->getVectorNumElements()))
1074 PointerType *ThisArgEltTy =
1075 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
1078 return ThisArgEltTy->getElementType() !=
1079 ReferenceType->getVectorElementType();
1082 llvm_unreachable("unhandled");
1086 Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1087 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1088 // If there are no descriptors left, then it can't be a vararg.
1092 // There should be only one descriptor remaining at this point.
1093 if (Infos.size() != 1)
1096 // Check and verify the descriptor.
1097 IITDescriptor D = Infos.front();
1098 Infos = Infos.slice(1);
1099 if (D.Kind == IITDescriptor::VarArg)
1105 Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) {
1106 Intrinsic::ID ID = F->getIntrinsicID();
1110 FunctionType *FTy = F->getFunctionType();
1111 // Accumulate an array of overloaded types for the given intrinsic
1112 SmallVector<Type *, 4> ArgTys;
1114 SmallVector<Intrinsic::IITDescriptor, 8> Table;
1115 getIntrinsicInfoTableEntries(ID, Table);
1116 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1118 // If we encounter any problems matching the signature with the descriptor
1119 // just give up remangling. It's up to verifier to report the discrepancy.
1120 if (Intrinsic::matchIntrinsicType(FTy->getReturnType(), TableRef, ArgTys))
1122 for (auto Ty : FTy->params())
1123 if (Intrinsic::matchIntrinsicType(Ty, TableRef, ArgTys))
1125 if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef))
1129 StringRef Name = F->getName();
1130 if (Name == Intrinsic::getName(ID, ArgTys))
1133 auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
1134 NewDecl->setCallingConv(F->getCallingConv());
1135 assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature");
1139 /// hasAddressTaken - returns true if there are any uses of this function
1140 /// other than direct calls or invokes to it.
1141 bool Function::hasAddressTaken(const User* *PutOffender) const {
1142 for (const Use &U : uses()) {
1143 const User *FU = U.getUser();
1144 if (isa<BlockAddress>(FU))
1146 if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) {
1151 ImmutableCallSite CS(cast<Instruction>(FU));
1152 if (!CS.isCallee(&U)) {
1161 bool Function::isDefTriviallyDead() const {
1162 // Check the linkage
1163 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1164 !hasAvailableExternallyLinkage())
1167 // Check if the function is used by anything other than a blockaddress.
1168 for (const User *U : users())
1169 if (!isa<BlockAddress>(U))
1175 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1176 /// setjmp or other function that gcc recognizes as "returning twice".
1177 bool Function::callsFunctionThatReturnsTwice() const {
1178 for (const_inst_iterator
1179 I = inst_begin(this), E = inst_end(this); I != E; ++I) {
1180 ImmutableCallSite CS(&*I);
1181 if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
1188 Constant *Function::getPersonalityFn() const {
1189 assert(hasPersonalityFn() && getNumOperands());
1190 return cast<Constant>(Op<0>());
1193 void Function::setPersonalityFn(Constant *Fn) {
1194 setHungoffOperand<0>(Fn);
1195 setValueSubclassDataBit(3, Fn != nullptr);
1198 Constant *Function::getPrefixData() const {
1199 assert(hasPrefixData() && getNumOperands());
1200 return cast<Constant>(Op<1>());
1203 void Function::setPrefixData(Constant *PrefixData) {
1204 setHungoffOperand<1>(PrefixData);
1205 setValueSubclassDataBit(1, PrefixData != nullptr);
1208 Constant *Function::getPrologueData() const {
1209 assert(hasPrologueData() && getNumOperands());
1210 return cast<Constant>(Op<2>());
1213 void Function::setPrologueData(Constant *PrologueData) {
1214 setHungoffOperand<2>(PrologueData);
1215 setValueSubclassDataBit(2, PrologueData != nullptr);
1218 void Function::allocHungoffUselist() {
1219 // If we've already allocated a uselist, stop here.
1220 if (getNumOperands())
1223 allocHungoffUses(3, /*IsPhi=*/ false);
1224 setNumHungOffUseOperands(3);
1226 // Initialize the uselist with placeholder operands to allow traversal.
1227 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
1234 void Function::setHungoffOperand(Constant *C) {
1236 allocHungoffUselist();
1238 } else if (getNumOperands()) {
1240 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
1244 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1245 assert(Bit < 16 && "SubclassData contains only 16 bits");
1247 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1249 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1252 void Function::setEntryCount(uint64_t Count,
1253 const DenseSet<GlobalValue::GUID> *S) {
1254 MDBuilder MDB(getContext());
1255 setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count, S));
1258 Optional<uint64_t> Function::getEntryCount() const {
1259 MDNode *MD = getMetadata(LLVMContext::MD_prof);
1260 if (MD && MD->getOperand(0))
1261 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1262 if (MDS->getString().equals("function_entry_count")) {
1263 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1264 uint64_t Count = CI->getValue().getZExtValue();
1272 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
1273 DenseSet<GlobalValue::GUID> R;
1274 if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1275 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1276 if (MDS->getString().equals("function_entry_count"))
1277 for (unsigned i = 2; i < MD->getNumOperands(); i++)
1278 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
1284 void Function::setSectionPrefix(StringRef Prefix) {
1285 MDBuilder MDB(getContext());
1286 setMetadata(LLVMContext::MD_section_prefix,
1287 MDB.createFunctionSectionPrefix(Prefix));
1290 Optional<StringRef> Function::getSectionPrefix() const {
1291 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
1292 assert(dyn_cast<MDString>(MD->getOperand(0))
1294 .equals("function_section_prefix") &&
1295 "Metadata not match");
1296 return dyn_cast<MDString>(MD->getOperand(1))->getString();