Path: blob/main/contrib/llvm-project/llvm/lib/IR/MDBuilder.cpp
35233 views
//===---- llvm/MDBuilder.cpp - Builder for LLVM metadata ------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines the MDBuilder class, which is used as a convenient way to9// create LLVM metadata with a consistent and simplified interface.10//11//===----------------------------------------------------------------------===//1213#include "llvm/IR/MDBuilder.h"14#include "llvm/IR/Constants.h"15#include "llvm/IR/Function.h"16#include "llvm/IR/Metadata.h"17using namespace llvm;1819MDString *MDBuilder::createString(StringRef Str) {20return MDString::get(Context, Str);21}2223ConstantAsMetadata *MDBuilder::createConstant(Constant *C) {24return ConstantAsMetadata::get(C);25}2627MDNode *MDBuilder::createFPMath(float Accuracy) {28if (Accuracy == 0.0)29return nullptr;30assert(Accuracy > 0.0 && "Invalid fpmath accuracy!");31auto *Op =32createConstant(ConstantFP::get(Type::getFloatTy(Context), Accuracy));33return MDNode::get(Context, Op);34}3536MDNode *MDBuilder::createBranchWeights(uint32_t TrueWeight,37uint32_t FalseWeight, bool IsExpected) {38return createBranchWeights({TrueWeight, FalseWeight}, IsExpected);39}4041MDNode *MDBuilder::createLikelyBranchWeights() {42// Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp43return createBranchWeights((1U << 20) - 1, 1);44}4546MDNode *MDBuilder::createUnlikelyBranchWeights() {47// Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp48return createBranchWeights(1, (1U << 20) - 1);49}5051MDNode *MDBuilder::createBranchWeights(ArrayRef<uint32_t> Weights,52bool IsExpected) {53assert(Weights.size() >= 1 && "Need at least one branch weights!");5455unsigned int Offset = IsExpected ? 2 : 1;56SmallVector<Metadata *, 4> Vals(Weights.size() + Offset);57Vals[0] = createString("branch_weights");58if (IsExpected)59Vals[1] = createString("expected");6061Type *Int32Ty = Type::getInt32Ty(Context);62for (unsigned i = 0, e = Weights.size(); i != e; ++i)63Vals[i + Offset] = createConstant(ConstantInt::get(Int32Ty, Weights[i]));6465return MDNode::get(Context, Vals);66}6768MDNode *MDBuilder::createUnpredictable() {69return MDNode::get(Context, std::nullopt);70}7172MDNode *MDBuilder::createFunctionEntryCount(73uint64_t Count, bool Synthetic,74const DenseSet<GlobalValue::GUID> *Imports) {75Type *Int64Ty = Type::getInt64Ty(Context);76SmallVector<Metadata *, 8> Ops;77if (Synthetic)78Ops.push_back(createString("synthetic_function_entry_count"));79else80Ops.push_back(createString("function_entry_count"));81Ops.push_back(createConstant(ConstantInt::get(Int64Ty, Count)));82if (Imports) {83SmallVector<GlobalValue::GUID, 2> OrderID(Imports->begin(), Imports->end());84llvm::sort(OrderID);85for (auto ID : OrderID)86Ops.push_back(createConstant(ConstantInt::get(Int64Ty, ID)));87}88return MDNode::get(Context, Ops);89}9091MDNode *MDBuilder::createFunctionSectionPrefix(StringRef Prefix) {92return MDNode::get(93Context, {createString("function_section_prefix"), createString(Prefix)});94}9596MDNode *MDBuilder::createRange(const APInt &Lo, const APInt &Hi) {97assert(Lo.getBitWidth() == Hi.getBitWidth() && "Mismatched bitwidths!");9899Type *Ty = IntegerType::get(Context, Lo.getBitWidth());100return createRange(ConstantInt::get(Ty, Lo), ConstantInt::get(Ty, Hi));101}102103MDNode *MDBuilder::createRange(Constant *Lo, Constant *Hi) {104// If the range is everything then it is useless.105if (Hi == Lo)106return nullptr;107108// Return the range [Lo, Hi).109return MDNode::get(Context, {createConstant(Lo), createConstant(Hi)});110}111112MDNode *MDBuilder::createCallees(ArrayRef<Function *> Callees) {113SmallVector<Metadata *, 4> Ops;114for (Function *F : Callees)115Ops.push_back(createConstant(F));116return MDNode::get(Context, Ops);117}118119MDNode *MDBuilder::createCallbackEncoding(unsigned CalleeArgNo,120ArrayRef<int> Arguments,121bool VarArgArePassed) {122SmallVector<Metadata *, 4> Ops;123124Type *Int64 = Type::getInt64Ty(Context);125Ops.push_back(createConstant(ConstantInt::get(Int64, CalleeArgNo)));126127for (int ArgNo : Arguments)128Ops.push_back(createConstant(ConstantInt::get(Int64, ArgNo, true)));129130Type *Int1 = Type::getInt1Ty(Context);131Ops.push_back(createConstant(ConstantInt::get(Int1, VarArgArePassed)));132133return MDNode::get(Context, Ops);134}135136MDNode *MDBuilder::mergeCallbackEncodings(MDNode *ExistingCallbacks,137MDNode *NewCB) {138if (!ExistingCallbacks)139return MDNode::get(Context, {NewCB});140141auto *NewCBCalleeIdxAsCM = cast<ConstantAsMetadata>(NewCB->getOperand(0));142uint64_t NewCBCalleeIdx =143cast<ConstantInt>(NewCBCalleeIdxAsCM->getValue())->getZExtValue();144(void)NewCBCalleeIdx;145146SmallVector<Metadata *, 4> Ops;147unsigned NumExistingOps = ExistingCallbacks->getNumOperands();148Ops.resize(NumExistingOps + 1);149150for (unsigned u = 0; u < NumExistingOps; u++) {151Ops[u] = ExistingCallbacks->getOperand(u);152153auto *OldCBCalleeIdxAsCM =154cast<ConstantAsMetadata>(cast<MDNode>(Ops[u])->getOperand(0));155uint64_t OldCBCalleeIdx =156cast<ConstantInt>(OldCBCalleeIdxAsCM->getValue())->getZExtValue();157(void)OldCBCalleeIdx;158assert(NewCBCalleeIdx != OldCBCalleeIdx &&159"Cannot map a callback callee index twice!");160}161162Ops[NumExistingOps] = NewCB;163return MDNode::get(Context, Ops);164}165166MDNode *MDBuilder::createRTTIPointerPrologue(Constant *PrologueSig,167Constant *RTTI) {168SmallVector<Metadata *, 4> Ops;169Ops.push_back(createConstant(PrologueSig));170Ops.push_back(createConstant(RTTI));171return MDNode::get(Context, Ops);172}173174MDNode *MDBuilder::createPCSections(ArrayRef<PCSection> Sections) {175SmallVector<Metadata *, 2> Ops;176177for (const auto &Entry : Sections) {178const StringRef &Sec = Entry.first;179Ops.push_back(createString(Sec));180181// If auxiliary data for this section exists, append it.182const SmallVector<Constant *> &AuxConsts = Entry.second;183if (!AuxConsts.empty()) {184SmallVector<Metadata *, 1> AuxMDs;185AuxMDs.reserve(AuxConsts.size());186for (Constant *C : AuxConsts)187AuxMDs.push_back(createConstant(C));188Ops.push_back(MDNode::get(Context, AuxMDs));189}190}191192return MDNode::get(Context, Ops);193}194195MDNode *MDBuilder::createAnonymousAARoot(StringRef Name, MDNode *Extra) {196SmallVector<Metadata *, 3> Args(1, nullptr);197if (Extra)198Args.push_back(Extra);199if (!Name.empty())200Args.push_back(createString(Name));201MDNode *Root = MDNode::getDistinct(Context, Args);202203// At this point we have204// !0 = distinct !{null} <- root205// Replace the reserved operand with the root node itself.206Root->replaceOperandWith(0, Root);207208// We now have209// !0 = distinct !{!0} <- root210return Root;211}212213MDNode *MDBuilder::createTBAARoot(StringRef Name) {214return MDNode::get(Context, createString(Name));215}216217/// Return metadata for a non-root TBAA node with the given name,218/// parent in the TBAA tree, and value for 'pointsToConstantMemory'.219MDNode *MDBuilder::createTBAANode(StringRef Name, MDNode *Parent,220bool isConstant) {221if (isConstant) {222Constant *Flags = ConstantInt::get(Type::getInt64Ty(Context), 1);223return MDNode::get(Context,224{createString(Name), Parent, createConstant(Flags)});225}226return MDNode::get(Context, {createString(Name), Parent});227}228229MDNode *MDBuilder::createAliasScopeDomain(StringRef Name) {230return MDNode::get(Context, createString(Name));231}232233MDNode *MDBuilder::createAliasScope(StringRef Name, MDNode *Domain) {234return MDNode::get(Context, {createString(Name), Domain});235}236237/// Return metadata for a tbaa.struct node with the given238/// struct field descriptions.239MDNode *MDBuilder::createTBAAStructNode(ArrayRef<TBAAStructField> Fields) {240SmallVector<Metadata *, 4> Vals(Fields.size() * 3);241Type *Int64 = Type::getInt64Ty(Context);242for (unsigned i = 0, e = Fields.size(); i != e; ++i) {243Vals[i * 3 + 0] = createConstant(ConstantInt::get(Int64, Fields[i].Offset));244Vals[i * 3 + 1] = createConstant(ConstantInt::get(Int64, Fields[i].Size));245Vals[i * 3 + 2] = Fields[i].Type;246}247return MDNode::get(Context, Vals);248}249250/// Return metadata for a TBAA struct node in the type DAG251/// with the given name, a list of pairs (offset, field type in the type DAG).252MDNode *MDBuilder::createTBAAStructTypeNode(253StringRef Name, ArrayRef<std::pair<MDNode *, uint64_t>> Fields) {254SmallVector<Metadata *, 4> Ops(Fields.size() * 2 + 1);255Type *Int64 = Type::getInt64Ty(Context);256Ops[0] = createString(Name);257for (unsigned i = 0, e = Fields.size(); i != e; ++i) {258Ops[i * 2 + 1] = Fields[i].first;259Ops[i * 2 + 2] = createConstant(ConstantInt::get(Int64, Fields[i].second));260}261return MDNode::get(Context, Ops);262}263264/// Return metadata for a TBAA scalar type node with the265/// given name, an offset and a parent in the TBAA type DAG.266MDNode *MDBuilder::createTBAAScalarTypeNode(StringRef Name, MDNode *Parent,267uint64_t Offset) {268ConstantInt *Off = ConstantInt::get(Type::getInt64Ty(Context), Offset);269return MDNode::get(Context,270{createString(Name), Parent, createConstant(Off)});271}272273/// Return metadata for a TBAA tag node with the given274/// base type, access type and offset relative to the base type.275MDNode *MDBuilder::createTBAAStructTagNode(MDNode *BaseType, MDNode *AccessType,276uint64_t Offset, bool IsConstant) {277IntegerType *Int64 = Type::getInt64Ty(Context);278ConstantInt *Off = ConstantInt::get(Int64, Offset);279if (IsConstant) {280return MDNode::get(Context, {BaseType, AccessType, createConstant(Off),281createConstant(ConstantInt::get(Int64, 1))});282}283return MDNode::get(Context, {BaseType, AccessType, createConstant(Off)});284}285286MDNode *MDBuilder::createTBAATypeNode(MDNode *Parent, uint64_t Size,287Metadata *Id,288ArrayRef<TBAAStructField> Fields) {289SmallVector<Metadata *, 4> Ops(3 + Fields.size() * 3);290Type *Int64 = Type::getInt64Ty(Context);291Ops[0] = Parent;292Ops[1] = createConstant(ConstantInt::get(Int64, Size));293Ops[2] = Id;294for (unsigned I = 0, E = Fields.size(); I != E; ++I) {295Ops[I * 3 + 3] = Fields[I].Type;296Ops[I * 3 + 4] = createConstant(ConstantInt::get(Int64, Fields[I].Offset));297Ops[I * 3 + 5] = createConstant(ConstantInt::get(Int64, Fields[I].Size));298}299return MDNode::get(Context, Ops);300}301302MDNode *MDBuilder::createTBAAAccessTag(MDNode *BaseType, MDNode *AccessType,303uint64_t Offset, uint64_t Size,304bool IsImmutable) {305IntegerType *Int64 = Type::getInt64Ty(Context);306auto *OffsetNode = createConstant(ConstantInt::get(Int64, Offset));307auto *SizeNode = createConstant(ConstantInt::get(Int64, Size));308if (IsImmutable) {309auto *ImmutabilityFlagNode = createConstant(ConstantInt::get(Int64, 1));310return MDNode::get(Context, {BaseType, AccessType, OffsetNode, SizeNode,311ImmutabilityFlagNode});312}313return MDNode::get(Context, {BaseType, AccessType, OffsetNode, SizeNode});314}315316MDNode *MDBuilder::createMutableTBAAAccessTag(MDNode *Tag) {317MDNode *BaseType = cast<MDNode>(Tag->getOperand(0));318MDNode *AccessType = cast<MDNode>(Tag->getOperand(1));319Metadata *OffsetNode = Tag->getOperand(2);320uint64_t Offset = mdconst::extract<ConstantInt>(OffsetNode)->getZExtValue();321322bool NewFormat = isa<MDNode>(AccessType->getOperand(0));323324// See if the tag is already mutable.325unsigned ImmutabilityFlagOp = NewFormat ? 4 : 3;326if (Tag->getNumOperands() <= ImmutabilityFlagOp)327return Tag;328329// If Tag is already mutable then return it.330Metadata *ImmutabilityFlagNode = Tag->getOperand(ImmutabilityFlagOp);331if (!mdconst::extract<ConstantInt>(ImmutabilityFlagNode)->getValue())332return Tag;333334// Otherwise, create another node.335if (!NewFormat)336return createTBAAStructTagNode(BaseType, AccessType, Offset);337338Metadata *SizeNode = Tag->getOperand(3);339uint64_t Size = mdconst::extract<ConstantInt>(SizeNode)->getZExtValue();340return createTBAAAccessTag(BaseType, AccessType, Offset, Size);341}342343MDNode *MDBuilder::createIrrLoopHeaderWeight(uint64_t Weight) {344Metadata *Vals[] = {345createString("loop_header_weight"),346createConstant(ConstantInt::get(Type::getInt64Ty(Context), Weight)),347};348return MDNode::get(Context, Vals);349}350351MDNode *MDBuilder::createPseudoProbeDesc(uint64_t GUID, uint64_t Hash,352StringRef FName) {353auto *Int64Ty = Type::getInt64Ty(Context);354SmallVector<Metadata *, 3> Ops(3);355Ops[0] = createConstant(ConstantInt::get(Int64Ty, GUID));356Ops[1] = createConstant(ConstantInt::get(Int64Ty, Hash));357Ops[2] = createString(FName);358return MDNode::get(Context, Ops);359}360361MDNode *362MDBuilder::createLLVMStats(ArrayRef<std::pair<StringRef, uint64_t>> LLVMStats) {363auto *Int64Ty = Type::getInt64Ty(Context);364SmallVector<Metadata *, 4> Ops(LLVMStats.size() * 2);365for (size_t I = 0; I < LLVMStats.size(); I++) {366Ops[I * 2] = createString(LLVMStats[I].first);367Ops[I * 2 + 1] =368createConstant(ConstantInt::get(Int64Ty, LLVMStats[I].second));369}370return MDNode::get(Context, Ops);371}372373374