Path: blob/main/contrib/llvm-project/llvm/lib/IR/DebugInfo.cpp
35234 views
//===- DebugInfo.cpp - Debug Information Helper Classes -------------------===//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 implements the helper classes used to build and interpret debug9// information in LLVM IR form.10//11//===----------------------------------------------------------------------===//1213#include "llvm-c/DebugInfo.h"14#include "LLVMContextImpl.h"15#include "llvm/ADT/DenseMap.h"16#include "llvm/ADT/DenseSet.h"17#include "llvm/ADT/STLExtras.h"18#include "llvm/ADT/SmallPtrSet.h"19#include "llvm/ADT/SmallVector.h"20#include "llvm/ADT/StringRef.h"21#include "llvm/IR/BasicBlock.h"22#include "llvm/IR/Constants.h"23#include "llvm/IR/DIBuilder.h"24#include "llvm/IR/DebugInfo.h"25#include "llvm/IR/DebugInfoMetadata.h"26#include "llvm/IR/DebugLoc.h"27#include "llvm/IR/DebugProgramInstruction.h"28#include "llvm/IR/Function.h"29#include "llvm/IR/GVMaterializer.h"30#include "llvm/IR/Instruction.h"31#include "llvm/IR/IntrinsicInst.h"32#include "llvm/IR/LLVMContext.h"33#include "llvm/IR/Metadata.h"34#include "llvm/IR/Module.h"35#include "llvm/IR/PassManager.h"36#include "llvm/Support/Casting.h"37#include <algorithm>38#include <cassert>39#include <optional>40#include <utility>4142using namespace llvm;43using namespace llvm::at;44using namespace llvm::dwarf;4546TinyPtrVector<DbgDeclareInst *> llvm::findDbgDeclares(Value *V) {47// This function is hot. Check whether the value has any metadata to avoid a48// DenseMap lookup.49if (!V->isUsedByMetadata())50return {};51auto *L = LocalAsMetadata::getIfExists(V);52if (!L)53return {};54auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);55if (!MDV)56return {};5758TinyPtrVector<DbgDeclareInst *> Declares;59for (User *U : MDV->users())60if (auto *DDI = dyn_cast<DbgDeclareInst>(U))61Declares.push_back(DDI);6263return Declares;64}65TinyPtrVector<DbgVariableRecord *> llvm::findDVRDeclares(Value *V) {66// This function is hot. Check whether the value has any metadata to avoid a67// DenseMap lookup.68if (!V->isUsedByMetadata())69return {};70auto *L = LocalAsMetadata::getIfExists(V);71if (!L)72return {};7374TinyPtrVector<DbgVariableRecord *> Declares;75for (DbgVariableRecord *DVR : L->getAllDbgVariableRecordUsers())76if (DVR->getType() == DbgVariableRecord::LocationType::Declare)77Declares.push_back(DVR);7879return Declares;80}8182template <typename IntrinsicT, bool DbgAssignAndValuesOnly>83static void84findDbgIntrinsics(SmallVectorImpl<IntrinsicT *> &Result, Value *V,85SmallVectorImpl<DbgVariableRecord *> *DbgVariableRecords) {86// This function is hot. Check whether the value has any metadata to avoid a87// DenseMap lookup.88if (!V->isUsedByMetadata())89return;9091LLVMContext &Ctx = V->getContext();92// TODO: If this value appears multiple times in a DIArgList, we should still93// only add the owning DbgValueInst once; use this set to track ArgListUsers.94// This behaviour can be removed when we can automatically remove duplicates.95// V will also appear twice in a dbg.assign if its used in the both the value96// and address components.97SmallPtrSet<IntrinsicT *, 4> EncounteredIntrinsics;98SmallPtrSet<DbgVariableRecord *, 4> EncounteredDbgVariableRecords;99100/// Append IntrinsicT users of MetadataAsValue(MD).101auto AppendUsers = [&Ctx, &EncounteredIntrinsics,102&EncounteredDbgVariableRecords, &Result,103DbgVariableRecords](Metadata *MD) {104if (auto *MDV = MetadataAsValue::getIfExists(Ctx, MD)) {105for (User *U : MDV->users())106if (IntrinsicT *DVI = dyn_cast<IntrinsicT>(U))107if (EncounteredIntrinsics.insert(DVI).second)108Result.push_back(DVI);109}110if (!DbgVariableRecords)111return;112// Get DbgVariableRecords that use this as a single value.113if (LocalAsMetadata *L = dyn_cast<LocalAsMetadata>(MD)) {114for (DbgVariableRecord *DVR : L->getAllDbgVariableRecordUsers()) {115if (!DbgAssignAndValuesOnly || DVR->isDbgValue() || DVR->isDbgAssign())116if (EncounteredDbgVariableRecords.insert(DVR).second)117DbgVariableRecords->push_back(DVR);118}119}120};121122if (auto *L = LocalAsMetadata::getIfExists(V)) {123AppendUsers(L);124for (Metadata *AL : L->getAllArgListUsers()) {125AppendUsers(AL);126if (!DbgVariableRecords)127continue;128DIArgList *DI = cast<DIArgList>(AL);129for (DbgVariableRecord *DVR : DI->getAllDbgVariableRecordUsers())130if (!DbgAssignAndValuesOnly || DVR->isDbgValue() || DVR->isDbgAssign())131if (EncounteredDbgVariableRecords.insert(DVR).second)132DbgVariableRecords->push_back(DVR);133}134}135}136137void llvm::findDbgValues(138SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V,139SmallVectorImpl<DbgVariableRecord *> *DbgVariableRecords) {140findDbgIntrinsics<DbgValueInst, /*DbgAssignAndValuesOnly=*/true>(141DbgValues, V, DbgVariableRecords);142}143144void llvm::findDbgUsers(145SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers, Value *V,146SmallVectorImpl<DbgVariableRecord *> *DbgVariableRecords) {147findDbgIntrinsics<DbgVariableIntrinsic, /*DbgAssignAndValuesOnly=*/false>(148DbgUsers, V, DbgVariableRecords);149}150151DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {152if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))153return LocalScope->getSubprogram();154return nullptr;155}156157DebugLoc llvm::getDebugValueLoc(DbgVariableIntrinsic *DII) {158// Original dbg.declare must have a location.159const DebugLoc &DeclareLoc = DII->getDebugLoc();160MDNode *Scope = DeclareLoc.getScope();161DILocation *InlinedAt = DeclareLoc.getInlinedAt();162// Because no machine insts can come from debug intrinsics, only the scope163// and inlinedAt is significant. Zero line numbers are used in case this164// DebugLoc leaks into any adjacent instructions. Produce an unknown location165// with the correct scope / inlinedAt fields.166return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt);167}168169DebugLoc llvm::getDebugValueLoc(DbgVariableRecord *DVR) {170// Original dbg.declare must have a location.171const DebugLoc &DeclareLoc = DVR->getDebugLoc();172MDNode *Scope = DeclareLoc.getScope();173DILocation *InlinedAt = DeclareLoc.getInlinedAt();174// Because no machine insts can come from debug intrinsics, only the scope175// and inlinedAt is significant. Zero line numbers are used in case this176// DebugLoc leaks into any adjacent instructions. Produce an unknown location177// with the correct scope / inlinedAt fields.178return DILocation::get(DVR->getContext(), 0, 0, Scope, InlinedAt);179}180181//===----------------------------------------------------------------------===//182// DebugInfoFinder implementations.183//===----------------------------------------------------------------------===//184185void DebugInfoFinder::reset() {186CUs.clear();187SPs.clear();188GVs.clear();189TYs.clear();190Scopes.clear();191NodesSeen.clear();192}193194void DebugInfoFinder::processModule(const Module &M) {195for (auto *CU : M.debug_compile_units())196processCompileUnit(CU);197for (auto &F : M.functions()) {198if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))199processSubprogram(SP);200// There could be subprograms from inlined functions referenced from201// instructions only. Walk the function to find them.202for (const BasicBlock &BB : F)203for (const Instruction &I : BB)204processInstruction(M, I);205}206}207208void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) {209if (!addCompileUnit(CU))210return;211for (auto *DIG : CU->getGlobalVariables()) {212if (!addGlobalVariable(DIG))213continue;214auto *GV = DIG->getVariable();215processScope(GV->getScope());216processType(GV->getType());217}218for (auto *ET : CU->getEnumTypes())219processType(ET);220for (auto *RT : CU->getRetainedTypes())221if (auto *T = dyn_cast<DIType>(RT))222processType(T);223else224processSubprogram(cast<DISubprogram>(RT));225for (auto *Import : CU->getImportedEntities()) {226auto *Entity = Import->getEntity();227if (auto *T = dyn_cast<DIType>(Entity))228processType(T);229else if (auto *SP = dyn_cast<DISubprogram>(Entity))230processSubprogram(SP);231else if (auto *NS = dyn_cast<DINamespace>(Entity))232processScope(NS->getScope());233else if (auto *M = dyn_cast<DIModule>(Entity))234processScope(M->getScope());235}236}237238void DebugInfoFinder::processInstruction(const Module &M,239const Instruction &I) {240if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))241processVariable(M, DVI->getVariable());242243if (auto DbgLoc = I.getDebugLoc())244processLocation(M, DbgLoc.get());245246for (const DbgRecord &DPR : I.getDbgRecordRange())247processDbgRecord(M, DPR);248}249250void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {251if (!Loc)252return;253processScope(Loc->getScope());254processLocation(M, Loc->getInlinedAt());255}256257void DebugInfoFinder::processDbgRecord(const Module &M, const DbgRecord &DR) {258if (const DbgVariableRecord *DVR = dyn_cast<const DbgVariableRecord>(&DR))259processVariable(M, DVR->getVariable());260processLocation(M, DR.getDebugLoc().get());261}262263void DebugInfoFinder::processType(DIType *DT) {264if (!addType(DT))265return;266processScope(DT->getScope());267if (auto *ST = dyn_cast<DISubroutineType>(DT)) {268for (DIType *Ref : ST->getTypeArray())269processType(Ref);270return;271}272if (auto *DCT = dyn_cast<DICompositeType>(DT)) {273processType(DCT->getBaseType());274for (Metadata *D : DCT->getElements()) {275if (auto *T = dyn_cast<DIType>(D))276processType(T);277else if (auto *SP = dyn_cast<DISubprogram>(D))278processSubprogram(SP);279}280return;281}282if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {283processType(DDT->getBaseType());284}285}286287void DebugInfoFinder::processScope(DIScope *Scope) {288if (!Scope)289return;290if (auto *Ty = dyn_cast<DIType>(Scope)) {291processType(Ty);292return;293}294if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {295addCompileUnit(CU);296return;297}298if (auto *SP = dyn_cast<DISubprogram>(Scope)) {299processSubprogram(SP);300return;301}302if (!addScope(Scope))303return;304if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {305processScope(LB->getScope());306} else if (auto *NS = dyn_cast<DINamespace>(Scope)) {307processScope(NS->getScope());308} else if (auto *M = dyn_cast<DIModule>(Scope)) {309processScope(M->getScope());310}311}312313void DebugInfoFinder::processSubprogram(DISubprogram *SP) {314if (!addSubprogram(SP))315return;316processScope(SP->getScope());317// Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a318// ValueMap containing identity mappings for all of the DICompileUnit's, not319// just DISubprogram's, referenced from anywhere within the Function being320// cloned prior to calling MapMetadata / RemapInstruction to avoid their321// duplication later as DICompileUnit's are also directly referenced by322// llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.323// Also, DICompileUnit's may reference DISubprogram's too and therefore need324// to be at least looked through.325processCompileUnit(SP->getUnit());326processType(SP->getType());327for (auto *Element : SP->getTemplateParams()) {328if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {329processType(TType->getType());330} else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {331processType(TVal->getType());332}333}334}335336void DebugInfoFinder::processVariable(const Module &M,337const DILocalVariable *DV) {338if (!NodesSeen.insert(DV).second)339return;340processScope(DV->getScope());341processType(DV->getType());342}343344bool DebugInfoFinder::addType(DIType *DT) {345if (!DT)346return false;347348if (!NodesSeen.insert(DT).second)349return false;350351TYs.push_back(const_cast<DIType *>(DT));352return true;353}354355bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {356if (!CU)357return false;358if (!NodesSeen.insert(CU).second)359return false;360361CUs.push_back(CU);362return true;363}364365bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {366if (!NodesSeen.insert(DIG).second)367return false;368369GVs.push_back(DIG);370return true;371}372373bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {374if (!SP)375return false;376377if (!NodesSeen.insert(SP).second)378return false;379380SPs.push_back(SP);381return true;382}383384bool DebugInfoFinder::addScope(DIScope *Scope) {385if (!Scope)386return false;387// FIXME: Ocaml binding generates a scope with no content, we treat it388// as null for now.389if (Scope->getNumOperands() == 0)390return false;391if (!NodesSeen.insert(Scope).second)392return false;393Scopes.push_back(Scope);394return true;395}396397static MDNode *updateLoopMetadataDebugLocationsImpl(398MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) {399assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 &&400"Loop ID needs at least one operand");401assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID &&402"Loop ID should refer to itself");403404// Save space for the self-referential LoopID.405SmallVector<Metadata *, 4> MDs = {nullptr};406407for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) {408Metadata *MD = OrigLoopID->getOperand(i);409if (!MD)410MDs.push_back(nullptr);411else if (Metadata *NewMD = Updater(MD))412MDs.push_back(NewMD);413}414415MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs);416// Insert the self-referential LoopID.417NewLoopID->replaceOperandWith(0, NewLoopID);418return NewLoopID;419}420421void llvm::updateLoopMetadataDebugLocations(422Instruction &I, function_ref<Metadata *(Metadata *)> Updater) {423MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop);424if (!OrigLoopID)425return;426MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater);427I.setMetadata(LLVMContext::MD_loop, NewLoopID);428}429430/// Return true if a node is a DILocation or if a DILocation is431/// indirectly referenced by one of the node's children.432static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited,433SmallPtrSetImpl<Metadata *> &Reachable,434Metadata *MD) {435MDNode *N = dyn_cast_or_null<MDNode>(MD);436if (!N)437return false;438if (isa<DILocation>(N) || Reachable.count(N))439return true;440if (!Visited.insert(N).second)441return false;442for (auto &OpIt : N->operands()) {443Metadata *Op = OpIt.get();444if (isDILocationReachable(Visited, Reachable, Op)) {445// Don't return just yet as we want to visit all MD's children to446// initialize DILocationReachable in stripDebugLocFromLoopID447Reachable.insert(N);448}449}450return Reachable.count(N);451}452453static bool isAllDILocation(SmallPtrSetImpl<Metadata *> &Visited,454SmallPtrSetImpl<Metadata *> &AllDILocation,455const SmallPtrSetImpl<Metadata *> &DIReachable,456Metadata *MD) {457MDNode *N = dyn_cast_or_null<MDNode>(MD);458if (!N)459return false;460if (isa<DILocation>(N) || AllDILocation.count(N))461return true;462if (!DIReachable.count(N))463return false;464if (!Visited.insert(N).second)465return false;466for (auto &OpIt : N->operands()) {467Metadata *Op = OpIt.get();468if (Op == MD)469continue;470if (!isAllDILocation(Visited, AllDILocation, DIReachable, Op)) {471return false;472}473}474AllDILocation.insert(N);475return true;476}477478static Metadata *479stripLoopMDLoc(const SmallPtrSetImpl<Metadata *> &AllDILocation,480const SmallPtrSetImpl<Metadata *> &DIReachable, Metadata *MD) {481if (isa<DILocation>(MD) || AllDILocation.count(MD))482return nullptr;483484if (!DIReachable.count(MD))485return MD;486487MDNode *N = dyn_cast_or_null<MDNode>(MD);488if (!N)489return MD;490491SmallVector<Metadata *, 4> Args;492bool HasSelfRef = false;493for (unsigned i = 0; i < N->getNumOperands(); ++i) {494Metadata *A = N->getOperand(i);495if (!A) {496Args.push_back(nullptr);497} else if (A == MD) {498assert(i == 0 && "expected i==0 for self-reference");499HasSelfRef = true;500Args.push_back(nullptr);501} else if (Metadata *NewArg =502stripLoopMDLoc(AllDILocation, DIReachable, A)) {503Args.push_back(NewArg);504}505}506if (Args.empty() || (HasSelfRef && Args.size() == 1))507return nullptr;508509MDNode *NewMD = N->isDistinct() ? MDNode::getDistinct(N->getContext(), Args)510: MDNode::get(N->getContext(), Args);511if (HasSelfRef)512NewMD->replaceOperandWith(0, NewMD);513return NewMD;514}515516static MDNode *stripDebugLocFromLoopID(MDNode *N) {517assert(!N->operands().empty() && "Missing self reference?");518SmallPtrSet<Metadata *, 8> Visited, DILocationReachable, AllDILocation;519// If we already visited N, there is nothing to do.520if (!Visited.insert(N).second)521return N;522523// If there is no debug location, we do not have to rewrite this524// MDNode. This loop also initializes DILocationReachable, later525// needed by updateLoopMetadataDebugLocationsImpl; the use of526// count_if avoids an early exit.527if (!llvm::count_if(llvm::drop_begin(N->operands()),528[&Visited, &DILocationReachable](const MDOperand &Op) {529return isDILocationReachable(530Visited, DILocationReachable, Op.get());531}))532return N;533534Visited.clear();535// If there is only the debug location without any actual loop metadata, we536// can remove the metadata.537if (llvm::all_of(llvm::drop_begin(N->operands()),538[&Visited, &AllDILocation,539&DILocationReachable](const MDOperand &Op) {540return isAllDILocation(Visited, AllDILocation,541DILocationReachable, Op.get());542}))543return nullptr;544545return updateLoopMetadataDebugLocationsImpl(546N, [&AllDILocation, &DILocationReachable](Metadata *MD) -> Metadata * {547return stripLoopMDLoc(AllDILocation, DILocationReachable, MD);548});549}550551bool llvm::stripDebugInfo(Function &F) {552bool Changed = false;553if (F.hasMetadata(LLVMContext::MD_dbg)) {554Changed = true;555F.setSubprogram(nullptr);556}557558DenseMap<MDNode *, MDNode *> LoopIDsMap;559for (BasicBlock &BB : F) {560for (Instruction &I : llvm::make_early_inc_range(BB)) {561if (isa<DbgInfoIntrinsic>(&I)) {562I.eraseFromParent();563Changed = true;564continue;565}566if (I.getDebugLoc()) {567Changed = true;568I.setDebugLoc(DebugLoc());569}570if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) {571auto *NewLoopID = LoopIDsMap.lookup(LoopID);572if (!NewLoopID)573NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);574if (NewLoopID != LoopID)575I.setMetadata(LLVMContext::MD_loop, NewLoopID);576}577// Strip other attachments that are or use debug info.578if (I.hasMetadataOtherThanDebugLoc()) {579// Heapallocsites point into the DIType system.580I.setMetadata("heapallocsite", nullptr);581// DIAssignID are debug info metadata primitives.582I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);583}584I.dropDbgRecords();585}586}587return Changed;588}589590bool llvm::StripDebugInfo(Module &M) {591bool Changed = false;592593for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) {594// We're stripping debug info, and without them, coverage information595// doesn't quite make sense.596if (NMD.getName().starts_with("llvm.dbg.") ||597NMD.getName() == "llvm.gcov") {598NMD.eraseFromParent();599Changed = true;600}601}602603for (Function &F : M)604Changed |= stripDebugInfo(F);605606for (auto &GV : M.globals()) {607Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);608}609610if (GVMaterializer *Materializer = M.getMaterializer())611Materializer->setStripDebugInfo();612613return Changed;614}615616namespace {617618/// Helper class to downgrade -g metadata to -gline-tables-only metadata.619class DebugTypeInfoRemoval {620DenseMap<Metadata *, Metadata *> Replacements;621622public:623/// The (void)() type.624MDNode *EmptySubroutineType;625626private:627/// Remember what linkage name we originally had before stripping. If we end628/// up making two subprograms identical who originally had different linkage629/// names, then we need to make one of them distinct, to avoid them getting630/// uniqued. Maps the new node to the old linkage name.631DenseMap<DISubprogram *, StringRef> NewToLinkageName;632633// TODO: Remember the distinct subprogram we created for a given linkage name,634// so that we can continue to unique whenever possible. Map <newly created635// node, old linkage name> to the first (possibly distinct) mdsubprogram636// created for that combination. This is not strictly needed for correctness,637// but can cut down on the number of MDNodes and let us diff cleanly with the638// output of -gline-tables-only.639640public:641DebugTypeInfoRemoval(LLVMContext &C)642: EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,643MDNode::get(C, {}))) {}644645Metadata *map(Metadata *M) {646if (!M)647return nullptr;648auto Replacement = Replacements.find(M);649if (Replacement != Replacements.end())650return Replacement->second;651652return M;653}654MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }655656/// Recursively remap N and all its referenced children. Does a DF post-order657/// traversal, so as to remap bottoms up.658void traverseAndRemap(MDNode *N) { traverse(N); }659660private:661// Create a new DISubprogram, to replace the one given.662DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {663auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));664StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";665DISubprogram *Declaration = nullptr;666auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));667DIType *ContainingType =668cast_or_null<DIType>(map(MDS->getContainingType()));669auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));670auto Variables = nullptr;671auto TemplateParams = nullptr;672673// Make a distinct DISubprogram, for situations that warrent it.674auto distinctMDSubprogram = [&]() {675return DISubprogram::getDistinct(676MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,677FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(),678ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),679MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,680Variables);681};682683if (MDS->isDistinct())684return distinctMDSubprogram();685686auto *NewMDS = DISubprogram::get(687MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,688FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType,689MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),690MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);691692StringRef OldLinkageName = MDS->getLinkageName();693694// See if we need to make a distinct one.695auto OrigLinkage = NewToLinkageName.find(NewMDS);696if (OrigLinkage != NewToLinkageName.end()) {697if (OrigLinkage->second == OldLinkageName)698// We're good.699return NewMDS;700701// Otherwise, need to make a distinct one.702// TODO: Query the map to see if we already have one.703return distinctMDSubprogram();704}705706NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});707return NewMDS;708}709710/// Create a new compile unit, to replace the one given711DICompileUnit *getReplacementCU(DICompileUnit *CU) {712// Drop skeleton CUs.713if (CU->getDWOId())714return nullptr;715716auto *File = cast_or_null<DIFile>(map(CU->getFile()));717MDTuple *EnumTypes = nullptr;718MDTuple *RetainedTypes = nullptr;719MDTuple *GlobalVariables = nullptr;720MDTuple *ImportedEntities = nullptr;721return DICompileUnit::getDistinct(722CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),723CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),724CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,725RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),726CU->getDWOId(), CU->getSplitDebugInlining(),727CU->getDebugInfoForProfiling(), CU->getNameTableKind(),728CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK());729}730731DILocation *getReplacementMDLocation(DILocation *MLD) {732auto *Scope = map(MLD->getScope());733auto *InlinedAt = map(MLD->getInlinedAt());734if (MLD->isDistinct())735return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),736MLD->getColumn(), Scope, InlinedAt);737return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),738Scope, InlinedAt);739}740741/// Create a new generic MDNode, to replace the one given742MDNode *getReplacementMDNode(MDNode *N) {743SmallVector<Metadata *, 8> Ops;744Ops.reserve(N->getNumOperands());745for (auto &I : N->operands())746if (I)747Ops.push_back(map(I));748auto *Ret = MDNode::get(N->getContext(), Ops);749return Ret;750}751752/// Attempt to re-map N to a newly created node.753void remap(MDNode *N) {754if (Replacements.count(N))755return;756757auto doRemap = [&](MDNode *N) -> MDNode * {758if (!N)759return nullptr;760if (auto *MDSub = dyn_cast<DISubprogram>(N)) {761remap(MDSub->getUnit());762return getReplacementSubprogram(MDSub);763}764if (isa<DISubroutineType>(N))765return EmptySubroutineType;766if (auto *CU = dyn_cast<DICompileUnit>(N))767return getReplacementCU(CU);768if (isa<DIFile>(N))769return N;770if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))771// Remap to our referenced scope (recursively).772return mapNode(MDLB->getScope());773if (auto *MLD = dyn_cast<DILocation>(N))774return getReplacementMDLocation(MLD);775776// Otherwise, if we see these, just drop them now. Not strictly necessary,777// but this speeds things up a little.778if (isa<DINode>(N))779return nullptr;780781return getReplacementMDNode(N);782};783Replacements[N] = doRemap(N);784}785786/// Do the remapping traversal.787void traverse(MDNode *);788};789790} // end anonymous namespace791792void DebugTypeInfoRemoval::traverse(MDNode *N) {793if (!N || Replacements.count(N))794return;795796// To avoid cycles, as well as for efficiency sake, we will sometimes prune797// parts of the graph.798auto prune = [](MDNode *Parent, MDNode *Child) {799if (auto *MDS = dyn_cast<DISubprogram>(Parent))800return Child == MDS->getRetainedNodes().get();801return false;802};803804SmallVector<MDNode *, 16> ToVisit;805DenseSet<MDNode *> Opened;806807// Visit each node starting at N in post order, and map them.808ToVisit.push_back(N);809while (!ToVisit.empty()) {810auto *N = ToVisit.back();811if (!Opened.insert(N).second) {812// Close it.813remap(N);814ToVisit.pop_back();815continue;816}817for (auto &I : N->operands())818if (auto *MDN = dyn_cast_or_null<MDNode>(I))819if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&820!isa<DICompileUnit>(MDN))821ToVisit.push_back(MDN);822}823}824825bool llvm::stripNonLineTableDebugInfo(Module &M) {826bool Changed = false;827828// First off, delete the debug intrinsics.829auto RemoveUses = [&](StringRef Name) {830if (auto *DbgVal = M.getFunction(Name)) {831while (!DbgVal->use_empty())832cast<Instruction>(DbgVal->user_back())->eraseFromParent();833DbgVal->eraseFromParent();834Changed = true;835}836};837RemoveUses("llvm.dbg.declare");838RemoveUses("llvm.dbg.label");839RemoveUses("llvm.dbg.value");840841// Delete non-CU debug info named metadata nodes.842for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();843NMI != NME;) {844NamedMDNode *NMD = &*NMI;845++NMI;846// Specifically keep dbg.cu around.847if (NMD->getName() == "llvm.dbg.cu")848continue;849}850851// Drop all dbg attachments from global variables.852for (auto &GV : M.globals())853GV.eraseMetadata(LLVMContext::MD_dbg);854855DebugTypeInfoRemoval Mapper(M.getContext());856auto remap = [&](MDNode *Node) -> MDNode * {857if (!Node)858return nullptr;859Mapper.traverseAndRemap(Node);860auto *NewNode = Mapper.mapNode(Node);861Changed |= Node != NewNode;862Node = NewNode;863return NewNode;864};865866// Rewrite the DebugLocs to be equivalent to what867// -gline-tables-only would have created.868for (auto &F : M) {869if (auto *SP = F.getSubprogram()) {870Mapper.traverseAndRemap(SP);871auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));872Changed |= SP != NewSP;873F.setSubprogram(NewSP);874}875for (auto &BB : F) {876for (auto &I : BB) {877auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc {878auto *Scope = DL.getScope();879MDNode *InlinedAt = DL.getInlinedAt();880Scope = remap(Scope);881InlinedAt = remap(InlinedAt);882return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),883Scope, InlinedAt);884};885886if (I.getDebugLoc() != DebugLoc())887I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));888889// Remap DILocations in llvm.loop attachments.890updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * {891if (auto *Loc = dyn_cast_or_null<DILocation>(MD))892return remapDebugLoc(Loc).get();893return MD;894});895896// Strip heapallocsite attachments, they point into the DIType system.897if (I.hasMetadataOtherThanDebugLoc())898I.setMetadata("heapallocsite", nullptr);899900// Strip any DbgRecords attached.901I.dropDbgRecords();902}903}904}905906// Create a new llvm.dbg.cu, which is equivalent to the one907// -gline-tables-only would have created.908for (auto &NMD : M.named_metadata()) {909SmallVector<MDNode *, 8> Ops;910for (MDNode *Op : NMD.operands())911Ops.push_back(remap(Op));912913if (!Changed)914continue;915916NMD.clearOperands();917for (auto *Op : Ops)918if (Op)919NMD.addOperand(Op);920}921return Changed;922}923924unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {925if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(926M.getModuleFlag("Debug Info Version")))927return Val->getZExtValue();928return 0;929}930931void Instruction::applyMergedLocation(DILocation *LocA, DILocation *LocB) {932setDebugLoc(DILocation::getMergedLocation(LocA, LocB));933}934935void Instruction::mergeDIAssignID(936ArrayRef<const Instruction *> SourceInstructions) {937// Replace all uses (and attachments) of all the DIAssignIDs938// on SourceInstructions with a single merged value.939assert(getFunction() && "Uninserted instruction merged");940// Collect up the DIAssignID tags.941SmallVector<DIAssignID *, 4> IDs;942for (const Instruction *I : SourceInstructions) {943if (auto *MD = I->getMetadata(LLVMContext::MD_DIAssignID))944IDs.push_back(cast<DIAssignID>(MD));945assert(getFunction() == I->getFunction() &&946"Merging with instruction from another function not allowed");947}948949// Add this instruction's DIAssignID too, if it has one.950if (auto *MD = getMetadata(LLVMContext::MD_DIAssignID))951IDs.push_back(cast<DIAssignID>(MD));952953if (IDs.empty())954return; // No DIAssignID tags to process.955956DIAssignID *MergeID = IDs[0];957for (auto It = std::next(IDs.begin()), End = IDs.end(); It != End; ++It) {958if (*It != MergeID)959at::RAUW(*It, MergeID);960}961setMetadata(LLVMContext::MD_DIAssignID, MergeID);962}963964void Instruction::updateLocationAfterHoist() { dropLocation(); }965966void Instruction::dropLocation() {967const DebugLoc &DL = getDebugLoc();968if (!DL)969return;970971// If this isn't a call, drop the location to allow a location from a972// preceding instruction to propagate.973bool MayLowerToCall = false;974if (isa<CallBase>(this)) {975auto *II = dyn_cast<IntrinsicInst>(this);976MayLowerToCall =977!II || IntrinsicInst::mayLowerToFunctionCall(II->getIntrinsicID());978}979980if (!MayLowerToCall) {981setDebugLoc(DebugLoc());982return;983}984985// Set a line 0 location for calls to preserve scope information in case986// inlining occurs.987DISubprogram *SP = getFunction()->getSubprogram();988if (SP)989// If a function scope is available, set it on the line 0 location. When990// hoisting a call to a predecessor block, using the function scope avoids991// making it look like the callee was reached earlier than it should be.992setDebugLoc(DILocation::get(getContext(), 0, 0, SP));993else994// The parent function has no scope. Go ahead and drop the location. If995// the parent function is inlined, and the callee has a subprogram, the996// inliner will attach a location to the call.997//998// One alternative is to set a line 0 location with the existing scope and999// inlinedAt info. The location might be sensitive to when inlining occurs.1000setDebugLoc(DebugLoc());1001}10021003//===----------------------------------------------------------------------===//1004// LLVM C API implementations.1005//===----------------------------------------------------------------------===//10061007static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {1008switch (lang) {1009#define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR) \1010case LLVMDWARFSourceLanguage##NAME: \1011return ID;1012#include "llvm/BinaryFormat/Dwarf.def"1013#undef HANDLE_DW_LANG1014}1015llvm_unreachable("Unhandled Tag");1016}10171018template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {1019return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);1020}10211022static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {1023return static_cast<DINode::DIFlags>(Flags);1024}10251026static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) {1027return static_cast<LLVMDIFlags>(Flags);1028}10291030static DISubprogram::DISPFlags1031pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) {1032return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized);1033}10341035unsigned LLVMDebugMetadataVersion() {1036return DEBUG_METADATA_VERSION;1037}10381039LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {1040return wrap(new DIBuilder(*unwrap(M), false));1041}10421043LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {1044return wrap(new DIBuilder(*unwrap(M)));1045}10461047unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {1048return getDebugMetadataVersionFromModule(*unwrap(M));1049}10501051LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {1052return StripDebugInfo(*unwrap(M));1053}10541055void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {1056delete unwrap(Builder);1057}10581059void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {1060unwrap(Builder)->finalize();1061}10621063void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,1064LLVMMetadataRef subprogram) {1065unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram));1066}10671068LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(1069LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,1070LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,1071LLVMBool isOptimized, const char *Flags, size_t FlagsLen,1072unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,1073LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,1074LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen,1075const char *SDK, size_t SDKLen) {1076auto File = unwrapDI<DIFile>(FileRef);10771078return wrap(unwrap(Builder)->createCompileUnit(1079map_from_llvmDWARFsourcelanguage(Lang), File,1080StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen),1081RuntimeVer, StringRef(SplitName, SplitNameLen),1082static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,1083SplitDebugInlining, DebugInfoForProfiling,1084DICompileUnit::DebugNameTableKind::Default, false,1085StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen)));1086}10871088LLVMMetadataRef1089LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,1090size_t FilenameLen, const char *Directory,1091size_t DirectoryLen) {1092return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),1093StringRef(Directory, DirectoryLen)));1094}10951096LLVMMetadataRef1097LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope,1098const char *Name, size_t NameLen,1099const char *ConfigMacros, size_t ConfigMacrosLen,1100const char *IncludePath, size_t IncludePathLen,1101const char *APINotesFile, size_t APINotesFileLen) {1102return wrap(unwrap(Builder)->createModule(1103unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen),1104StringRef(ConfigMacros, ConfigMacrosLen),1105StringRef(IncludePath, IncludePathLen),1106StringRef(APINotesFile, APINotesFileLen)));1107}11081109LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,1110LLVMMetadataRef ParentScope,1111const char *Name, size_t NameLen,1112LLVMBool ExportSymbols) {1113return wrap(unwrap(Builder)->createNameSpace(1114unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols));1115}11161117LLVMMetadataRef LLVMDIBuilderCreateFunction(1118LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,1119size_t NameLen, const char *LinkageName, size_t LinkageNameLen,1120LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,1121LLVMBool IsLocalToUnit, LLVMBool IsDefinition,1122unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {1123return wrap(unwrap(Builder)->createFunction(1124unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},1125unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,1126map_from_llvmDIFlags(Flags),1127pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr,1128nullptr, nullptr));1129}113011311132LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(1133LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,1134LLVMMetadataRef File, unsigned Line, unsigned Col) {1135return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),1136unwrapDI<DIFile>(File),1137Line, Col));1138}11391140LLVMMetadataRef1141LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,1142LLVMMetadataRef Scope,1143LLVMMetadataRef File,1144unsigned Discriminator) {1145return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),1146unwrapDI<DIFile>(File),1147Discriminator));1148}11491150LLVMMetadataRef1151LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,1152LLVMMetadataRef Scope,1153LLVMMetadataRef NS,1154LLVMMetadataRef File,1155unsigned Line) {1156return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),1157unwrapDI<DINamespace>(NS),1158unwrapDI<DIFile>(File),1159Line));1160}11611162LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(1163LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,1164LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line,1165LLVMMetadataRef *Elements, unsigned NumElements) {1166auto Elts =1167(NumElements > 0)1168? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})1169: nullptr;1170return wrap(unwrap(Builder)->createImportedModule(1171unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity),1172unwrapDI<DIFile>(File), Line, Elts));1173}11741175LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(1176LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M,1177LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements,1178unsigned NumElements) {1179auto Elts =1180(NumElements > 0)1181? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})1182: nullptr;1183return wrap(unwrap(Builder)->createImportedModule(1184unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File),1185Line, Elts));1186}11871188LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(1189LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl,1190LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen,1191LLVMMetadataRef *Elements, unsigned NumElements) {1192auto Elts =1193(NumElements > 0)1194? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})1195: nullptr;1196return wrap(unwrap(Builder)->createImportedDeclaration(1197unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File),1198Line, {Name, NameLen}, Elts));1199}12001201LLVMMetadataRef1202LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,1203unsigned Column, LLVMMetadataRef Scope,1204LLVMMetadataRef InlinedAt) {1205return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),1206unwrap(InlinedAt)));1207}12081209unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) {1210return unwrapDI<DILocation>(Location)->getLine();1211}12121213unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) {1214return unwrapDI<DILocation>(Location)->getColumn();1215}12161217LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) {1218return wrap(unwrapDI<DILocation>(Location)->getScope());1219}12201221LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) {1222return wrap(unwrapDI<DILocation>(Location)->getInlinedAt());1223}12241225LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) {1226return wrap(unwrapDI<DIScope>(Scope)->getFile());1227}12281229const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) {1230auto Dir = unwrapDI<DIFile>(File)->getDirectory();1231*Len = Dir.size();1232return Dir.data();1233}12341235const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) {1236auto Name = unwrapDI<DIFile>(File)->getFilename();1237*Len = Name.size();1238return Name.data();1239}12401241const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) {1242if (auto Src = unwrapDI<DIFile>(File)->getSource()) {1243*Len = Src->size();1244return Src->data();1245}1246*Len = 0;1247return "";1248}12491250LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,1251LLVMMetadataRef ParentMacroFile,1252unsigned Line,1253LLVMDWARFMacinfoRecordType RecordType,1254const char *Name, size_t NameLen,1255const char *Value, size_t ValueLen) {1256return wrap(1257unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,1258static_cast<MacinfoRecordType>(RecordType),1259{Name, NameLen}, {Value, ValueLen}));1260}12611262LLVMMetadataRef1263LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,1264LLVMMetadataRef ParentMacroFile, unsigned Line,1265LLVMMetadataRef File) {1266return wrap(unwrap(Builder)->createTempMacroFile(1267unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));1268}12691270LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,1271const char *Name, size_t NameLen,1272int64_t Value,1273LLVMBool IsUnsigned) {1274return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value,1275IsUnsigned != 0));1276}12771278LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(1279LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,1280size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,1281uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements,1282unsigned NumElements, LLVMMetadataRef ClassTy) {1283auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),1284NumElements});1285return wrap(unwrap(Builder)->createEnumerationType(1286unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),1287LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));1288}12891290LLVMMetadataRef LLVMDIBuilderCreateUnionType(1291LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,1292size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,1293uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,1294LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,1295const char *UniqueId, size_t UniqueIdLen) {1296auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),1297NumElements});1298return wrap(unwrap(Builder)->createUnionType(1299unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),1300LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),1301Elts, RunTimeLang, {UniqueId, UniqueIdLen}));1302}130313041305LLVMMetadataRef1306LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size,1307uint32_t AlignInBits, LLVMMetadataRef Ty,1308LLVMMetadataRef *Subscripts,1309unsigned NumSubscripts) {1310auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),1311NumSubscripts});1312return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,1313unwrapDI<DIType>(Ty), Subs));1314}13151316LLVMMetadataRef1317LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size,1318uint32_t AlignInBits, LLVMMetadataRef Ty,1319LLVMMetadataRef *Subscripts,1320unsigned NumSubscripts) {1321auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),1322NumSubscripts});1323return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,1324unwrapDI<DIType>(Ty), Subs));1325}13261327LLVMMetadataRef1328LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,1329size_t NameLen, uint64_t SizeInBits,1330LLVMDWARFTypeEncoding Encoding,1331LLVMDIFlags Flags) {1332return wrap(unwrap(Builder)->createBasicType({Name, NameLen},1333SizeInBits, Encoding,1334map_from_llvmDIFlags(Flags)));1335}13361337LLVMMetadataRef LLVMDIBuilderCreatePointerType(1338LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,1339uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,1340const char *Name, size_t NameLen) {1341return wrap(unwrap(Builder)->createPointerType(1342unwrapDI<DIType>(PointeeTy), SizeInBits, AlignInBits, AddressSpace,1343{Name, NameLen}));1344}13451346LLVMMetadataRef LLVMDIBuilderCreateStructType(1347LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,1348size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,1349uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,1350LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,1351unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,1352const char *UniqueId, size_t UniqueIdLen) {1353auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),1354NumElements});1355return wrap(unwrap(Builder)->createStructType(1356unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),1357LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),1358unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,1359unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));1360}13611362LLVMMetadataRef LLVMDIBuilderCreateMemberType(1363LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,1364size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,1365uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,1366LLVMMetadataRef Ty) {1367return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),1368{Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,1369OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));1370}13711372LLVMMetadataRef1373LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,1374size_t NameLen) {1375return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));1376}13771378LLVMMetadataRef LLVMDIBuilderCreateStaticMemberType(1379LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,1380size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,1381LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,1382uint32_t AlignInBits) {1383return wrap(unwrap(Builder)->createStaticMemberType(1384unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),1385LineNumber, unwrapDI<DIType>(Type), map_from_llvmDIFlags(Flags),1386unwrap<Constant>(ConstantVal), DW_TAG_member, AlignInBits));1387}13881389LLVMMetadataRef1390LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,1391const char *Name, size_t NameLen,1392LLVMMetadataRef File, unsigned LineNo,1393uint64_t SizeInBits, uint32_t AlignInBits,1394uint64_t OffsetInBits, LLVMDIFlags Flags,1395LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) {1396return wrap(unwrap(Builder)->createObjCIVar(1397{Name, NameLen}, unwrapDI<DIFile>(File), LineNo,1398SizeInBits, AlignInBits, OffsetInBits,1399map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty),1400unwrapDI<MDNode>(PropertyNode)));1401}14021403LLVMMetadataRef1404LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,1405const char *Name, size_t NameLen,1406LLVMMetadataRef File, unsigned LineNo,1407const char *GetterName, size_t GetterNameLen,1408const char *SetterName, size_t SetterNameLen,1409unsigned PropertyAttributes,1410LLVMMetadataRef Ty) {1411return wrap(unwrap(Builder)->createObjCProperty(1412{Name, NameLen}, unwrapDI<DIFile>(File), LineNo,1413{GetterName, GetterNameLen}, {SetterName, SetterNameLen},1414PropertyAttributes, unwrapDI<DIType>(Ty)));1415}14161417LLVMMetadataRef1418LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,1419LLVMMetadataRef Type) {1420return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));1421}14221423LLVMMetadataRef1424LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type,1425const char *Name, size_t NameLen,1426LLVMMetadataRef File, unsigned LineNo,1427LLVMMetadataRef Scope, uint32_t AlignInBits) {1428return wrap(unwrap(Builder)->createTypedef(1429unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,1430unwrapDI<DIScope>(Scope), AlignInBits));1431}14321433LLVMMetadataRef1434LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,1435LLVMMetadataRef Ty, LLVMMetadataRef BaseTy,1436uint64_t BaseOffset, uint32_t VBPtrOffset,1437LLVMDIFlags Flags) {1438return wrap(unwrap(Builder)->createInheritance(1439unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy),1440BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags)));1441}14421443LLVMMetadataRef1444LLVMDIBuilderCreateForwardDecl(1445LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,1446size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,1447unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,1448const char *UniqueIdentifier, size_t UniqueIdentifierLen) {1449return wrap(unwrap(Builder)->createForwardDecl(1450Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),1451unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,1452AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));1453}14541455LLVMMetadataRef1456LLVMDIBuilderCreateReplaceableCompositeType(1457LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,1458size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,1459unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,1460LLVMDIFlags Flags, const char *UniqueIdentifier,1461size_t UniqueIdentifierLen) {1462return wrap(unwrap(Builder)->createReplaceableCompositeType(1463Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),1464unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,1465AlignInBits, map_from_llvmDIFlags(Flags),1466{UniqueIdentifier, UniqueIdentifierLen}));1467}14681469LLVMMetadataRef1470LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,1471LLVMMetadataRef Type) {1472return wrap(unwrap(Builder)->createQualifiedType(Tag,1473unwrapDI<DIType>(Type)));1474}14751476LLVMMetadataRef1477LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,1478LLVMMetadataRef Type) {1479return wrap(unwrap(Builder)->createReferenceType(Tag,1480unwrapDI<DIType>(Type)));1481}14821483LLVMMetadataRef1484LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {1485return wrap(unwrap(Builder)->createNullPtrType());1486}14871488LLVMMetadataRef1489LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,1490LLVMMetadataRef PointeeType,1491LLVMMetadataRef ClassType,1492uint64_t SizeInBits,1493uint32_t AlignInBits,1494LLVMDIFlags Flags) {1495return wrap(unwrap(Builder)->createMemberPointerType(1496unwrapDI<DIType>(PointeeType),1497unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,1498map_from_llvmDIFlags(Flags)));1499}15001501LLVMMetadataRef1502LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,1503LLVMMetadataRef Scope,1504const char *Name, size_t NameLen,1505LLVMMetadataRef File, unsigned LineNumber,1506uint64_t SizeInBits,1507uint64_t OffsetInBits,1508uint64_t StorageOffsetInBits,1509LLVMDIFlags Flags, LLVMMetadataRef Type) {1510return wrap(unwrap(Builder)->createBitFieldMemberType(1511unwrapDI<DIScope>(Scope), {Name, NameLen},1512unwrapDI<DIFile>(File), LineNumber,1513SizeInBits, OffsetInBits, StorageOffsetInBits,1514map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type)));1515}15161517LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,1518LLVMMetadataRef Scope, const char *Name, size_t NameLen,1519LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,1520uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,1521LLVMMetadataRef DerivedFrom,1522LLVMMetadataRef *Elements, unsigned NumElements,1523LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode,1524const char *UniqueIdentifier, size_t UniqueIdentifierLen) {1525auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),1526NumElements});1527return wrap(unwrap(Builder)->createClassType(1528unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),1529LineNumber, SizeInBits, AlignInBits, OffsetInBits,1530map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom), Elts,1531/*RunTimeLang=*/0, unwrapDI<DIType>(VTableHolder),1532unwrapDI<MDNode>(TemplateParamsNode),1533{UniqueIdentifier, UniqueIdentifierLen}));1534}15351536LLVMMetadataRef1537LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,1538LLVMMetadataRef Type) {1539return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));1540}15411542uint16_t LLVMGetDINodeTag(LLVMMetadataRef MD) {1543return unwrapDI<DINode>(MD)->getTag();1544}15451546const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) {1547StringRef Str = unwrapDI<DIType>(DType)->getName();1548*Length = Str.size();1549return Str.data();1550}15511552uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) {1553return unwrapDI<DIType>(DType)->getSizeInBits();1554}15551556uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) {1557return unwrapDI<DIType>(DType)->getOffsetInBits();1558}15591560uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) {1561return unwrapDI<DIType>(DType)->getAlignInBits();1562}15631564unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) {1565return unwrapDI<DIType>(DType)->getLine();1566}15671568LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) {1569return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags());1570}15711572LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,1573LLVMMetadataRef *Types,1574size_t Length) {1575return wrap(1576unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get());1577}15781579LLVMMetadataRef1580LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,1581LLVMMetadataRef File,1582LLVMMetadataRef *ParameterTypes,1583unsigned NumParameterTypes,1584LLVMDIFlags Flags) {1585auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),1586NumParameterTypes});1587return wrap(unwrap(Builder)->createSubroutineType(1588Elts, map_from_llvmDIFlags(Flags)));1589}15901591LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,1592uint64_t *Addr, size_t Length) {1593return wrap(1594unwrap(Builder)->createExpression(ArrayRef<uint64_t>(Addr, Length)));1595}15961597LLVMMetadataRef1598LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,1599uint64_t Value) {1600return wrap(unwrap(Builder)->createConstantValueExpression(Value));1601}16021603LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(1604LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,1605size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File,1606unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,1607LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) {1608return wrap(unwrap(Builder)->createGlobalVariableExpression(1609unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen},1610unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,1611true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),1612nullptr, AlignInBits));1613}16141615LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) {1616return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());1617}16181619LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(1620LLVMMetadataRef GVE) {1621return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());1622}16231624LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) {1625return wrap(unwrapDI<DIVariable>(Var)->getFile());1626}16271628LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) {1629return wrap(unwrapDI<DIVariable>(Var)->getScope());1630}16311632unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) {1633return unwrapDI<DIVariable>(Var)->getLine();1634}16351636LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data,1637size_t Count) {1638return wrap(1639MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release());1640}16411642void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) {1643MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode));1644}16451646void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,1647LLVMMetadataRef Replacement) {1648auto *Node = unwrapDI<MDNode>(TargetMetadata);1649Node->replaceAllUsesWith(unwrap(Replacement));1650MDNode::deleteTemporary(Node);1651}16521653LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(1654LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,1655size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File,1656unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,1657LLVMMetadataRef Decl, uint32_t AlignInBits) {1658return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl(1659unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen},1660unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,1661unwrapDI<MDNode>(Decl), nullptr, AlignInBits));1662}16631664LLVMDbgRecordRef LLVMDIBuilderInsertDeclareRecordBefore(1665LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,1666LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMValueRef Instr) {1667DbgInstPtr DbgInst = unwrap(Builder)->insertDeclare(1668unwrap(Storage), unwrap<DILocalVariable>(VarInfo),1669unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),1670unwrap<Instruction>(Instr));1671// This assert will fail if the module is in the old debug info format.1672// This function should only be called if the module is in the new1673// debug info format.1674// See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes,1675// LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info.1676assert(isa<DbgRecord *>(DbgInst) &&1677"Function unexpectedly in old debug info format");1678return wrap(cast<DbgRecord *>(DbgInst));1679}16801681LLVMDbgRecordRef LLVMDIBuilderInsertDeclareRecordAtEnd(1682LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,1683LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {1684DbgInstPtr DbgInst = unwrap(Builder)->insertDeclare(1685unwrap(Storage), unwrap<DILocalVariable>(VarInfo),1686unwrap<DIExpression>(Expr), unwrap<DILocation>(DL), unwrap(Block));1687// This assert will fail if the module is in the old debug info format.1688// This function should only be called if the module is in the new1689// debug info format.1690// See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes,1691// LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info.1692assert(isa<DbgRecord *>(DbgInst) &&1693"Function unexpectedly in old debug info format");1694return wrap(cast<DbgRecord *>(DbgInst));1695}16961697LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueRecordBefore(1698LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,1699LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr) {1700DbgInstPtr DbgInst = unwrap(Builder)->insertDbgValueIntrinsic(1701unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),1702unwrap<DILocation>(DebugLoc), unwrap<Instruction>(Instr));1703// This assert will fail if the module is in the old debug info format.1704// This function should only be called if the module is in the new1705// debug info format.1706// See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes,1707// LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info.1708assert(isa<DbgRecord *>(DbgInst) &&1709"Function unexpectedly in old debug info format");1710return wrap(cast<DbgRecord *>(DbgInst));1711}17121713LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueRecordAtEnd(1714LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,1715LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block) {1716DbgInstPtr DbgInst = unwrap(Builder)->insertDbgValueIntrinsic(1717unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),1718unwrap<DILocation>(DebugLoc), unwrap(Block));1719// This assert will fail if the module is in the old debug info format.1720// This function should only be called if the module is in the new1721// debug info format.1722// See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes,1723// LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info.1724assert(isa<DbgRecord *>(DbgInst) &&1725"Function unexpectedly in old debug info format");1726return wrap(cast<DbgRecord *>(DbgInst));1727}17281729LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(1730LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,1731size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,1732LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) {1733return wrap(unwrap(Builder)->createAutoVariable(1734unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File),1735LineNo, unwrap<DIType>(Ty), AlwaysPreserve,1736map_from_llvmDIFlags(Flags), AlignInBits));1737}17381739LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(1740LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,1741size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo,1742LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) {1743return wrap(unwrap(Builder)->createParameterVariable(1744unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File),1745LineNo, unwrap<DIType>(Ty), AlwaysPreserve,1746map_from_llvmDIFlags(Flags)));1747}17481749LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,1750int64_t Lo, int64_t Count) {1751return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count));1752}17531754LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,1755LLVMMetadataRef *Data,1756size_t Length) {1757Metadata **DataValue = unwrap(Data);1758return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get());1759}17601761LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {1762return wrap(unwrap<Function>(Func)->getSubprogram());1763}17641765void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {1766unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));1767}17681769unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) {1770return unwrapDI<DISubprogram>(Subprogram)->getLine();1771}17721773LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) {1774return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode());1775}17761777void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) {1778if (Loc)1779unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc)));1780else1781unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc());1782}17831784LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) {1785switch(unwrap(Metadata)->getMetadataID()) {1786#define HANDLE_METADATA_LEAF(CLASS) \1787case Metadata::CLASS##Kind: \1788return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;1789#include "llvm/IR/Metadata.def"1790default:1791return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind;1792}1793}17941795AssignmentInstRange at::getAssignmentInsts(DIAssignID *ID) {1796assert(ID && "Expected non-null ID");1797LLVMContext &Ctx = ID->getContext();1798auto &Map = Ctx.pImpl->AssignmentIDToInstrs;17991800auto MapIt = Map.find(ID);1801if (MapIt == Map.end())1802return make_range(nullptr, nullptr);18031804return make_range(MapIt->second.begin(), MapIt->second.end());1805}18061807AssignmentMarkerRange at::getAssignmentMarkers(DIAssignID *ID) {1808assert(ID && "Expected non-null ID");1809LLVMContext &Ctx = ID->getContext();18101811auto *IDAsValue = MetadataAsValue::getIfExists(Ctx, ID);18121813// The ID is only used wrapped in MetadataAsValue(ID), so lets check that1814// one of those already exists first.1815if (!IDAsValue)1816return make_range(Value::user_iterator(), Value::user_iterator());18171818return make_range(IDAsValue->user_begin(), IDAsValue->user_end());1819}18201821void at::deleteAssignmentMarkers(const Instruction *Inst) {1822auto Range = getAssignmentMarkers(Inst);1823SmallVector<DbgVariableRecord *> DVRAssigns = getDVRAssignmentMarkers(Inst);1824if (Range.empty() && DVRAssigns.empty())1825return;1826SmallVector<DbgAssignIntrinsic *> ToDelete(Range.begin(), Range.end());1827for (auto *DAI : ToDelete)1828DAI->eraseFromParent();1829for (auto *DVR : DVRAssigns)1830DVR->eraseFromParent();1831}18321833void at::RAUW(DIAssignID *Old, DIAssignID *New) {1834// Replace attachments.1835AssignmentInstRange InstRange = getAssignmentInsts(Old);1836// Use intermediate storage for the instruction ptrs because the1837// getAssignmentInsts range iterators will be invalidated by adding and1838// removing DIAssignID attachments.1839SmallVector<Instruction *> InstVec(InstRange.begin(), InstRange.end());1840for (auto *I : InstVec)1841I->setMetadata(LLVMContext::MD_DIAssignID, New);18421843Old->replaceAllUsesWith(New);1844}18451846void at::deleteAll(Function *F) {1847SmallVector<DbgAssignIntrinsic *, 12> ToDelete;1848SmallVector<DbgVariableRecord *, 12> DPToDelete;1849for (BasicBlock &BB : *F) {1850for (Instruction &I : BB) {1851for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))1852if (DVR.isDbgAssign())1853DPToDelete.push_back(&DVR);1854if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I))1855ToDelete.push_back(DAI);1856else1857I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);1858}1859}1860for (auto *DAI : ToDelete)1861DAI->eraseFromParent();1862for (auto *DVR : DPToDelete)1863DVR->eraseFromParent();1864}18651866/// FIXME: Remove this wrapper function and call1867/// DIExpression::calculateFragmentIntersect directly.1868template <typename T>1869bool calculateFragmentIntersectImpl(1870const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,1871uint64_t SliceSizeInBits, const T *AssignRecord,1872std::optional<DIExpression::FragmentInfo> &Result) {1873// No overlap if this DbgRecord describes a killed location.1874if (AssignRecord->isKillAddress())1875return false;18761877int64_t AddrOffsetInBits;1878{1879int64_t AddrOffsetInBytes;1880SmallVector<uint64_t> PostOffsetOps; //< Unused.1881// Bail if we can't find a constant offset (or none) in the expression.1882if (!AssignRecord->getAddressExpression()->extractLeadingOffset(1883AddrOffsetInBytes, PostOffsetOps))1884return false;1885AddrOffsetInBits = AddrOffsetInBytes * 8;1886}18871888Value *Addr = AssignRecord->getAddress();1889// FIXME: It may not always be zero.1890int64_t BitExtractOffsetInBits = 0;1891DIExpression::FragmentInfo VarFrag =1892AssignRecord->getFragmentOrEntireVariable();18931894int64_t OffsetFromLocationInBits; //< Unused.1895return DIExpression::calculateFragmentIntersect(1896DL, Dest, SliceOffsetInBits, SliceSizeInBits, Addr, AddrOffsetInBits,1897BitExtractOffsetInBits, VarFrag, Result, OffsetFromLocationInBits);1898}18991900/// FIXME: Remove this wrapper function and call1901/// DIExpression::calculateFragmentIntersect directly.1902bool at::calculateFragmentIntersect(1903const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,1904uint64_t SliceSizeInBits, const DbgAssignIntrinsic *DbgAssign,1905std::optional<DIExpression::FragmentInfo> &Result) {1906return calculateFragmentIntersectImpl(DL, Dest, SliceOffsetInBits,1907SliceSizeInBits, DbgAssign, Result);1908}19091910/// FIXME: Remove this wrapper function and call1911/// DIExpression::calculateFragmentIntersect directly.1912bool at::calculateFragmentIntersect(1913const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,1914uint64_t SliceSizeInBits, const DbgVariableRecord *DVRAssign,1915std::optional<DIExpression::FragmentInfo> &Result) {1916return calculateFragmentIntersectImpl(DL, Dest, SliceOffsetInBits,1917SliceSizeInBits, DVRAssign, Result);1918}19191920/// Update inlined instructions' DIAssignID metadata. We need to do this1921/// otherwise a function inlined more than once into the same function1922/// will cause DIAssignID to be shared by many instructions.1923void at::remapAssignID(DenseMap<DIAssignID *, DIAssignID *> &Map,1924Instruction &I) {1925auto GetNewID = [&Map](Metadata *Old) {1926DIAssignID *OldID = cast<DIAssignID>(Old);1927if (DIAssignID *NewID = Map.lookup(OldID))1928return NewID;1929DIAssignID *NewID = DIAssignID::getDistinct(OldID->getContext());1930Map[OldID] = NewID;1931return NewID;1932};1933// If we find a DIAssignID attachment or use, replace it with a new version.1934for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {1935if (DVR.isDbgAssign())1936DVR.setAssignId(GetNewID(DVR.getAssignID()));1937}1938if (auto *ID = I.getMetadata(LLVMContext::MD_DIAssignID))1939I.setMetadata(LLVMContext::MD_DIAssignID, GetNewID(ID));1940else if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I))1941DAI->setAssignId(GetNewID(DAI->getAssignID()));1942}19431944/// Collect constant properies (base, size, offset) of \p StoreDest.1945/// Return std::nullopt if any properties are not constants or the1946/// offset from the base pointer is negative.1947static std::optional<AssignmentInfo>1948getAssignmentInfoImpl(const DataLayout &DL, const Value *StoreDest,1949TypeSize SizeInBits) {1950if (SizeInBits.isScalable())1951return std::nullopt;1952APInt GEPOffset(DL.getIndexTypeSizeInBits(StoreDest->getType()), 0);1953const Value *Base = StoreDest->stripAndAccumulateConstantOffsets(1954DL, GEPOffset, /*AllowNonInbounds*/ true);19551956if (GEPOffset.isNegative())1957return std::nullopt;19581959uint64_t OffsetInBytes = GEPOffset.getLimitedValue();1960// Check for overflow.1961if (OffsetInBytes == UINT64_MAX)1962return std::nullopt;1963if (const auto *Alloca = dyn_cast<AllocaInst>(Base))1964return AssignmentInfo(DL, Alloca, OffsetInBytes * 8, SizeInBits);1965return std::nullopt;1966}19671968std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,1969const MemIntrinsic *I) {1970const Value *StoreDest = I->getRawDest();1971// Assume 8 bit bytes.1972auto *ConstLengthInBytes = dyn_cast<ConstantInt>(I->getLength());1973if (!ConstLengthInBytes)1974// We can't use a non-const size, bail.1975return std::nullopt;1976uint64_t SizeInBits = 8 * ConstLengthInBytes->getZExtValue();1977return getAssignmentInfoImpl(DL, StoreDest, TypeSize::getFixed(SizeInBits));1978}19791980std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,1981const StoreInst *SI) {1982TypeSize SizeInBits = DL.getTypeSizeInBits(SI->getValueOperand()->getType());1983return getAssignmentInfoImpl(DL, SI->getPointerOperand(), SizeInBits);1984}19851986std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,1987const AllocaInst *AI) {1988TypeSize SizeInBits = DL.getTypeSizeInBits(AI->getAllocatedType());1989return getAssignmentInfoImpl(DL, AI, SizeInBits);1990}19911992/// Returns nullptr if the assignment shouldn't be attributed to this variable.1993static void emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest,1994Instruction &StoreLikeInst, const VarRecord &VarRec,1995DIBuilder &DIB) {1996auto *ID = StoreLikeInst.getMetadata(LLVMContext::MD_DIAssignID);1997assert(ID && "Store instruction must have DIAssignID metadata");1998(void)ID;19992000const uint64_t StoreStartBit = Info.OffsetInBits;2001const uint64_t StoreEndBit = Info.OffsetInBits + Info.SizeInBits;20022003uint64_t FragStartBit = StoreStartBit;2004uint64_t FragEndBit = StoreEndBit;20052006bool StoreToWholeVariable = Info.StoreToWholeAlloca;2007if (auto Size = VarRec.Var->getSizeInBits()) {2008// NOTE: trackAssignments doesn't understand base expressions yet, so all2009// variables that reach here are guaranteed to start at offset 0 in the2010// alloca.2011const uint64_t VarStartBit = 0;2012const uint64_t VarEndBit = *Size;20132014// FIXME: trim FragStartBit when nonzero VarStartBit is supported.2015FragEndBit = std::min(FragEndBit, VarEndBit);20162017// Discard stores to bits outside this variable.2018if (FragStartBit >= FragEndBit)2019return;20202021StoreToWholeVariable = FragStartBit <= VarStartBit && FragEndBit >= *Size;2022}20232024DIExpression *Expr =2025DIExpression::get(StoreLikeInst.getContext(), std::nullopt);2026if (!StoreToWholeVariable) {2027auto R = DIExpression::createFragmentExpression(Expr, FragStartBit,2028FragEndBit - FragStartBit);2029assert(R.has_value() && "failed to create fragment expression");2030Expr = *R;2031}2032DIExpression *AddrExpr =2033DIExpression::get(StoreLikeInst.getContext(), std::nullopt);2034if (StoreLikeInst.getParent()->IsNewDbgInfoFormat) {2035auto *Assign = DbgVariableRecord::createLinkedDVRAssign(2036&StoreLikeInst, Val, VarRec.Var, Expr, Dest, AddrExpr, VarRec.DL);2037(void)Assign;2038LLVM_DEBUG(if (Assign) errs() << " > INSERT: " << *Assign << "\n");2039return;2040}2041auto Assign = DIB.insertDbgAssign(&StoreLikeInst, Val, VarRec.Var, Expr, Dest,2042AddrExpr, VarRec.DL);2043(void)Assign;2044LLVM_DEBUG(if (!Assign.isNull()) {2045if (Assign.is<DbgRecord *>())2046errs() << " > INSERT: " << *Assign.get<DbgRecord *>() << "\n";2047else2048errs() << " > INSERT: " << *Assign.get<Instruction *>() << "\n";2049});2050}20512052#undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h).2053#define DEBUG_TYPE "assignment-tracking"20542055void at::trackAssignments(Function::iterator Start, Function::iterator End,2056const StorageToVarsMap &Vars, const DataLayout &DL,2057bool DebugPrints) {2058// Early-exit if there are no interesting variables.2059if (Vars.empty())2060return;20612062auto &Ctx = Start->getContext();2063auto &Module = *Start->getModule();20642065// Undef type doesn't matter, so long as it isn't void. Let's just use i1.2066auto *Undef = UndefValue::get(Type::getInt1Ty(Ctx));2067DIBuilder DIB(Module, /*AllowUnresolved*/ false);20682069// Scan the instructions looking for stores to local variables' storage.2070LLVM_DEBUG(errs() << "# Scanning instructions\n");2071for (auto BBI = Start; BBI != End; ++BBI) {2072for (Instruction &I : *BBI) {20732074std::optional<AssignmentInfo> Info;2075Value *ValueComponent = nullptr;2076Value *DestComponent = nullptr;2077if (auto *AI = dyn_cast<AllocaInst>(&I)) {2078// We want to track the variable's stack home from its alloca's2079// position onwards so we treat it as an assignment (where the stored2080// value is Undef).2081Info = getAssignmentInfo(DL, AI);2082ValueComponent = Undef;2083DestComponent = AI;2084} else if (auto *SI = dyn_cast<StoreInst>(&I)) {2085Info = getAssignmentInfo(DL, SI);2086ValueComponent = SI->getValueOperand();2087DestComponent = SI->getPointerOperand();2088} else if (auto *MI = dyn_cast<MemTransferInst>(&I)) {2089Info = getAssignmentInfo(DL, MI);2090// May not be able to represent this value easily.2091ValueComponent = Undef;2092DestComponent = MI->getOperand(0);2093} else if (auto *MI = dyn_cast<MemSetInst>(&I)) {2094Info = getAssignmentInfo(DL, MI);2095// If we're zero-initing we can state the assigned value is zero,2096// otherwise use undef.2097auto *ConstValue = dyn_cast<ConstantInt>(MI->getOperand(1));2098if (ConstValue && ConstValue->isZero())2099ValueComponent = ConstValue;2100else2101ValueComponent = Undef;2102DestComponent = MI->getOperand(0);2103} else {2104// Not a store-like instruction.2105continue;2106}21072108assert(ValueComponent && DestComponent);2109LLVM_DEBUG(errs() << "SCAN: Found store-like: " << I << "\n");21102111// Check if getAssignmentInfo failed to understand this store.2112if (!Info.has_value()) {2113LLVM_DEBUG(2114errs()2115<< " | SKIP: Untrackable store (e.g. through non-const gep)\n");2116continue;2117}2118LLVM_DEBUG(errs() << " | BASE: " << *Info->Base << "\n");21192120// Check if the store destination is a local variable with debug info.2121auto LocalIt = Vars.find(Info->Base);2122if (LocalIt == Vars.end()) {2123LLVM_DEBUG(2124errs()2125<< " | SKIP: Base address not associated with local variable\n");2126continue;2127}21282129DIAssignID *ID =2130cast_or_null<DIAssignID>(I.getMetadata(LLVMContext::MD_DIAssignID));2131if (!ID) {2132ID = DIAssignID::getDistinct(Ctx);2133I.setMetadata(LLVMContext::MD_DIAssignID, ID);2134}21352136for (const VarRecord &R : LocalIt->second)2137emitDbgAssign(*Info, ValueComponent, DestComponent, I, R, DIB);2138}2139}2140}21412142bool AssignmentTrackingPass::runOnFunction(Function &F) {2143// No value in assignment tracking without optimisations.2144if (F.hasFnAttribute(Attribute::OptimizeNone))2145return /*Changed*/ false;21462147bool Changed = false;2148auto *DL = &F.getDataLayout();2149// Collect a map of {backing storage : dbg.declares} (currently "backing2150// storage" is limited to Allocas). We'll use this to find dbg.declares to2151// delete after running `trackAssignments`.2152DenseMap<const AllocaInst *, SmallPtrSet<DbgDeclareInst *, 2>> DbgDeclares;2153DenseMap<const AllocaInst *, SmallPtrSet<DbgVariableRecord *, 2>> DVRDeclares;2154// Create another similar map of {storage : variables} that we'll pass to2155// trackAssignments.2156StorageToVarsMap Vars;2157auto ProcessDeclare = [&](auto *Declare, auto &DeclareList) {2158// FIXME: trackAssignments doesn't let you specify any modifiers to the2159// variable (e.g. fragment) or location (e.g. offset), so we have to2160// leave dbg.declares with non-empty expressions in place.2161if (Declare->getExpression()->getNumElements() != 0)2162return;2163if (!Declare->getAddress())2164return;2165if (AllocaInst *Alloca =2166dyn_cast<AllocaInst>(Declare->getAddress()->stripPointerCasts())) {2167// FIXME: Skip VLAs for now (let these variables use dbg.declares).2168if (!Alloca->isStaticAlloca())2169return;2170// Similarly, skip scalable vectors (use dbg.declares instead).2171if (auto Sz = Alloca->getAllocationSize(*DL); Sz && Sz->isScalable())2172return;2173DeclareList[Alloca].insert(Declare);2174Vars[Alloca].insert(VarRecord(Declare));2175}2176};2177for (auto &BB : F) {2178for (auto &I : BB) {2179for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {2180if (DVR.isDbgDeclare())2181ProcessDeclare(&DVR, DVRDeclares);2182}2183if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(&I))2184ProcessDeclare(DDI, DbgDeclares);2185}2186}21872188// FIXME: Locals can be backed by caller allocas (sret, byval).2189// Note: trackAssignments doesn't respect dbg.declare's IR positions (as it2190// doesn't "understand" dbg.declares). However, this doesn't appear to break2191// any rules given this description of dbg.declare from2192// llvm/docs/SourceLevelDebugging.rst:2193//2194// It is not control-dependent, meaning that if a call to llvm.dbg.declare2195// exists and has a valid location argument, that address is considered to2196// be the true home of the variable across its entire lifetime.2197trackAssignments(F.begin(), F.end(), Vars, *DL);21982199// Delete dbg.declares for variables now tracked with assignment tracking.2200auto DeleteSubsumedDeclare = [&](const auto &Markers, auto &Declares) {2201(void)Markers;2202for (auto *Declare : Declares) {2203// Assert that the alloca that Declare uses is now linked to a dbg.assign2204// describing the same variable (i.e. check that this dbg.declare has2205// been replaced by a dbg.assign). Use DebugVariableAggregate to Discard2206// the fragment part because trackAssignments may alter the2207// fragment. e.g. if the alloca is smaller than the variable, then2208// trackAssignments will create an alloca-sized fragment for the2209// dbg.assign.2210assert(llvm::any_of(Markers, [Declare](auto *Assign) {2211return DebugVariableAggregate(Assign) ==2212DebugVariableAggregate(Declare);2213}));2214// Delete Declare because the variable location is now tracked using2215// assignment tracking.2216Declare->eraseFromParent();2217Changed = true;2218}2219};2220for (auto &P : DbgDeclares)2221DeleteSubsumedDeclare(at::getAssignmentMarkers(P.first), P.second);2222for (auto &P : DVRDeclares)2223DeleteSubsumedDeclare(at::getDVRAssignmentMarkers(P.first), P.second);2224return Changed;2225}22262227static const char *AssignmentTrackingModuleFlag =2228"debug-info-assignment-tracking";22292230static void setAssignmentTrackingModuleFlag(Module &M) {2231M.setModuleFlag(Module::ModFlagBehavior::Max, AssignmentTrackingModuleFlag,2232ConstantAsMetadata::get(2233ConstantInt::get(Type::getInt1Ty(M.getContext()), 1)));2234}22352236static bool getAssignmentTrackingModuleFlag(const Module &M) {2237Metadata *Value = M.getModuleFlag(AssignmentTrackingModuleFlag);2238return Value && !cast<ConstantAsMetadata>(Value)->getValue()->isZeroValue();2239}22402241bool llvm::isAssignmentTrackingEnabled(const Module &M) {2242return getAssignmentTrackingModuleFlag(M);2243}22442245PreservedAnalyses AssignmentTrackingPass::run(Function &F,2246FunctionAnalysisManager &AM) {2247if (!runOnFunction(F))2248return PreservedAnalyses::all();22492250// Record that this module uses assignment tracking. It doesn't matter that2251// some functons in the module may not use it - the debug info in those2252// functions will still be handled properly.2253setAssignmentTrackingModuleFlag(*F.getParent());22542255// Q: Can we return a less conservative set than just CFGAnalyses? Can we2256// return PreservedAnalyses::all()?2257PreservedAnalyses PA;2258PA.preserveSet<CFGAnalyses>();2259return PA;2260}22612262PreservedAnalyses AssignmentTrackingPass::run(Module &M,2263ModuleAnalysisManager &AM) {2264bool Changed = false;2265for (auto &F : M)2266Changed |= runOnFunction(F);22672268if (!Changed)2269return PreservedAnalyses::all();22702271// Record that this module uses assignment tracking.2272setAssignmentTrackingModuleFlag(M);22732274// Q: Can we return a less conservative set than just CFGAnalyses? Can we2275// return PreservedAnalyses::all()?2276PreservedAnalyses PA;2277PA.preserveSet<CFGAnalyses>();2278return PA;2279}22802281#undef DEBUG_TYPE228222832284