123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785 |
- //===- Function.cpp - Implement the Global object classes -----------------===//
- //
- // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
- // See https://llvm.org/LICENSE.txt for license information.
- // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
- //
- //===----------------------------------------------------------------------===//
- //
- // This file implements the Function class for the IR library.
- //
- //===----------------------------------------------------------------------===//
- #include "llvm/IR/Function.h"
- #include "SymbolTableListTraitsImpl.h"
- #include "llvm/ADT/ArrayRef.h"
- #include "llvm/ADT/DenseSet.h"
- #include "llvm/ADT/None.h"
- #include "llvm/ADT/STLExtras.h"
- #include "llvm/ADT/SmallString.h"
- #include "llvm/ADT/SmallVector.h"
- #include "llvm/ADT/StringExtras.h"
- #include "llvm/ADT/StringRef.h"
- #include "llvm/IR/AbstractCallSite.h"
- #include "llvm/IR/Argument.h"
- #include "llvm/IR/Attributes.h"
- #include "llvm/IR/BasicBlock.h"
- #include "llvm/IR/Constant.h"
- #include "llvm/IR/Constants.h"
- #include "llvm/IR/DerivedTypes.h"
- #include "llvm/IR/GlobalValue.h"
- #include "llvm/IR/InstIterator.h"
- #include "llvm/IR/Instruction.h"
- #include "llvm/IR/Instructions.h"
- #include "llvm/IR/Intrinsics.h"
- #include "llvm/IR/IntrinsicsAArch64.h"
- #include "llvm/IR/IntrinsicsAMDGPU.h"
- #include "llvm/IR/IntrinsicsARM.h"
- #include "llvm/IR/IntrinsicsBPF.h"
- #include "llvm/IR/IntrinsicsHexagon.h"
- #include "llvm/IR/IntrinsicsMips.h"
- #include "llvm/IR/IntrinsicsNVPTX.h"
- #include "llvm/IR/IntrinsicsPowerPC.h"
- #include "llvm/IR/IntrinsicsR600.h"
- #include "llvm/IR/IntrinsicsRISCV.h"
- #include "llvm/IR/IntrinsicsS390.h"
- #include "llvm/IR/IntrinsicsVE.h"
- #include "llvm/IR/IntrinsicsWebAssembly.h"
- #include "llvm/IR/IntrinsicsX86.h"
- #include "llvm/IR/IntrinsicsXCore.h"
- #include "llvm/IR/LLVMContext.h"
- #include "llvm/IR/MDBuilder.h"
- #include "llvm/IR/Metadata.h"
- #include "llvm/IR/Module.h"
- #include "llvm/IR/SymbolTableListTraits.h"
- #include "llvm/IR/Type.h"
- #include "llvm/IR/Use.h"
- #include "llvm/IR/User.h"
- #include "llvm/IR/Value.h"
- #include "llvm/IR/ValueSymbolTable.h"
- #include "llvm/Support/Casting.h"
- #include "llvm/Support/Compiler.h"
- #include "llvm/Support/ErrorHandling.h"
- #include <algorithm>
- #include <cassert>
- #include <cstddef>
- #include <cstdint>
- #include <cstring>
- #include <string>
- using namespace llvm;
- using ProfileCount = Function::ProfileCount;
- // Explicit instantiations of SymbolTableListTraits since some of the methods
- // are not in the public header file...
- template class llvm::SymbolTableListTraits<BasicBlock>;
- //===----------------------------------------------------------------------===//
- // Argument Implementation
- //===----------------------------------------------------------------------===//
- Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
- : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
- setName(Name);
- }
- void Argument::setParent(Function *parent) {
- Parent = parent;
- }
- bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {
- if (!getType()->isPointerTy()) return false;
- if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) &&
- (AllowUndefOrPoison ||
- getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef)))
- return true;
- else if (getDereferenceableBytes() > 0 &&
- !NullPointerIsDefined(getParent(),
- getType()->getPointerAddressSpace()))
- return true;
- return false;
- }
- bool Argument::hasByValAttr() const {
- if (!getType()->isPointerTy()) return false;
- return hasAttribute(Attribute::ByVal);
- }
- bool Argument::hasByRefAttr() const {
- if (!getType()->isPointerTy())
- return false;
- return hasAttribute(Attribute::ByRef);
- }
- bool Argument::hasSwiftSelfAttr() const {
- return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
- }
- bool Argument::hasSwiftErrorAttr() const {
- return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
- }
- bool Argument::hasInAllocaAttr() const {
- if (!getType()->isPointerTy()) return false;
- return hasAttribute(Attribute::InAlloca);
- }
- bool Argument::hasPreallocatedAttr() const {
- if (!getType()->isPointerTy())
- return false;
- return hasAttribute(Attribute::Preallocated);
- }
- bool Argument::hasPassPointeeByValueCopyAttr() const {
- if (!getType()->isPointerTy()) return false;
- AttributeList Attrs = getParent()->getAttributes();
- return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
- Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) ||
- Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated);
- }
- bool Argument::hasPointeeInMemoryValueAttr() const {
- if (!getType()->isPointerTy())
- return false;
- AttributeList Attrs = getParent()->getAttributes();
- return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
- Attrs.hasParamAttribute(getArgNo(), Attribute::StructRet) ||
- Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca) ||
- Attrs.hasParamAttribute(getArgNo(), Attribute::Preallocated) ||
- Attrs.hasParamAttribute(getArgNo(), Attribute::ByRef);
- }
- /// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
- /// parameter type.
- static Type *getMemoryParamAllocType(AttributeSet ParamAttrs, Type *ArgTy) {
- // FIXME: All the type carrying attributes are mutually exclusive, so there
- // should be a single query to get the stored type that handles any of them.
- if (Type *ByValTy = ParamAttrs.getByValType())
- return ByValTy;
- if (Type *ByRefTy = ParamAttrs.getByRefType())
- return ByRefTy;
- if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
- return PreAllocTy;
- // FIXME: sret and inalloca always depends on pointee element type. It's also
- // possible for byval to miss it.
- if (ParamAttrs.hasAttribute(Attribute::InAlloca) ||
- ParamAttrs.hasAttribute(Attribute::ByVal) ||
- ParamAttrs.hasAttribute(Attribute::StructRet) ||
- ParamAttrs.hasAttribute(Attribute::Preallocated))
- return cast<PointerType>(ArgTy)->getElementType();
- return nullptr;
- }
- uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const {
- AttributeSet ParamAttrs =
- getParent()->getAttributes().getParamAttributes(getArgNo());
- if (Type *MemTy = getMemoryParamAllocType(ParamAttrs, getType()))
- return DL.getTypeAllocSize(MemTy);
- return 0;
- }
- Type *Argument::getPointeeInMemoryValueType() const {
- AttributeSet ParamAttrs =
- getParent()->getAttributes().getParamAttributes(getArgNo());
- return getMemoryParamAllocType(ParamAttrs, getType());
- }
- unsigned Argument::getParamAlignment() const {
- assert(getType()->isPointerTy() && "Only pointers have alignments");
- return getParent()->getParamAlignment(getArgNo());
- }
- MaybeAlign Argument::getParamAlign() const {
- assert(getType()->isPointerTy() && "Only pointers have alignments");
- return getParent()->getParamAlign(getArgNo());
- }
- Type *Argument::getParamByValType() const {
- assert(getType()->isPointerTy() && "Only pointers have byval types");
- return getParent()->getParamByValType(getArgNo());
- }
- Type *Argument::getParamStructRetType() const {
- assert(getType()->isPointerTy() && "Only pointers have sret types");
- return getParent()->getParamStructRetType(getArgNo());
- }
- Type *Argument::getParamByRefType() const {
- assert(getType()->isPointerTy() && "Only pointers have byval types");
- return getParent()->getParamByRefType(getArgNo());
- }
- uint64_t Argument::getDereferenceableBytes() const {
- assert(getType()->isPointerTy() &&
- "Only pointers have dereferenceable bytes");
- return getParent()->getParamDereferenceableBytes(getArgNo());
- }
- uint64_t Argument::getDereferenceableOrNullBytes() const {
- assert(getType()->isPointerTy() &&
- "Only pointers have dereferenceable bytes");
- return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
- }
- bool Argument::hasNestAttr() const {
- if (!getType()->isPointerTy()) return false;
- return hasAttribute(Attribute::Nest);
- }
- bool Argument::hasNoAliasAttr() const {
- if (!getType()->isPointerTy()) return false;
- return hasAttribute(Attribute::NoAlias);
- }
- bool Argument::hasNoCaptureAttr() const {
- if (!getType()->isPointerTy()) return false;
- return hasAttribute(Attribute::NoCapture);
- }
- bool Argument::hasStructRetAttr() const {
- if (!getType()->isPointerTy()) return false;
- return hasAttribute(Attribute::StructRet);
- }
- bool Argument::hasInRegAttr() const {
- return hasAttribute(Attribute::InReg);
- }
- bool Argument::hasReturnedAttr() const {
- return hasAttribute(Attribute::Returned);
- }
- bool Argument::hasZExtAttr() const {
- return hasAttribute(Attribute::ZExt);
- }
- bool Argument::hasSExtAttr() const {
- return hasAttribute(Attribute::SExt);
- }
- bool Argument::onlyReadsMemory() const {
- AttributeList Attrs = getParent()->getAttributes();
- return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
- Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
- }
- void Argument::addAttrs(AttrBuilder &B) {
- AttributeList AL = getParent()->getAttributes();
- AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
- getParent()->setAttributes(AL);
- }
- void Argument::addAttr(Attribute::AttrKind Kind) {
- getParent()->addParamAttr(getArgNo(), Kind);
- }
- void Argument::addAttr(Attribute Attr) {
- getParent()->addParamAttr(getArgNo(), Attr);
- }
- void Argument::removeAttr(Attribute::AttrKind Kind) {
- getParent()->removeParamAttr(getArgNo(), Kind);
- }
- bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
- return getParent()->hasParamAttribute(getArgNo(), Kind);
- }
- Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
- return getParent()->getParamAttribute(getArgNo(), Kind);
- }
- //===----------------------------------------------------------------------===//
- // Helper Methods in Function
- //===----------------------------------------------------------------------===//
- LLVMContext &Function::getContext() const {
- return getType()->getContext();
- }
- unsigned Function::getInstructionCount() const {
- unsigned NumInstrs = 0;
- for (const BasicBlock &BB : BasicBlocks)
- NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
- BB.instructionsWithoutDebug().end());
- return NumInstrs;
- }
- Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
- const Twine &N, Module &M) {
- return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
- }
- void Function::removeFromParent() {
- getParent()->getFunctionList().remove(getIterator());
- }
- void Function::eraseFromParent() {
- getParent()->getFunctionList().erase(getIterator());
- }
- //===----------------------------------------------------------------------===//
- // Function Implementation
- //===----------------------------------------------------------------------===//
- static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
- // If AS == -1 and we are passed a valid module pointer we place the function
- // in the program address space. Otherwise we default to AS0.
- if (AddrSpace == static_cast<unsigned>(-1))
- return M ? M->getDataLayout().getProgramAddressSpace() : 0;
- return AddrSpace;
- }
- Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
- const Twine &name, Module *ParentModule)
- : GlobalObject(Ty, Value::FunctionVal,
- OperandTraits<Function>::op_begin(this), 0, Linkage, name,
- computeAddrSpace(AddrSpace, ParentModule)),
- NumArgs(Ty->getNumParams()) {
- assert(FunctionType::isValidReturnType(getReturnType()) &&
- "invalid return type");
- setGlobalObjectSubClassData(0);
- // We only need a symbol table for a function if the context keeps value names
- if (!getContext().shouldDiscardValueNames())
- SymTab = std::make_unique<ValueSymbolTable>();
- // If the function has arguments, mark them as lazily built.
- if (Ty->getNumParams())
- setValueSubclassData(1); // Set the "has lazy arguments" bit.
- if (ParentModule)
- ParentModule->getFunctionList().push_back(this);
- HasLLVMReservedName = getName().startswith("llvm.");
- // Ensure intrinsics have the right parameter attributes.
- // Note, the IntID field will have been set in Value::setName if this function
- // name is a valid intrinsic ID.
- if (IntID)
- setAttributes(Intrinsic::getAttributes(getContext(), IntID));
- }
- Function::~Function() {
- dropAllReferences(); // After this it is safe to delete instructions.
- // Delete all of the method arguments and unlink from symbol table...
- if (Arguments)
- clearArguments();
- // Remove the function from the on-the-side GC table.
- clearGC();
- }
- void Function::BuildLazyArguments() const {
- // Create the arguments vector, all arguments start out unnamed.
- auto *FT = getFunctionType();
- if (NumArgs > 0) {
- Arguments = std::allocator<Argument>().allocate(NumArgs);
- for (unsigned i = 0, e = NumArgs; i != e; ++i) {
- Type *ArgTy = FT->getParamType(i);
- assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
- new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
- }
- }
- // Clear the lazy arguments bit.
- unsigned SDC = getSubclassDataFromValue();
- SDC &= ~(1 << 0);
- const_cast<Function*>(this)->setValueSubclassData(SDC);
- assert(!hasLazyArguments());
- }
- static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
- return MutableArrayRef<Argument>(Args, Count);
- }
- bool Function::isConstrainedFPIntrinsic() const {
- switch (getIntrinsicID()) {
- #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
- case Intrinsic::INTRINSIC:
- #include "llvm/IR/ConstrainedOps.def"
- return true;
- #undef INSTRUCTION
- default:
- return false;
- }
- }
- void Function::clearArguments() {
- for (Argument &A : makeArgArray(Arguments, NumArgs)) {
- A.setName("");
- A.~Argument();
- }
- std::allocator<Argument>().deallocate(Arguments, NumArgs);
- Arguments = nullptr;
- }
- void Function::stealArgumentListFrom(Function &Src) {
- assert(isDeclaration() && "Expected no references to current arguments");
- // Drop the current arguments, if any, and set the lazy argument bit.
- if (!hasLazyArguments()) {
- assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
- [](const Argument &A) { return A.use_empty(); }) &&
- "Expected arguments to be unused in declaration");
- clearArguments();
- setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
- }
- // Nothing to steal if Src has lazy arguments.
- if (Src.hasLazyArguments())
- return;
- // Steal arguments from Src, and fix the lazy argument bits.
- assert(arg_size() == Src.arg_size());
- Arguments = Src.Arguments;
- Src.Arguments = nullptr;
- for (Argument &A : makeArgArray(Arguments, NumArgs)) {
- // FIXME: This does the work of transferNodesFromList inefficiently.
- SmallString<128> Name;
- if (A.hasName())
- Name = A.getName();
- if (!Name.empty())
- A.setName("");
- A.setParent(this);
- if (!Name.empty())
- A.setName(Name);
- }
- setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
- assert(!hasLazyArguments());
- Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
- }
- // dropAllReferences() - This function causes all the subinstructions to "let
- // go" of all references that they are maintaining. This allows one to
- // 'delete' a whole class at a time, even though there may be circular
- // references... first all references are dropped, and all use counts go to
- // zero. Then everything is deleted for real. Note that no operations are
- // valid on an object that has "dropped all references", except operator
- // delete.
- //
- void Function::dropAllReferences() {
- setIsMaterializable(false);
- for (BasicBlock &BB : *this)
- BB.dropAllReferences();
- // Delete all basic blocks. They are now unused, except possibly by
- // blockaddresses, but BasicBlock's destructor takes care of those.
- while (!BasicBlocks.empty())
- BasicBlocks.begin()->eraseFromParent();
- // Drop uses of any optional data (real or placeholder).
- if (getNumOperands()) {
- User::dropAllReferences();
- setNumHungOffUseOperands(0);
- setValueSubclassData(getSubclassDataFromValue() & ~0xe);
- }
- // Metadata is stored in a side-table.
- clearMetadata();
- }
- void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
- AttributeList PAL = getAttributes();
- PAL = PAL.addAttribute(getContext(), i, Kind);
- setAttributes(PAL);
- }
- void Function::addAttribute(unsigned i, Attribute Attr) {
- AttributeList PAL = getAttributes();
- PAL = PAL.addAttribute(getContext(), i, Attr);
- setAttributes(PAL);
- }
- void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
- AttributeList PAL = getAttributes();
- PAL = PAL.addAttributes(getContext(), i, Attrs);
- setAttributes(PAL);
- }
- void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
- AttributeList PAL = getAttributes();
- PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
- setAttributes(PAL);
- }
- void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
- AttributeList PAL = getAttributes();
- PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
- setAttributes(PAL);
- }
- void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
- AttributeList PAL = getAttributes();
- PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs);
- setAttributes(PAL);
- }
- void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
- AttributeList PAL = getAttributes();
- PAL = PAL.removeAttribute(getContext(), i, Kind);
- setAttributes(PAL);
- }
- void Function::removeAttribute(unsigned i, StringRef Kind) {
- AttributeList PAL = getAttributes();
- PAL = PAL.removeAttribute(getContext(), i, Kind);
- setAttributes(PAL);
- }
- void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
- AttributeList PAL = getAttributes();
- PAL = PAL.removeAttributes(getContext(), i, Attrs);
- setAttributes(PAL);
- }
- void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
- AttributeList PAL = getAttributes();
- PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
- setAttributes(PAL);
- }
- void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
- AttributeList PAL = getAttributes();
- PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
- setAttributes(PAL);
- }
- void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
- AttributeList PAL = getAttributes();
- PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs);
- setAttributes(PAL);
- }
- void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
- AttributeList PAL = getAttributes();
- PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
- setAttributes(PAL);
- }
- void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
- AttributeList PAL = getAttributes();
- PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
- setAttributes(PAL);
- }
- void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
- AttributeList PAL = getAttributes();
- PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
- setAttributes(PAL);
- }
- void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
- uint64_t Bytes) {
- AttributeList PAL = getAttributes();
- PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes);
- setAttributes(PAL);
- }
- DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const {
- if (&FPType == &APFloat::IEEEsingle()) {
- Attribute Attr = getFnAttribute("denormal-fp-math-f32");
- StringRef Val = Attr.getValueAsString();
- if (!Val.empty())
- return parseDenormalFPAttribute(Val);
- // If the f32 variant of the attribute isn't specified, try to use the
- // generic one.
- }
- Attribute Attr = getFnAttribute("denormal-fp-math");
- return parseDenormalFPAttribute(Attr.getValueAsString());
- }
- const std::string &Function::getGC() const {
- assert(hasGC() && "Function has no collector");
- return getContext().getGC(*this);
- }
- void Function::setGC(std::string Str) {
- setValueSubclassDataBit(14, !Str.empty());
- getContext().setGC(*this, std::move(Str));
- }
- void Function::clearGC() {
- if (!hasGC())
- return;
- getContext().deleteGC(*this);
- setValueSubclassDataBit(14, false);
- }
- bool Function::hasStackProtectorFnAttr() const {
- return hasFnAttribute(Attribute::StackProtect) ||
- hasFnAttribute(Attribute::StackProtectStrong) ||
- hasFnAttribute(Attribute::StackProtectReq);
- }
- /// Copy all additional attributes (those not needed to create a Function) from
- /// the Function Src to this one.
- void Function::copyAttributesFrom(const Function *Src) {
- GlobalObject::copyAttributesFrom(Src);
- setCallingConv(Src->getCallingConv());
- setAttributes(Src->getAttributes());
- if (Src->hasGC())
- setGC(Src->getGC());
- else
- clearGC();
- if (Src->hasPersonalityFn())
- setPersonalityFn(Src->getPersonalityFn());
- if (Src->hasPrefixData())
- setPrefixData(Src->getPrefixData());
- if (Src->hasPrologueData())
- setPrologueData(Src->getPrologueData());
- }
- /// Table of string intrinsic names indexed by enum value.
- static const char * const IntrinsicNameTable[] = {
- "not_intrinsic",
- #define GET_INTRINSIC_NAME_TABLE
- #include "llvm/IR/IntrinsicImpl.inc"
- #undef GET_INTRINSIC_NAME_TABLE
- };
- /// Table of per-target intrinsic name tables.
- #define GET_INTRINSIC_TARGET_DATA
- #include "llvm/IR/IntrinsicImpl.inc"
- #undef GET_INTRINSIC_TARGET_DATA
- bool Function::isTargetIntrinsic(Intrinsic::ID IID) {
- return IID > TargetInfos[0].Count;
- }
- bool Function::isTargetIntrinsic() const {
- return isTargetIntrinsic(IntID);
- }
- /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
- /// target as \c Name, or the generic table if \c Name is not target specific.
- ///
- /// Returns the relevant slice of \c IntrinsicNameTable
- static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
- assert(Name.startswith("llvm."));
- ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
- // Drop "llvm." and take the first dotted component. That will be the target
- // if this is target specific.
- StringRef Target = Name.drop_front(5).split('.').first;
- auto It = partition_point(
- Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
- // We've either found the target or just fall back to the generic set, which
- // is always first.
- const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
- return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
- }
- /// This does the actual lookup of an intrinsic ID which
- /// matches the given function name.
- Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
- ArrayRef<const char *> NameTable = findTargetSubtable(Name);
- int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
- if (Idx == -1)
- return Intrinsic::not_intrinsic;
- // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
- // an index into a sub-table.
- int Adjust = NameTable.data() - IntrinsicNameTable;
- Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
- // If the intrinsic is not overloaded, require an exact match. If it is
- // overloaded, require either exact or prefix match.
- const auto MatchSize = strlen(NameTable[Idx]);
- assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
- bool IsExactMatch = Name.size() == MatchSize;
- return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
- : Intrinsic::not_intrinsic;
- }
- void Function::recalculateIntrinsicID() {
- StringRef Name = getName();
- if (!Name.startswith("llvm.")) {
- HasLLVMReservedName = false;
- IntID = Intrinsic::not_intrinsic;
- return;
- }
- HasLLVMReservedName = true;
- IntID = lookupIntrinsicID(Name);
- }
- /// Returns a stable mangling for the type specified for use in the name
- /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
- /// of named types is simply their name. Manglings for unnamed types consist
- /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
- /// combined with the mangling of their component types. A vararg function
- /// type will have a suffix of 'vararg'. Since function types can contain
- /// other function types, we close a function type mangling with suffix 'f'
- /// which can't be confused with it's prefix. This ensures we don't have
- /// collisions between two unrelated function types. Otherwise, you might
- /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
- ///
- static std::string getMangledTypeStr(Type* Ty) {
- std::string Result;
- if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
- Result += "p" + utostr(PTyp->getAddressSpace()) +
- getMangledTypeStr(PTyp->getElementType());
- } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
- Result += "a" + utostr(ATyp->getNumElements()) +
- getMangledTypeStr(ATyp->getElementType());
- } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
- if (!STyp->isLiteral()) {
- Result += "s_";
- Result += STyp->getName();
- } else {
- Result += "sl_";
- for (auto Elem : STyp->elements())
- Result += getMangledTypeStr(Elem);
- }
- // Ensure nested structs are distinguishable.
- Result += "s";
- } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
- Result += "f_" + getMangledTypeStr(FT->getReturnType());
- for (size_t i = 0; i < FT->getNumParams(); i++)
- Result += getMangledTypeStr(FT->getParamType(i));
- if (FT->isVarArg())
- Result += "vararg";
- // Ensure nested function types are distinguishable.
- Result += "f";
- } else if (VectorType* VTy = dyn_cast<VectorType>(Ty)) {
- ElementCount EC = VTy->getElementCount();
- if (EC.isScalable())
- Result += "nx";
- Result += "v" + utostr(EC.getKnownMinValue()) +
- getMangledTypeStr(VTy->getElementType());
- } else if (Ty) {
- switch (Ty->getTypeID()) {
- default: llvm_unreachable("Unhandled type");
- case Type::VoidTyID: Result += "isVoid"; break;
- case Type::MetadataTyID: Result += "Metadata"; break;
- case Type::HalfTyID: Result += "f16"; break;
- case Type::BFloatTyID: Result += "bf16"; break;
- case Type::FloatTyID: Result += "f32"; break;
- case Type::DoubleTyID: Result += "f64"; break;
- case Type::X86_FP80TyID: Result += "f80"; break;
- case Type::FP128TyID: Result += "f128"; break;
- case Type::PPC_FP128TyID: Result += "ppcf128"; break;
- case Type::X86_MMXTyID: Result += "x86mmx"; break;
- case Type::X86_AMXTyID: Result += "x86amx"; break;
- case Type::IntegerTyID:
- Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
- break;
- }
- }
- return Result;
- }
- StringRef Intrinsic::getName(ID id) {
- assert(id < num_intrinsics && "Invalid intrinsic ID!");
- assert(!Intrinsic::isOverloaded(id) &&
- "This version of getName does not support overloading");
- return IntrinsicNameTable[id];
- }
- std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
- assert(id < num_intrinsics && "Invalid intrinsic ID!");
- assert((Tys.empty() || Intrinsic::isOverloaded(id)) &&
- "This version of getName is for overloaded intrinsics only");
- std::string Result(IntrinsicNameTable[id]);
- for (Type *Ty : Tys) {
- Result += "." + getMangledTypeStr(Ty);
- }
- return Result;
- }
- /// IIT_Info - These are enumerators that describe the entries returned by the
- /// getIntrinsicInfoTableEntries function.
- ///
- /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
- enum IIT_Info {
- // Common values should be encoded with 0-15.
- IIT_Done = 0,
- IIT_I1 = 1,
- IIT_I8 = 2,
- IIT_I16 = 3,
- IIT_I32 = 4,
- IIT_I64 = 5,
- IIT_F16 = 6,
- IIT_F32 = 7,
- IIT_F64 = 8,
- IIT_V2 = 9,
- IIT_V4 = 10,
- IIT_V8 = 11,
- IIT_V16 = 12,
- IIT_V32 = 13,
- IIT_PTR = 14,
- IIT_ARG = 15,
- // Values from 16+ are only encodable with the inefficient encoding.
- IIT_V64 = 16,
- IIT_MMX = 17,
- IIT_TOKEN = 18,
- IIT_METADATA = 19,
- IIT_EMPTYSTRUCT = 20,
- IIT_STRUCT2 = 21,
- IIT_STRUCT3 = 22,
- IIT_STRUCT4 = 23,
- IIT_STRUCT5 = 24,
- IIT_EXTEND_ARG = 25,
- IIT_TRUNC_ARG = 26,
- IIT_ANYPTR = 27,
- IIT_V1 = 28,
- IIT_VARARG = 29,
- IIT_HALF_VEC_ARG = 30,
- IIT_SAME_VEC_WIDTH_ARG = 31,
- IIT_PTR_TO_ARG = 32,
- IIT_PTR_TO_ELT = 33,
- IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
- IIT_I128 = 35,
- IIT_V512 = 36,
- IIT_V1024 = 37,
- IIT_STRUCT6 = 38,
- IIT_STRUCT7 = 39,
- IIT_STRUCT8 = 40,
- IIT_F128 = 41,
- IIT_VEC_ELEMENT = 42,
- IIT_SCALABLE_VEC = 43,
- IIT_SUBDIVIDE2_ARG = 44,
- IIT_SUBDIVIDE4_ARG = 45,
- IIT_VEC_OF_BITCASTS_TO_INT = 46,
- IIT_V128 = 47,
- IIT_BF16 = 48,
- IIT_STRUCT9 = 49,
- IIT_V256 = 50,
- IIT_AMX = 51
- };
- static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
- IIT_Info LastInfo,
- SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
- using namespace Intrinsic;
- bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
- IIT_Info Info = IIT_Info(Infos[NextElt++]);
- unsigned StructElts = 2;
- switch (Info) {
- case IIT_Done:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
- return;
- case IIT_VARARG:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
- return;
- case IIT_MMX:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
- return;
- case IIT_AMX:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0));
- return;
- case IIT_TOKEN:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
- return;
- case IIT_METADATA:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
- return;
- case IIT_F16:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
- return;
- case IIT_BF16:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
- return;
- case IIT_F32:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
- return;
- case IIT_F64:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
- return;
- case IIT_F128:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
- return;
- case IIT_I1:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
- return;
- case IIT_I8:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
- return;
- case IIT_I16:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
- return;
- case IIT_I32:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
- return;
- case IIT_I64:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
- return;
- case IIT_I128:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
- return;
- case IIT_V1:
- OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_V2:
- OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_V4:
- OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_V8:
- OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_V16:
- OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_V32:
- OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_V64:
- OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_V128:
- OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_V256:
- OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_V512:
- OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_V1024:
- OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_PTR:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
- Infos[NextElt++]));
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- }
- case IIT_ARG: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
- return;
- }
- case IIT_EXTEND_ARG: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
- ArgInfo));
- return;
- }
- case IIT_TRUNC_ARG: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
- ArgInfo));
- return;
- }
- case IIT_HALF_VEC_ARG: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
- ArgInfo));
- return;
- }
- case IIT_SAME_VEC_WIDTH_ARG: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
- ArgInfo));
- return;
- }
- case IIT_PTR_TO_ARG: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
- ArgInfo));
- return;
- }
- case IIT_PTR_TO_ELT: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
- return;
- }
- case IIT_VEC_OF_ANYPTRS_TO_ELT: {
- unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(
- IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
- return;
- }
- case IIT_EMPTYSTRUCT:
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
- return;
- case IIT_STRUCT9: ++StructElts; LLVM_FALLTHROUGH;
- case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
- case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
- case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
- case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
- case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
- case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
- case IIT_STRUCT2: {
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
- for (unsigned i = 0; i != StructElts; ++i)
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- }
- case IIT_SUBDIVIDE2_ARG: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,
- ArgInfo));
- return;
- }
- case IIT_SUBDIVIDE4_ARG: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,
- ArgInfo));
- return;
- }
- case IIT_VEC_ELEMENT: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
- ArgInfo));
- return;
- }
- case IIT_SCALABLE_VEC: {
- DecodeIITType(NextElt, Infos, Info, OutputTable);
- return;
- }
- case IIT_VEC_OF_BITCASTS_TO_INT: {
- unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
- OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
- ArgInfo));
- return;
- }
- }
- llvm_unreachable("unhandled");
- }
- #define GET_INTRINSIC_GENERATOR_GLOBAL
- #include "llvm/IR/IntrinsicImpl.inc"
- #undef GET_INTRINSIC_GENERATOR_GLOBAL
- void Intrinsic::getIntrinsicInfoTableEntries(ID id,
- SmallVectorImpl<IITDescriptor> &T){
- // Check to see if the intrinsic's type was expressible by the table.
- unsigned TableVal = IIT_Table[id-1];
- // Decode the TableVal into an array of IITValues.
- SmallVector<unsigned char, 8> IITValues;
- ArrayRef<unsigned char> IITEntries;
- unsigned NextElt = 0;
- if ((TableVal >> 31) != 0) {
- // This is an offset into the IIT_LongEncodingTable.
- IITEntries = IIT_LongEncodingTable;
- // Strip sentinel bit.
- NextElt = (TableVal << 1) >> 1;
- } else {
- // Decode the TableVal into an array of IITValues. If the entry was encoded
- // into a single word in the table itself, decode it now.
- do {
- IITValues.push_back(TableVal & 0xF);
- TableVal >>= 4;
- } while (TableVal);
- IITEntries = IITValues;
- NextElt = 0;
- }
- // Okay, decode the table into the output vector of IITDescriptors.
- DecodeIITType(NextElt, IITEntries, IIT_Done, T);
- while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
- DecodeIITType(NextElt, IITEntries, IIT_Done, T);
- }
- static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
- ArrayRef<Type*> Tys, LLVMContext &Context) {
- using namespace Intrinsic;
- IITDescriptor D = Infos.front();
- Infos = Infos.slice(1);
- switch (D.Kind) {
- case IITDescriptor::Void: return Type::getVoidTy(Context);
- case IITDescriptor::VarArg: return Type::getVoidTy(Context);
- case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
- case IITDescriptor::AMX: return Type::getX86_AMXTy(Context);
- case IITDescriptor::Token: return Type::getTokenTy(Context);
- case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
- case IITDescriptor::Half: return Type::getHalfTy(Context);
- case IITDescriptor::BFloat: return Type::getBFloatTy(Context);
- case IITDescriptor::Float: return Type::getFloatTy(Context);
- case IITDescriptor::Double: return Type::getDoubleTy(Context);
- case IITDescriptor::Quad: return Type::getFP128Ty(Context);
- case IITDescriptor::Integer:
- return IntegerType::get(Context, D.Integer_Width);
- case IITDescriptor::Vector:
- return VectorType::get(DecodeFixedType(Infos, Tys, Context),
- D.Vector_Width);
- case IITDescriptor::Pointer:
- return PointerType::get(DecodeFixedType(Infos, Tys, Context),
- D.Pointer_AddressSpace);
- case IITDescriptor::Struct: {
- SmallVector<Type *, 8> Elts;
- for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
- Elts.push_back(DecodeFixedType(Infos, Tys, Context));
- return StructType::get(Context, Elts);
- }
- case IITDescriptor::Argument:
- return Tys[D.getArgumentNumber()];
- case IITDescriptor::ExtendArgument: {
- Type *Ty = Tys[D.getArgumentNumber()];
- if (VectorType *VTy = dyn_cast<VectorType>(Ty))
- return VectorType::getExtendedElementVectorType(VTy);
- return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
- }
- case IITDescriptor::TruncArgument: {
- Type *Ty = Tys[D.getArgumentNumber()];
- if (VectorType *VTy = dyn_cast<VectorType>(Ty))
- return VectorType::getTruncatedElementVectorType(VTy);
- IntegerType *ITy = cast<IntegerType>(Ty);
- assert(ITy->getBitWidth() % 2 == 0);
- return IntegerType::get(Context, ITy->getBitWidth() / 2);
- }
- case IITDescriptor::Subdivide2Argument:
- case IITDescriptor::Subdivide4Argument: {
- Type *Ty = Tys[D.getArgumentNumber()];
- VectorType *VTy = dyn_cast<VectorType>(Ty);
- assert(VTy && "Expected an argument of Vector Type");
- int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
- return VectorType::getSubdividedVectorType(VTy, SubDivs);
- }
- case IITDescriptor::HalfVecArgument:
- return VectorType::getHalfElementsVectorType(cast<VectorType>(
- Tys[D.getArgumentNumber()]));
- case IITDescriptor::SameVecWidthArgument: {
- Type *EltTy = DecodeFixedType(Infos, Tys, Context);
- Type *Ty = Tys[D.getArgumentNumber()];
- if (auto *VTy = dyn_cast<VectorType>(Ty))
- return VectorType::get(EltTy, VTy->getElementCount());
- return EltTy;
- }
- case IITDescriptor::PtrToArgument: {
- Type *Ty = Tys[D.getArgumentNumber()];
- return PointerType::getUnqual(Ty);
- }
- case IITDescriptor::PtrToElt: {
- Type *Ty = Tys[D.getArgumentNumber()];
- VectorType *VTy = dyn_cast<VectorType>(Ty);
- if (!VTy)
- llvm_unreachable("Expected an argument of Vector Type");
- Type *EltTy = VTy->getElementType();
- return PointerType::getUnqual(EltTy);
- }
- case IITDescriptor::VecElementArgument: {
- Type *Ty = Tys[D.getArgumentNumber()];
- if (VectorType *VTy = dyn_cast<VectorType>(Ty))
- return VTy->getElementType();
- llvm_unreachable("Expected an argument of Vector Type");
- }
- case IITDescriptor::VecOfBitcastsToInt: {
- Type *Ty = Tys[D.getArgumentNumber()];
- VectorType *VTy = dyn_cast<VectorType>(Ty);
- assert(VTy && "Expected an argument of Vector Type");
- return VectorType::getInteger(VTy);
- }
- case IITDescriptor::VecOfAnyPtrsToElt:
- // Return the overloaded type (which determines the pointers address space)
- return Tys[D.getOverloadArgNumber()];
- }
- llvm_unreachable("unhandled");
- }
- FunctionType *Intrinsic::getType(LLVMContext &Context,
- ID id, ArrayRef<Type*> Tys) {
- SmallVector<IITDescriptor, 8> Table;
- getIntrinsicInfoTableEntries(id, Table);
- ArrayRef<IITDescriptor> TableRef = Table;
- Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
- SmallVector<Type*, 8> ArgTys;
- while (!TableRef.empty())
- ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
- // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
- // If we see void type as the type of the last argument, it is vararg intrinsic
- if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
- ArgTys.pop_back();
- return FunctionType::get(ResultTy, ArgTys, true);
- }
- return FunctionType::get(ResultTy, ArgTys, false);
- }
- bool Intrinsic::isOverloaded(ID id) {
- #define GET_INTRINSIC_OVERLOAD_TABLE
- #include "llvm/IR/IntrinsicImpl.inc"
- #undef GET_INTRINSIC_OVERLOAD_TABLE
- }
- bool Intrinsic::isLeaf(ID id) {
- switch (id) {
- default:
- return true;
- case Intrinsic::experimental_gc_statepoint:
- case Intrinsic::experimental_patchpoint_void:
- case Intrinsic::experimental_patchpoint_i64:
- return false;
- }
- }
- /// This defines the "Intrinsic::getAttributes(ID id)" method.
- #define GET_INTRINSIC_ATTRIBUTES
- #include "llvm/IR/IntrinsicImpl.inc"
- #undef GET_INTRINSIC_ATTRIBUTES
- Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
- // There can never be multiple globals with the same name of different types,
- // because intrinsics must be a specific type.
- return cast<Function>(
- M->getOrInsertFunction(Tys.empty() ? getName(id) : getName(id, Tys),
- getType(M->getContext(), id, Tys))
- .getCallee());
- }
- // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
- #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
- #include "llvm/IR/IntrinsicImpl.inc"
- #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
- // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
- #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
- #include "llvm/IR/IntrinsicImpl.inc"
- #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
- using DeferredIntrinsicMatchPair =
- std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
- static bool matchIntrinsicType(
- Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
- SmallVectorImpl<Type *> &ArgTys,
- SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
- bool IsDeferredCheck) {
- using namespace Intrinsic;
- // If we ran out of descriptors, there are too many arguments.
- if (Infos.empty()) return true;
- // Do this before slicing off the 'front' part
- auto InfosRef = Infos;
- auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
- DeferredChecks.emplace_back(T, InfosRef);
- return false;
- };
- IITDescriptor D = Infos.front();
- Infos = Infos.slice(1);
- switch (D.Kind) {
- case IITDescriptor::Void: return !Ty->isVoidTy();
- case IITDescriptor::VarArg: return true;
- case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
- case IITDescriptor::AMX: return !Ty->isX86_AMXTy();
- case IITDescriptor::Token: return !Ty->isTokenTy();
- case IITDescriptor::Metadata: return !Ty->isMetadataTy();
- case IITDescriptor::Half: return !Ty->isHalfTy();
- case IITDescriptor::BFloat: return !Ty->isBFloatTy();
- case IITDescriptor::Float: return !Ty->isFloatTy();
- case IITDescriptor::Double: return !Ty->isDoubleTy();
- case IITDescriptor::Quad: return !Ty->isFP128Ty();
- case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
- case IITDescriptor::Vector: {
- VectorType *VT = dyn_cast<VectorType>(Ty);
- return !VT || VT->getElementCount() != D.Vector_Width ||
- matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
- DeferredChecks, IsDeferredCheck);
- }
- case IITDescriptor::Pointer: {
- PointerType *PT = dyn_cast<PointerType>(Ty);
- return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
- matchIntrinsicType(PT->getElementType(), Infos, ArgTys,
- DeferredChecks, IsDeferredCheck);
- }
- case IITDescriptor::Struct: {
- StructType *ST = dyn_cast<StructType>(Ty);
- if (!ST || ST->getNumElements() != D.Struct_NumElements)
- return true;
- for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
- if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
- DeferredChecks, IsDeferredCheck))
- return true;
- return false;
- }
- case IITDescriptor::Argument:
- // If this is the second occurrence of an argument,
- // verify that the later instance matches the previous instance.
- if (D.getArgumentNumber() < ArgTys.size())
- return Ty != ArgTys[D.getArgumentNumber()];
- if (D.getArgumentNumber() > ArgTys.size() ||
- D.getArgumentKind() == IITDescriptor::AK_MatchType)
- return IsDeferredCheck || DeferCheck(Ty);
- assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
- "Table consistency error");
- ArgTys.push_back(Ty);
- switch (D.getArgumentKind()) {
- case IITDescriptor::AK_Any: return false; // Success
- case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
- case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
- case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
- case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
- default: break;
- }
- llvm_unreachable("all argument kinds not covered");
- case IITDescriptor::ExtendArgument: {
- // If this is a forward reference, defer the check for later.
- if (D.getArgumentNumber() >= ArgTys.size())
- return IsDeferredCheck || DeferCheck(Ty);
- Type *NewTy = ArgTys[D.getArgumentNumber()];
- if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
- NewTy = VectorType::getExtendedElementVectorType(VTy);
- else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
- NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
- else
- return true;
- return Ty != NewTy;
- }
- case IITDescriptor::TruncArgument: {
- // If this is a forward reference, defer the check for later.
- if (D.getArgumentNumber() >= ArgTys.size())
- return IsDeferredCheck || DeferCheck(Ty);
- Type *NewTy = ArgTys[D.getArgumentNumber()];
- if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
- NewTy = VectorType::getTruncatedElementVectorType(VTy);
- else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
- NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
- else
- return true;
- return Ty != NewTy;
- }
- case IITDescriptor::HalfVecArgument:
- // If this is a forward reference, defer the check for later.
- if (D.getArgumentNumber() >= ArgTys.size())
- return IsDeferredCheck || DeferCheck(Ty);
- return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
- VectorType::getHalfElementsVectorType(
- cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
- case IITDescriptor::SameVecWidthArgument: {
- if (D.getArgumentNumber() >= ArgTys.size()) {
- // Defer check and subsequent check for the vector element type.
- Infos = Infos.slice(1);
- return IsDeferredCheck || DeferCheck(Ty);
- }
- auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
- auto *ThisArgType = dyn_cast<VectorType>(Ty);
- // Both must be vectors of the same number of elements or neither.
- if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
- return true;
- Type *EltTy = Ty;
- if (ThisArgType) {
- if (ReferenceType->getElementCount() !=
- ThisArgType->getElementCount())
- return true;
- EltTy = ThisArgType->getElementType();
- }
- return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
- IsDeferredCheck);
- }
- case IITDescriptor::PtrToArgument: {
- if (D.getArgumentNumber() >= ArgTys.size())
- return IsDeferredCheck || DeferCheck(Ty);
- Type * ReferenceType = ArgTys[D.getArgumentNumber()];
- PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
- return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
- }
- case IITDescriptor::PtrToElt: {
- if (D.getArgumentNumber() >= ArgTys.size())
- return IsDeferredCheck || DeferCheck(Ty);
- VectorType * ReferenceType =
- dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
- PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
- return (!ThisArgType || !ReferenceType ||
- ThisArgType->getElementType() != ReferenceType->getElementType());
- }
- case IITDescriptor::VecOfAnyPtrsToElt: {
- unsigned RefArgNumber = D.getRefArgNumber();
- if (RefArgNumber >= ArgTys.size()) {
- if (IsDeferredCheck)
- return true;
- // If forward referencing, already add the pointer-vector type and
- // defer the checks for later.
- ArgTys.push_back(Ty);
- return DeferCheck(Ty);
- }
- if (!IsDeferredCheck){
- assert(D.getOverloadArgNumber() == ArgTys.size() &&
- "Table consistency error");
- ArgTys.push_back(Ty);
- }
- // Verify the overloaded type "matches" the Ref type.
- // i.e. Ty is a vector with the same width as Ref.
- // Composed of pointers to the same element type as Ref.
- auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
- auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
- if (!ThisArgVecTy || !ReferenceType ||
- (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))
- return true;
- PointerType *ThisArgEltTy =
- dyn_cast<PointerType>(ThisArgVecTy->getElementType());
- if (!ThisArgEltTy)
- return true;
- return ThisArgEltTy->getElementType() != ReferenceType->getElementType();
- }
- case IITDescriptor::VecElementArgument: {
- if (D.getArgumentNumber() >= ArgTys.size())
- return IsDeferredCheck ? true : DeferCheck(Ty);
- auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
- return !ReferenceType || Ty != ReferenceType->getElementType();
- }
- case IITDescriptor::Subdivide2Argument:
- case IITDescriptor::Subdivide4Argument: {
- // If this is a forward reference, defer the check for later.
- if (D.getArgumentNumber() >= ArgTys.size())
- return IsDeferredCheck || DeferCheck(Ty);
- Type *NewTy = ArgTys[D.getArgumentNumber()];
- if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
- int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
- NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
- return Ty != NewTy;
- }
- return true;
- }
- case IITDescriptor::VecOfBitcastsToInt: {
- if (D.getArgumentNumber() >= ArgTys.size())
- return IsDeferredCheck || DeferCheck(Ty);
- auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
- auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
- if (!ThisArgVecTy || !ReferenceType)
- return true;
- return ThisArgVecTy != VectorType::getInteger(ReferenceType);
- }
- }
- llvm_unreachable("unhandled");
- }
- Intrinsic::MatchIntrinsicTypesResult
- Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
- ArrayRef<Intrinsic::IITDescriptor> &Infos,
- SmallVectorImpl<Type *> &ArgTys) {
- SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
- if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
- false))
- return MatchIntrinsicTypes_NoMatchRet;
- unsigned NumDeferredReturnChecks = DeferredChecks.size();
- for (auto Ty : FTy->params())
- if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
- return MatchIntrinsicTypes_NoMatchArg;
- for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
- DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
- if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
- true))
- return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
- : MatchIntrinsicTypes_NoMatchArg;
- }
- return MatchIntrinsicTypes_Match;
- }
- bool
- Intrinsic::matchIntrinsicVarArg(bool isVarArg,
- ArrayRef<Intrinsic::IITDescriptor> &Infos) {
- // If there are no descriptors left, then it can't be a vararg.
- if (Infos.empty())
- return isVarArg;
- // There should be only one descriptor remaining at this point.
- if (Infos.size() != 1)
- return true;
- // Check and verify the descriptor.
- IITDescriptor D = Infos.front();
- Infos = Infos.slice(1);
- if (D.Kind == IITDescriptor::VarArg)
- return !isVarArg;
- return true;
- }
- bool Intrinsic::getIntrinsicSignature(Function *F,
- SmallVectorImpl<Type *> &ArgTys) {
- Intrinsic::ID ID = F->getIntrinsicID();
- if (!ID)
- return false;
- SmallVector<Intrinsic::IITDescriptor, 8> Table;
- getIntrinsicInfoTableEntries(ID, Table);
- ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
- if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef,
- ArgTys) !=
- Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {
- return false;
- }
- if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(),
- TableRef))
- return false;
- return true;
- }
- Optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {
- SmallVector<Type *, 4> ArgTys;
- if (!getIntrinsicSignature(F, ArgTys))
- return None;
- Intrinsic::ID ID = F->getIntrinsicID();
- StringRef Name = F->getName();
- if (Name == Intrinsic::getName(ID, ArgTys))
- return None;
- auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
- NewDecl->setCallingConv(F->getCallingConv());
- assert(NewDecl->getFunctionType() == F->getFunctionType() &&
- "Shouldn't change the signature");
- return NewDecl;
- }
- /// hasAddressTaken - returns true if there are any uses of this function
- /// other than direct calls or invokes to it. Optionally ignores callback
- /// uses.
- bool Function::hasAddressTaken(const User **PutOffender,
- bool IgnoreCallbackUses) const {
- for (const Use &U : uses()) {
- const User *FU = U.getUser();
- if (isa<BlockAddress>(FU))
- continue;
- if (IgnoreCallbackUses) {
- AbstractCallSite ACS(&U);
- if (ACS && ACS.isCallbackCall())
- continue;
- }
- const auto *Call = dyn_cast<CallBase>(FU);
- if (!Call) {
- if (PutOffender)
- *PutOffender = FU;
- return true;
- }
- if (!Call->isCallee(&U)) {
- if (PutOffender)
- *PutOffender = FU;
- return true;
- }
- }
- return false;
- }
- bool Function::isDefTriviallyDead() const {
- // Check the linkage
- if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
- !hasAvailableExternallyLinkage())
- return false;
- // Check if the function is used by anything other than a blockaddress.
- for (const User *U : users())
- if (!isa<BlockAddress>(U))
- return false;
- return true;
- }
- /// callsFunctionThatReturnsTwice - Return true if the function has a call to
- /// setjmp or other function that gcc recognizes as "returning twice".
- bool Function::callsFunctionThatReturnsTwice() const {
- for (const Instruction &I : instructions(this))
- if (const auto *Call = dyn_cast<CallBase>(&I))
- if (Call->hasFnAttr(Attribute::ReturnsTwice))
- return true;
- return false;
- }
- Constant *Function::getPersonalityFn() const {
- assert(hasPersonalityFn() && getNumOperands());
- return cast<Constant>(Op<0>());
- }
- void Function::setPersonalityFn(Constant *Fn) {
- setHungoffOperand<0>(Fn);
- setValueSubclassDataBit(3, Fn != nullptr);
- }
- Constant *Function::getPrefixData() const {
- assert(hasPrefixData() && getNumOperands());
- return cast<Constant>(Op<1>());
- }
- void Function::setPrefixData(Constant *PrefixData) {
- setHungoffOperand<1>(PrefixData);
- setValueSubclassDataBit(1, PrefixData != nullptr);
- }
- Constant *Function::getPrologueData() const {
- assert(hasPrologueData() && getNumOperands());
- return cast<Constant>(Op<2>());
- }
- void Function::setPrologueData(Constant *PrologueData) {
- setHungoffOperand<2>(PrologueData);
- setValueSubclassDataBit(2, PrologueData != nullptr);
- }
- void Function::allocHungoffUselist() {
- // If we've already allocated a uselist, stop here.
- if (getNumOperands())
- return;
- allocHungoffUses(3, /*IsPhi=*/ false);
- setNumHungOffUseOperands(3);
- // Initialize the uselist with placeholder operands to allow traversal.
- auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
- Op<0>().set(CPN);
- Op<1>().set(CPN);
- Op<2>().set(CPN);
- }
- template <int Idx>
- void Function::setHungoffOperand(Constant *C) {
- if (C) {
- allocHungoffUselist();
- Op<Idx>().set(C);
- } else if (getNumOperands()) {
- Op<Idx>().set(
- ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
- }
- }
- void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
- assert(Bit < 16 && "SubclassData contains only 16 bits");
- if (On)
- setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
- else
- setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
- }
- void Function::setEntryCount(ProfileCount Count,
- const DenseSet<GlobalValue::GUID> *S) {
- assert(Count.hasValue());
- #if !defined(NDEBUG)
- auto PrevCount = getEntryCount();
- assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType());
- #endif
- auto ImportGUIDs = getImportGUIDs();
- if (S == nullptr && ImportGUIDs.size())
- S = &ImportGUIDs;
- MDBuilder MDB(getContext());
- setMetadata(
- LLVMContext::MD_prof,
- MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
- }
- void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
- const DenseSet<GlobalValue::GUID> *Imports) {
- setEntryCount(ProfileCount(Count, Type), Imports);
- }
- ProfileCount Function::getEntryCount(bool AllowSynthetic) const {
- MDNode *MD = getMetadata(LLVMContext::MD_prof);
- if (MD && MD->getOperand(0))
- if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
- if (MDS->getString().equals("function_entry_count")) {
- ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
- uint64_t Count = CI->getValue().getZExtValue();
- // A value of -1 is used for SamplePGO when there were no samples.
- // Treat this the same as unknown.
- if (Count == (uint64_t)-1)
- return ProfileCount::getInvalid();
- return ProfileCount(Count, PCT_Real);
- } else if (AllowSynthetic &&
- MDS->getString().equals("synthetic_function_entry_count")) {
- ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
- uint64_t Count = CI->getValue().getZExtValue();
- return ProfileCount(Count, PCT_Synthetic);
- }
- }
- return ProfileCount::getInvalid();
- }
- DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
- DenseSet<GlobalValue::GUID> R;
- if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
- if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
- if (MDS->getString().equals("function_entry_count"))
- for (unsigned i = 2; i < MD->getNumOperands(); i++)
- R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
- ->getValue()
- .getZExtValue());
- return R;
- }
- void Function::setSectionPrefix(StringRef Prefix) {
- MDBuilder MDB(getContext());
- setMetadata(LLVMContext::MD_section_prefix,
- MDB.createFunctionSectionPrefix(Prefix));
- }
- Optional<StringRef> Function::getSectionPrefix() const {
- if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
- assert(cast<MDString>(MD->getOperand(0))
- ->getString()
- .equals("function_section_prefix") &&
- "Metadata not match");
- return cast<MDString>(MD->getOperand(1))->getString();
- }
- return None;
- }
- bool Function::nullPointerIsDefined() const {
- return hasFnAttribute(Attribute::NullPointerIsValid);
- }
- bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
- if (F && F->nullPointerIsDefined())
- return true;
- if (AS != 0)
- return true;
- return false;
- }
|