1//===- DebugInfo.cpp - Debug Information Helper Classes -------------------===// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 7//===----------------------------------------------------------------------===// 9// This file implements the helper classes used to build and interpret debug 10// information in LLVM IR form. 12//===----------------------------------------------------------------------===// 48// This function is hot. Check whether the value has any metadata to avoid a 49// DenseMap lookup. This check is a bitfield datamember lookup. 50if (!V->isUsedByMetadata())
60for (
User *U : MDV->users())
61if (
auto *DDI = dyn_cast<DbgDeclareInst>(U))
67// This function is hot. Check whether the value has any metadata to avoid a 68// DenseMap lookup. This check is a bitfield datamember lookup. 69if (!V->isUsedByMetadata())
77if (DVR->getType() == DbgVariableRecord::LocationType::Declare)
84// This function is hot. Check whether the value has any metadata to avoid a 85// DenseMap lookup. This check is a bitfield datamember lookup. 86if (!V->isUsedByMetadata())
94if (DVR->isValueOfVariable())
100template <
typename IntrinsicT,
bool DbgAssignAndValuesOnly>
104// This function is hot. Check whether the value has any metadata to avoid a 106if (!V->isUsedByMetadata())
110// TODO: If this value appears multiple times in a DIArgList, we should still 111// only add the owning DbgValueInst once; use this set to track ArgListUsers. 112// This behaviour can be removed when we can automatically remove duplicates. 113// V will also appear twice in a dbg.assign if its used in the both the value 114// and address components. 118 /// Append IntrinsicT users of MetadataAsValue(MD). 119auto AppendUsers = [&Ctx, &EncounteredIntrinsics,
120 &EncounteredDbgVariableRecords, &Result,
123for (
User *U : MDV->users())
124if (IntrinsicT *DVI = dyn_cast<IntrinsicT>(U))
125if (EncounteredIntrinsics.
insert(DVI).second)
126 Result.push_back(DVI);
128if (!DbgVariableRecords)
130// Get DbgVariableRecords that use this as a single value. 133if (!DbgAssignAndValuesOnly || DVR->isDbgValue() || DVR->isDbgAssign())
134if (EncounteredDbgVariableRecords.
insert(DVR).second)
142for (
Metadata *AL : L->getAllArgListUsers()) {
144if (!DbgVariableRecords)
148if (!DbgAssignAndValuesOnly || DVR->isDbgValue() || DVR->isDbgAssign())
149if (EncounteredDbgVariableRecords.
insert(DVR).second)
159 DbgValues, V, DbgVariableRecords);
166 DbgUsers, V, DbgVariableRecords);
170if (
auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
176// Original dbg.declare must have a location. 180// Because no machine insts can come from debug intrinsics, only the scope 181// and inlinedAt is significant. Zero line numbers are used in case this 182// DebugLoc leaks into any adjacent instructions. Produce an unknown location 183// with the correct scope / inlinedAt fields. 184return DILocation::get(DII->
getContext(), 0, 0, Scope, InlinedAt);
188// Original dbg.declare must have a location. 192// Because no machine insts can come from debug intrinsics, only the scope 193// and inlinedAt is significant. Zero line numbers are used in case this 194// DebugLoc leaks into any adjacent instructions. Produce an unknown location 195// with the correct scope / inlinedAt fields. 196return DILocation::get(DVR->
getContext(), 0, 0, Scope, InlinedAt);
199//===----------------------------------------------------------------------===// 200// DebugInfoFinder implementations. 201//===----------------------------------------------------------------------===// 213for (
auto *
CU : M.debug_compile_units())
214 processCompileUnit(
CU);
215for (
auto &
F : M.functions()) {
216if (
auto *SP = cast_or_null<DISubprogram>(
F.getSubprogram()))
218// There could be subprograms from inlined functions referenced from 219// instructions only. Walk the function to find them. 227if (!addCompileUnit(
CU))
229for (
auto *DIG :
CU->getGlobalVariables()) {
230if (!addGlobalVariable(DIG))
232auto *GV = DIG->getVariable();
233 processScope(GV->getScope());
234 processType(GV->getType());
236for (
auto *ET :
CU->getEnumTypes())
238for (
auto *RT :
CU->getRetainedTypes())
239if (
auto *
T = dyn_cast<DIType>(RT))
243for (
auto *
Import :
CU->getImportedEntities()) {
244auto *Entity =
Import->getEntity();
245if (
auto *
T = dyn_cast<DIType>(Entity))
247elseif (
auto *SP = dyn_cast<DISubprogram>(Entity))
249elseif (
auto *NS = dyn_cast<DINamespace>(Entity))
250 processScope(NS->getScope());
251elseif (
auto *M = dyn_cast<DIModule>(Entity))
252 processScope(M->getScope());
258if (
auto *DVI = dyn_cast<DbgVariableIntrinsic>(&
I))
261if (
auto DbgLoc =
I.getDebugLoc())
264for (
constDbgRecord &DPR :
I.getDbgRecordRange())
271 processScope(Loc->getScope());
281void DebugInfoFinder::processType(
DIType *DT) {
284 processScope(DT->getScope());
285if (
auto *ST = dyn_cast<DISubroutineType>(DT)) {
290if (
auto *DCT = dyn_cast<DICompositeType>(DT)) {
291 processType(DCT->getBaseType());
293if (
auto *
T = dyn_cast<DIType>(
D))
295elseif (
auto *SP = dyn_cast<DISubprogram>(
D))
300if (
auto *DDT = dyn_cast<DIDerivedType>(DT)) {
301 processType(DDT->getBaseType());
305void DebugInfoFinder::processScope(
DIScope *Scope) {
308if (
auto *Ty = dyn_cast<DIType>(Scope)) {
312if (
auto *
CU = dyn_cast<DICompileUnit>(Scope)) {
316if (
auto *SP = dyn_cast<DISubprogram>(Scope)) {
322if (
auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
323 processScope(LB->getScope());
324 }
elseif (
auto *NS = dyn_cast<DINamespace>(Scope)) {
325 processScope(NS->getScope());
326 }
elseif (
auto *M = dyn_cast<DIModule>(Scope)) {
327 processScope(
M->getScope());
332if (!addSubprogram(SP))
335// Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a 336// ValueMap containing identity mappings for all of the DICompileUnit's, not 337// just DISubprogram's, referenced from anywhere within the Function being 338// cloned prior to calling MapMetadata / RemapInstruction to avoid their 339// duplication later as DICompileUnit's are also directly referenced by 340// llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well. 341// Also, DICompileUnit's may reference DISubprogram's too and therefore need 342// to be at least looked through. 343 processCompileUnit(SP->getUnit());
344 processType(SP->getType());
345for (
auto *Element : SP->getTemplateParams()) {
346if (
auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
347 processType(TType->getType());
348 }
elseif (
auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
349 processType(TVal->getType());
356if (!NodesSeen.insert(DV).second)
362bool DebugInfoFinder::addType(
DIType *DT) {
366if (!NodesSeen.insert(DT).second)
369 TYs.push_back(
const_cast<DIType *
>(DT));
376if (!NodesSeen.insert(
CU).second)
384if (!NodesSeen.insert(DIG).second)
395if (!NodesSeen.insert(SP).second)
402bool DebugInfoFinder::addScope(
DIScope *Scope) {
405// FIXME: Ocaml binding generates a scope with no content, we treat it 407if (
Scope->getNumOperands() == 0)
409if (!NodesSeen.insert(Scope).second)
411 Scopes.push_back(Scope);
418"Loop ID needs at least one operand");
420"Loop ID should refer to itself");
422// Save space for the self-referential LoopID. 429elseif (
Metadata *NewMD = Updater(MD))
434// Insert the self-referential LoopID. 441MDNode *OrigLoopID =
I.getMetadata(LLVMContext::MD_loop);
445I.setMetadata(LLVMContext::MD_loop, NewLoopID);
448/// Return true if a node is a DILocation or if a DILocation is 449/// indirectly referenced by one of the node's children. 453MDNode *
N = dyn_cast_or_null<MDNode>(MD);
456if (isa<DILocation>(
N) || Reachable.
count(
N))
460for (
auto &OpIt :
N->operands()) {
463// Don't return just yet as we want to visit all MD's children to 464// initialize DILocationReachable in stripDebugLocFromLoopID 475MDNode *
N = dyn_cast_or_null<MDNode>(MD);
478if (isa<DILocation>(
N) || AllDILocation.
count(
N))
484for (
auto &OpIt :
N->operands()) {
499if (isa<DILocation>(MD) || AllDILocation.
count(MD))
502if (!DIReachable.
count(MD))
505MDNode *
N = dyn_cast_or_null<MDNode>(MD);
510bool HasSelfRef =
false;
511for (
unsigned i = 0; i <
N->getNumOperands(); ++i) {
514 Args.push_back(
nullptr);
516assert(i == 0 &&
"expected i==0 for self-reference");
518 Args.push_back(
nullptr);
521 Args.push_back(NewArg);
524if (Args.empty() || (HasSelfRef && Args.size() == 1))
535assert(!
N->operands().empty() &&
"Missing self reference?");
537// If we already visited N, there is nothing to do. 541// If there is no debug location, we do not have to rewrite this 542// MDNode. This loop also initializes DILocationReachable, later 543// needed by updateLoopMetadataDebugLocationsImpl; the use of 544// count_if avoids an early exit. 546 [&Visited, &DILocationReachable](
constMDOperand &
Op) {
547 return isDILocationReachable(
548 Visited, DILocationReachable, Op.get());
553// If there is only the debug location without any actual loop metadata, we 554// can remove the metadata. 556 [&Visited, &AllDILocation,
558 return isAllDILocation(Visited, AllDILocation,
559 DILocationReachable, Op.get());
571if (
F.hasMetadata(LLVMContext::MD_dbg)) {
573F.setSubprogram(
nullptr);
579if (isa<DbgInfoIntrinsic>(&
I)) {
584if (
I.getDebugLoc()) {
588if (
auto *LoopID =
I.getMetadata(LLVMContext::MD_loop)) {
589auto *NewLoopID = LoopIDsMap.
lookup(LoopID);
592if (NewLoopID != LoopID)
593I.setMetadata(LLVMContext::MD_loop, NewLoopID);
595// Strip other attachments that are or use debug info. 596if (
I.hasMetadataOtherThanDebugLoc()) {
597// Heapallocsites point into the DIType system. 598I.setMetadata(
"heapallocsite",
nullptr);
599// DIAssignID are debug info metadata primitives. 600I.setMetadata(LLVMContext::MD_DIAssignID,
nullptr);
612// We're stripping debug info, and without them, coverage information 613// doesn't quite make sense. 614if (NMD.getName().starts_with(
"llvm.dbg.") ||
615 NMD.getName() ==
"llvm.gcov") {
616 NMD.eraseFromParent();
624for (
auto &GV : M.globals()) {
625 Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);
629 Materializer->setStripDebugInfo();
636/// Helper class to downgrade -g metadata to -gline-tables-only metadata. 637classDebugTypeInfoRemoval {
641 /// The (void)() type. 642MDNode *EmptySubroutineType;
645 /// Remember what linkage name we originally had before stripping. If we end 646 /// up making two subprograms identical who originally had different linkage 647 /// names, then we need to make one of them distinct, to avoid them getting 648 /// uniqued. Maps the new node to the old linkage name. 651// TODO: Remember the distinct subprogram we created for a given linkage name, 652// so that we can continue to unique whenever possible. Map <newly created 653// node, old linkage name> to the first (possibly distinct) mdsubprogram 654// created for that combination. This is not strictly needed for correctness, 655// but can cut down on the number of MDNodes and let us diff cleanly with the 656// output of -gline-tables-only. 666auto Replacement = Replacements.find(M);
667if (Replacement != Replacements.end())
668return Replacement->second;
674 /// Recursively remap N and all its referenced children. Does a DF post-order 675 /// traversal, so as to remap bottoms up. 676void traverseAndRemap(
MDNode *
N) { traverse(
N); }
679// Create a new DISubprogram, to replace the one given. 681auto *FileAndScope = cast_or_null<DIFile>(map(MDS->
getFile()));
684auto *
Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
686 cast_or_null<DIType>(map(MDS->getContainingType()));
687auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
688auto Variables =
nullptr;
689auto TemplateParams =
nullptr;
691// Make a distinct DISubprogram, for situations that warrent it. 692auto distinctMDSubprogram = [&]() {
693return DISubprogram::getDistinct(
695 FileAndScope, MDS->getLine(),
Type, MDS->getScopeLine(),
696 ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),
697 MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,
702return distinctMDSubprogram();
704auto *NewMDS = DISubprogram::get(
706 FileAndScope, MDS->getLine(),
Type, MDS->getScopeLine(), ContainingType,
707 MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),
708 MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);
710StringRef OldLinkageName = MDS->getLinkageName();
712// See if we need to make a distinct one. 713auto OrigLinkage = NewToLinkageName.find(NewMDS);
714if (OrigLinkage != NewToLinkageName.end()) {
715if (OrigLinkage->second == OldLinkageName)
719// Otherwise, need to make a distinct one. 720// TODO: Query the map to see if we already have one. 721return distinctMDSubprogram();
724 NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
728 /// Create a new compile unit, to replace the one given 734auto *
File = cast_or_null<DIFile>(map(
CU->getFile()));
736MDTuple *RetainedTypes =
nullptr;
737MDTuple *GlobalVariables =
nullptr;
738MDTuple *ImportedEntities =
nullptr;
739return DICompileUnit::getDistinct(
740CU->getContext(),
CU->getSourceLanguage(), File,
CU->getProducer(),
741CU->isOptimized(),
CU->getFlags(),
CU->getRuntimeVersion(),
743 RetainedTypes, GlobalVariables, ImportedEntities,
CU->getMacros(),
744CU->getDWOId(),
CU->getSplitDebugInlining(),
745CU->getDebugInfoForProfiling(),
CU->getNameTableKind(),
746CU->getRangesBaseAddress(),
CU->getSysRoot(),
CU->getSDK());
750auto *
Scope = map(MLD->getScope());
751auto *InlinedAt = map(MLD->getInlinedAt());
753return DILocation::getDistinct(MLD->
getContext(), MLD->getLine(),
754 MLD->getColumn(), Scope, InlinedAt);
755return DILocation::get(MLD->
getContext(), MLD->getLine(), MLD->getColumn(),
759 /// Create a new generic MDNode, to replace the one given 763for (
auto &
I :
N->operands())
770 /// Attempt to re-map N to a newly created node. 772if (Replacements.count(
N))
778if (
auto *MDSub = dyn_cast<DISubprogram>(
N)) {
779 remap(MDSub->getUnit());
780return getReplacementSubprogram(MDSub);
782if (isa<DISubroutineType>(
N))
783return EmptySubroutineType;
784if (
auto *
CU = dyn_cast<DICompileUnit>(
N))
785return getReplacementCU(
CU);
788if (
auto *MDLB = dyn_cast<DILexicalBlockBase>(
N))
789// Remap to our referenced scope (recursively). 790return mapNode(MDLB->getScope());
791if (
auto *MLD = dyn_cast<DILocation>(
N))
792return getReplacementMDLocation(MLD);
794// Otherwise, if we see these, just drop them now. Not strictly necessary, 795// but this speeds things up a little. 799return getReplacementMDNode(
N);
801 Replacements[
N] = doRemap(
N);
804 /// Do the remapping traversal. 808}
// end anonymous namespace 810void DebugTypeInfoRemoval::traverse(
MDNode *
N) {
811if (!
N || Replacements.count(
N))
814// To avoid cycles, as well as for efficiency sake, we will sometimes prune 815// parts of the graph. 817if (
auto *MDS = dyn_cast<DISubprogram>(Parent))
818return Child == MDS->getRetainedNodes().
get();
825// Visit each node starting at N in post order, and map them. 827while (!ToVisit.
empty()) {
828auto *
N = ToVisit.
back();
835for (
auto &
I :
N->operands())
836if (
auto *MDN = dyn_cast_or_null<MDNode>(
I))
837if (!Opened.
count(MDN) && !Replacements.count(MDN) && !
prune(
N, MDN) &&
838 !isa<DICompileUnit>(MDN))
846// First off, delete the debug intrinsics. 848if (
auto *DbgVal = M.getFunction(
Name)) {
849while (!DbgVal->use_empty())
850 cast<Instruction>(DbgVal->user_back())->eraseFromParent();
851 DbgVal->eraseFromParent();
855 RemoveUses(
"llvm.dbg.declare");
856 RemoveUses(
"llvm.dbg.label");
857 RemoveUses(
"llvm.dbg.value");
859// Delete non-CU debug info named metadata nodes. 860for (
auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
864// Specifically keep dbg.cu around. 865if (NMD->
getName() ==
"llvm.dbg.cu")
869// Drop all dbg attachments from global variables. 870for (
auto &GV : M.globals())
871 GV.eraseMetadata(LLVMContext::MD_dbg);
873 DebugTypeInfoRemoval Mapper(M.getContext());
877 Mapper.traverseAndRemap(Node);
878auto *NewNode = Mapper.mapNode(Node);
879 Changed |= Node != NewNode;
884// Rewrite the DebugLocs to be equivalent to what 885// -gline-tables-only would have created. 887if (
auto *SP =
F.getSubprogram()) {
888 Mapper.traverseAndRemap(SP);
889auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
890 Changed |= SP != NewSP;
891F.setSubprogram(NewSP);
896auto *Scope =
DL.getScope();
897MDNode *InlinedAt =
DL.getInlinedAt();
898 Scope = remap(Scope);
899 InlinedAt = remap(InlinedAt);
905I.setDebugLoc(remapDebugLoc(
I.getDebugLoc()));
907// Remap DILocations in llvm.loop attachments. 909if (
auto *Loc = dyn_cast_or_null<DILocation>(MD))
910return remapDebugLoc(Loc).
get();
914// Strip heapallocsite attachments, they point into the DIType system. 915if (
I.hasMetadataOtherThanDebugLoc())
916I.setMetadata(
"heapallocsite",
nullptr);
918// Strip any DbgRecords attached. 924// Create a new llvm.dbg.cu, which is equivalent to the one 925// -gline-tables-only would have created. 926for (
auto &NMD : M.named_metadata()) {
943if (
auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
944 M.getModuleFlag(
"Debug Info Version")))
945return Val->getZExtValue();
955// Replace all uses (and attachments) of all the DIAssignIDs 956// on SourceInstructions with a single merged value. 958// Collect up the DIAssignID tags. 961if (
auto *MD =
I->getMetadata(LLVMContext::MD_DIAssignID))
964"Merging with instruction from another function not allowed");
967// Add this instruction's DIAssignID too, if it has one. 968if (
auto *MD =
getMetadata(LLVMContext::MD_DIAssignID))
972return;
// No DIAssignID tags to process. 975for (
auto It = std::next(IDs.
begin()),
End = IDs.
end(); It !=
End; ++It) {
989// If this isn't a call, drop the location to allow a location from a 990// preceding instruction to propagate. 991bool MayLowerToCall =
false;
992if (isa<CallBase>(
this)) {
993auto *
II = dyn_cast<IntrinsicInst>(
this);
998if (!MayLowerToCall) {
1003// Set a line 0 location for calls to preserve scope information in case 1007// If a function scope is available, set it on the line 0 location. When 1008// hoisting a call to a predecessor block, using the function scope avoids 1009// making it look like the callee was reached earlier than it should be. 1012// The parent function has no scope. Go ahead and drop the location. If 1013// the parent function is inlined, and the callee has a subprogram, the 1014// inliner will attach a location to the call. 1016// One alternative is to set a line 0 location with the existing scope and 1017// inlinedAt info. The location might be sensitive to when inlining occurs. 1021//===----------------------------------------------------------------------===// 1022// LLVM C API implementations. 1023//===----------------------------------------------------------------------===// 1027#define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR) \ 1028 case LLVMDWARFSourceLanguage##NAME: \ 1030#include "llvm/BinaryFormat/Dwarf.def" 1031#undef HANDLE_DW_LANG 1037return (DIT *)(
Ref ? unwrap<MDNode>(
Ref) :
nullptr);
1078unwrap(Builder)->finalize();
1083unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram));
1089LLVMBool isOptimized,
constchar *Flags,
size_t FlagsLen,
1090unsigned RuntimeVer,
constchar *SplitName,
size_t SplitNameLen,
1092LLVMBool DebugInfoForProfiling,
constchar *SysRoot,
size_t SysRootLen,
1093constchar *SDK,
size_t SDKLen) {
1094auto File = unwrapDI<DIFile>(FileRef);
1096returnwrap(
unwrap(Builder)->createCompileUnit(
1099 RuntimeVer,
StringRef(SplitName, SplitNameLen),
1101 SplitDebugInlining, DebugInfoForProfiling,
1108size_t FilenameLen,
constchar *Directory,
1109size_t DirectoryLen) {
1116constchar *
Name,
size_t NameLen,
1117constchar *ConfigMacros,
size_t ConfigMacrosLen,
1118constchar *IncludePath,
size_t IncludePathLen,
1119constchar *APINotesFile,
size_t APINotesFileLen) {
1122StringRef(ConfigMacros, ConfigMacrosLen),
1124StringRef(APINotesFile, APINotesFileLen)));
1129constchar *
Name,
size_t NameLen,
1132 unwrapDI<DIScope>(ParentScope),
StringRef(
Name, NameLen), ExportSymbols));
1137size_t NameLen,
constchar *
LinkageName,
size_t LinkageNameLen,
1142 unwrapDI<DIScope>(Scope), {
Name, NameLen}, {
LinkageName, LinkageNameLen},
1143 unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,
1153returnwrap(
unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
1154 unwrapDI<DIFile>(File),
1162unsigned Discriminator) {
1163returnwrap(
unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
1164 unwrapDI<DIFile>(File),
1175 unwrapDI<DINamespace>(NS),
1176 unwrapDI<DIFile>(File),
1186 ?
unwrap(Builder)->getOrCreateArray({
unwrap(Elements), NumElements})
1189 unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity),
1190 unwrapDI<DIFile>(File), Line, Elts));
1196unsigned NumElements) {
1199 ?
unwrap(Builder)->getOrCreateArray({
unwrap(Elements), NumElements})
1202 unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File),
1212 ?
unwrap(Builder)->getOrCreateArray({
unwrap(Elements), NumElements})
1214returnwrap(
unwrap(Builder)->createImportedDeclaration(
1215 unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File),
1216 Line, {
Name, NameLen}, Elts));
1228return unwrapDI<DILocation>(Location)->getLine();
1232return unwrapDI<DILocation>(Location)->getColumn();
1236returnwrap(unwrapDI<DILocation>(Location)->getScope());
1240returnwrap(unwrapDI<DILocation>(Location)->getInlinedAt());
1244returnwrap(unwrapDI<DIScope>(Scope)->getFile());
1248auto Dir = unwrapDI<DIFile>(File)->getDirectory();
1254autoName = unwrapDI<DIFile>(File)->getFilename();
1260if (
auto Src = unwrapDI<DIFile>(File)->getSource()) {
1272constchar *
Name,
size_t NameLen,
1273constchar *
Value,
size_t ValueLen) {
1275unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,
1284returnwrap(
unwrap(Builder)->createTempMacroFile(
1285 unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));
1289constchar *
Name,
size_t NameLen,
1301auto Elts =
unwrap(Builder)->getOrCreateArray({
unwrap(Elements),
1303returnwrap(
unwrap(Builder)->createEnumerationType(
1304 unwrapDI<DIScope>(Scope), {
Name, NameLen}, unwrapDI<DIFile>(File),
1305 LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
1313constchar *UniqueId,
size_t UniqueIdLen) {
1314auto Elts =
unwrap(Builder)->getOrCreateArray({
unwrap(Elements),
1317 unwrapDI<DIScope>(Scope), {
Name, NameLen}, unwrapDI<DIFile>(File),
1319 Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
1327unsigned NumSubscripts) {
1328auto Subs =
unwrap(Builder)->getOrCreateArray({
unwrap(Subscripts),
1331 unwrapDI<DIType>(Ty), Subs));
1338unsigned NumSubscripts) {
1339auto Subs =
unwrap(Builder)->getOrCreateArray({
unwrap(Subscripts),
1342 unwrapDI<DIType>(Ty), Subs));
1351 SizeInBits, Encoding,
1358constchar *
Name,
size_t NameLen) {
1359returnwrap(
unwrap(Builder)->createPointerType(
1360 unwrapDI<DIType>(PointeeTy), SizeInBits, AlignInBits,
AddressSpace,
1369unsigned NumElements,
unsigned RunTimeLang,
LLVMMetadataRef VTableHolder,
1370constchar *UniqueId,
size_t UniqueIdLen) {
1371auto Elts =
unwrap(Builder)->getOrCreateArray({
unwrap(Elements),
1374 unwrapDI<DIScope>(Scope), {
Name, NameLen}, unwrapDI<DIFile>(File),
1376 unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
1377 unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
1385returnwrap(
unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
1386 {
Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
1393returnwrap(
unwrap(Builder)->createUnspecifiedType({
Name, NameLen}));
1401returnwrap(
unwrap(Builder)->createStaticMemberType(
1402 unwrapDI<DIScope>(Scope), {
Name, NameLen}, unwrapDI<DIFile>(File),
1404 unwrap<Constant>(ConstantVal), DW_TAG_member, AlignInBits));
1409constchar *
Name,
size_t NameLen,
1415 {
Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1416 SizeInBits, AlignInBits, OffsetInBits,
1418 unwrapDI<MDNode>(PropertyNode)));
1423constchar *
Name,
size_t NameLen,
1425constchar *GetterName,
size_t GetterNameLen,
1426constchar *SetterName,
size_t SetterNameLen,
1427unsigned PropertyAttributes,
1429returnwrap(
unwrap(Builder)->createObjCProperty(
1430 {
Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1431 {GetterName, GetterNameLen}, {SetterName, SetterNameLen},
1432 PropertyAttributes, unwrapDI<DIType>(Ty)));
1438returnwrap(
unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(
Type),
1444constchar *
Name,
size_t NameLen,
1448 unwrapDI<DIType>(
Type), {
Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1449 unwrapDI<DIScope>(Scope), AlignInBits));
1457returnwrap(
unwrap(Builder)->createInheritance(
1458 unwrapDI<DIType>(Ty), unwrapDI<DIType>(
BaseTy),
1467constchar *UniqueIdentifier,
size_t UniqueIdentifierLen) {
1468returnwrap(
unwrap(Builder)->createForwardDecl(
1469Tag, {
Name, NameLen}, unwrapDI<DIScope>(Scope),
1470 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1471 AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));
1480size_t UniqueIdentifierLen) {
1481returnwrap(
unwrap(Builder)->createReplaceableCompositeType(
1482Tag, {
Name, NameLen}, unwrapDI<DIScope>(Scope),
1483 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1485 {UniqueIdentifier, UniqueIdentifierLen}));
1492 unwrapDI<DIType>(
Type)));
1499 unwrapDI<DIType>(
Type)));
1504returnwrap(
unwrap(Builder)->createNullPtrType());
1514returnwrap(
unwrap(Builder)->createMemberPointerType(
1515 unwrapDI<DIType>(PointeeType),
1516 unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
1523constchar *
Name,
size_t NameLen,
1529returnwrap(
unwrap(Builder)->createBitFieldMemberType(
1530 unwrapDI<DIScope>(Scope), {
Name, NameLen},
1531 unwrapDI<DIFile>(File), LineNumber,
1532 SizeInBits, OffsetInBits, StorageOffsetInBits,
1543constchar *UniqueIdentifier,
size_t UniqueIdentifierLen) {
1544auto Elts =
unwrap(Builder)->getOrCreateArray({
unwrap(Elements),
1547 unwrapDI<DIScope>(Scope), {
Name, NameLen}, unwrapDI<DIFile>(File),
1548 LineNumber, SizeInBits, AlignInBits, OffsetInBits,
1550/*RunTimeLang=*/0, unwrapDI<DIType>(VTableHolder),
1551 unwrapDI<MDNode>(TemplateParamsNode),
1552 {UniqueIdentifier, UniqueIdentifierLen}));
1558returnwrap(
unwrap(Builder)->createArtificialType(unwrapDI<DIType>(
Type)));
1562return unwrapDI<DINode>(MD)->getTag();
1566StringRef Str = unwrapDI<DIType>(DType)->getName();
1572return unwrapDI<DIType>(DType)->getSizeInBits();
1576return unwrapDI<DIType>(DType)->getOffsetInBits();
1580return unwrapDI<DIType>(DType)->getAlignInBits();
1584return unwrapDI<DIType>(DType)->getLine();
1602unsigned NumParameterTypes,
1604auto Elts =
unwrap(Builder)->getOrCreateTypeArray({
unwrap(ParameterTypes),
1605 NumParameterTypes});
1606returnwrap(
unwrap(Builder)->createSubroutineType(
1627returnwrap(
unwrap(Builder)->createGlobalVariableExpression(
1628 unwrapDI<DIScope>(Scope), {
Name, NameLen}, {Linkage, LinkLen},
1629 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1630true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),
1631nullptr, AlignInBits));
1635returnwrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());
1640returnwrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());
1644returnwrap(unwrapDI<DIVariable>(Var)->getFile());
1648returnwrap(unwrapDI<DIVariable>(Var)->getScope());
1652return unwrapDI<DIVariable>(Var)->getLine();
1667auto *
Node = unwrapDI<MDNode>(TargetMetadata);
1668Node->replaceAllUsesWith(
unwrap(Replacement));
1677returnwrap(
unwrap(Builder)->createTempGlobalVariableFwdDecl(
1678 unwrapDI<DIScope>(Scope), {
Name, NameLen}, {Linkage, LnkLen},
1679 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1680 unwrapDI<MDNode>(Decl),
nullptr, AlignInBits));
1687unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1688 unwrap<DIExpression>(Expr), unwrap<DILocation>(
DL),
1689 unwrap<Instruction>(Instr));
1690// This assert will fail if the module is in the old debug info format. 1691// This function should only be called if the module is in the new 1692// debug info format. 1693// See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1694// LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1695assert(isa<DbgRecord *>(DbgInst) &&
1696"Function unexpectedly in old debug info format");
1697returnwrap(cast<DbgRecord *>(DbgInst));
1704unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1705 unwrap<DIExpression>(Expr), unwrap<DILocation>(
DL),
unwrap(
Block));
1706// This assert will fail if the module is in the old debug info format. 1707// This function should only be called if the module is in the new 1708// debug info format. 1709// See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1710// LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1711assert(isa<DbgRecord *>(DbgInst) &&
1712"Function unexpectedly in old debug info format");
1713returnwrap(cast<DbgRecord *>(DbgInst));
1720unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),
1721 unwrap<DILocation>(
DebugLoc), unwrap<Instruction>(Instr));
1722// This assert will fail if the module is in the old debug info format. 1723// This function should only be called if the module is in the new 1724// debug info format. 1725// See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1726// LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1727assert(isa<DbgRecord *>(DbgInst) &&
1728"Function unexpectedly in old debug info format");
1729returnwrap(cast<DbgRecord *>(DbgInst));
1736unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),
1738// This assert will fail if the module is in the old debug info format. 1739// This function should only be called if the module is in the new 1740// debug info format. 1741// See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1742// LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1743assert(isa<DbgRecord *>(DbgInst) &&
1744"Function unexpectedly in old debug info format");
1745returnwrap(cast<DbgRecord *>(DbgInst));
1752returnwrap(
unwrap(Builder)->createAutoVariable(
1753 unwrap<DIScope>(Scope), {
Name, NameLen}, unwrap<DIFile>(File),
1754 LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1762returnwrap(
unwrap(Builder)->createParameterVariable(
1763 unwrap<DIScope>(Scope), {
Name, NameLen}, ArgNo, unwrap<DIFile>(File),
1764 LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1769 int64_t
Lo, int64_t Count) {
1770returnwrap(
unwrap(Builder)->getOrCreateSubrange(
Lo, Count));
1785 unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
1789return unwrapDI<DISubprogram>(Subprogram)->getLine();
1798 unwrap<Instruction>(Inst)->setDebugLoc(
DebugLoc(unwrap<MDNode>(Loc)));
1800 unwrap<Instruction>(Inst)->setDebugLoc(
DebugLoc());
1809 unwrapDI<DIFile>(File), LineNo, AlwaysPreserve));
1816 unwrapDI<DILabel>(LabelInfo), unwrapDI<DILocation>(Location),
1817 unwrap<Instruction>(InsertBefore));
1818// This assert will fail if the module is in the old debug info format. 1819// This function should only be called if the module is in the new 1820// debug info format. 1821// See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1822// LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1823assert(isa<DbgRecord *>(DbgInst) &&
1824"Function unexpectedly in old debug info format");
1825returnwrap(cast<DbgRecord *>(DbgInst));
1832 unwrapDI<DILabel>(LabelInfo), unwrapDI<DILocation>(Location),
1834// This assert will fail if the module is in the old debug info format. 1835// This function should only be called if the module is in the new 1836// debug info format. 1837// See https://llvm.org/docs/RemoveDIsDebugInfo.html#c-api-changes, 1838// LLVMIsNewDbgInfoFormat, and LLVMSetIsNewDbgInfoFormat for more info. 1839assert(isa<DbgRecord *>(DbgInst) &&
1840"Function unexpectedly in old debug info format");
1841returnwrap(cast<DbgRecord *>(DbgInst));
1846#define HANDLE_METADATA_LEAF(CLASS) \ 1847 case Metadata::CLASS##Kind: \ 1848 return (LLVMMetadataKind)LLVM##CLASS##MetadataKind; 1849#include "llvm/IR/Metadata.def" 1856assert(
ID &&
"Expected non-null ID");
1860auto MapIt = Map.find(
ID);
1861if (MapIt == Map.end())
1864returnmake_range(MapIt->second.begin(), MapIt->second.end());
1868assert(
ID &&
"Expected non-null ID");
1873// The ID is only used wrapped in MetadataAsValue(ID), so lets check that 1874// one of those already exists first. 1878returnmake_range(IDAsValue->user_begin(), IDAsValue->user_end());
1887for (
auto *DAI : ToDelete)
1888 DAI->eraseFromParent();
1889for (
auto *DVR : DVRAssigns)
1890 DVR->eraseFromParent();
1894// Replace attachments. 1896// Use intermediate storage for the instruction ptrs because the 1897// getAssignmentInsts range iterators will be invalidated by adding and 1898// removing DIAssignID attachments. 1900for (
auto *
I : InstVec)
1901I->setMetadata(LLVMContext::MD_DIAssignID, New);
1912if (DVR.isDbgAssign())
1914if (
auto *DAI = dyn_cast<DbgAssignIntrinsic>(&
I))
1917I.setMetadata(LLVMContext::MD_DIAssignID,
nullptr);
1920for (
auto *DAI : ToDelete)
1921 DAI->eraseFromParent();
1922for (
auto *DVR : DPToDelete)
1923 DVR->eraseFromParent();
1926/// FIXME: Remove this wrapper function and call 1927/// DIExpression::calculateFragmentIntersect directly. 1928template <
typename T>
1931uint64_t SliceSizeInBits,
constT *AssignRecord,
1932 std::optional<DIExpression::FragmentInfo> &Result) {
1933// No overlap if this DbgRecord describes a killed location. 1934if (AssignRecord->isKillAddress())
1937 int64_t AddrOffsetInBits;
1939 int64_t AddrOffsetInBytes;
1941// Bail if we can't find a constant offset (or none) in the expression. 1942if (!AssignRecord->getAddressExpression()->extractLeadingOffset(
1943 AddrOffsetInBytes, PostOffsetOps))
1945 AddrOffsetInBits = AddrOffsetInBytes * 8;
1948Value *
Addr = AssignRecord->getAddress();
1949// FIXME: It may not always be zero. 1950 int64_t BitExtractOffsetInBits = 0;
1952 AssignRecord->getFragmentOrEntireVariable();
1954 int64_t OffsetFromLocationInBits;
//< Unused. 1956DL, Dest, SliceOffsetInBits, SliceSizeInBits,
Addr, AddrOffsetInBits,
1957 BitExtractOffsetInBits, VarFrag, Result, OffsetFromLocationInBits);
1960/// FIXME: Remove this wrapper function and call 1961/// DIExpression::calculateFragmentIntersect directly. 1965 std::optional<DIExpression::FragmentInfo> &Result) {
1967 SliceSizeInBits, DbgAssign, Result);
1970/// FIXME: Remove this wrapper function and call 1971/// DIExpression::calculateFragmentIntersect directly. 1975 std::optional<DIExpression::FragmentInfo> &Result) {
1977 SliceSizeInBits, DVRAssign, Result);
1980/// Update inlined instructions' DIAssignID metadata. We need to do this 1981/// otherwise a function inlined more than once into the same function 1982/// will cause DIAssignID to be shared by many instructions. 1985auto GetNewID = [&Map](
Metadata *Old) {
1993// If we find a DIAssignID attachment or use, replace it with a new version. 1995if (DVR.isDbgAssign())
1996 DVR.setAssignId(GetNewID(DVR.getAssignID()));
1998if (
auto *
ID =
I.getMetadata(LLVMContext::MD_DIAssignID))
1999I.setMetadata(LLVMContext::MD_DIAssignID, GetNewID(
ID));
2000elseif (
auto *DAI = dyn_cast<DbgAssignIntrinsic>(&
I))
2001 DAI->setAssignId(GetNewID(DAI->getAssignID()));
2004/// Collect constant properies (base, size, offset) of \p StoreDest. 2005/// Return std::nullopt if any properties are not constants or the 2006/// offset from the base pointer is negative. 2007static std::optional<AssignmentInfo>
2012APInt GEPOffset(
DL.getIndexTypeSizeInBits(StoreDest->
getType()), 0);
2014DL, GEPOffset,
/*AllowNonInbounds*/true);
2020// Check for overflow. 2023if (
constauto *Alloca = dyn_cast<AllocaInst>(
Base))
2030constValue *StoreDest =
I->getRawDest();
2031// Assume 8 bit bytes. 2032auto *ConstLengthInBytes = dyn_cast<ConstantInt>(
I->getLength());
2033if (!ConstLengthInBytes)
2034// We can't use a non-const size, bail. 2036uint64_t SizeInBits = 8 * ConstLengthInBytes->getZExtValue();
2042TypeSize SizeInBits =
DL.getTypeSizeInBits(SI->getValueOperand()->getType());
2052/// Returns nullptr if the assignment shouldn't be attributed to this variable. 2056auto *
ID = StoreLikeInst.
getMetadata(LLVMContext::MD_DIAssignID);
2057assert(
ID &&
"Store instruction must have DIAssignID metadata");
2063uint64_t FragStartBit = StoreStartBit;
2066bool StoreToWholeVariable =
Info.StoreToWholeAlloca;
2068// NOTE: trackAssignments doesn't understand base expressions yet, so all 2069// variables that reach here are guaranteed to start at offset 0 in the 2074// FIXME: trim FragStartBit when nonzero VarStartBit is supported. 2075 FragEndBit = std::min(FragEndBit, VarEndBit);
2077// Discard stores to bits outside this variable. 2078if (FragStartBit >= FragEndBit)
2081 StoreToWholeVariable = FragStartBit <= VarStartBit && FragEndBit >= *
Size;
2085if (!StoreToWholeVariable) {
2087 FragEndBit - FragStartBit);
2088assert(R.has_value() &&
"failed to create fragment expression");
2092if (StoreLikeInst.
getParent()->IsNewDbgInfoFormat) {
2094 &StoreLikeInst, Val, VarRec.
Var, Expr, Dest, AddrExpr, VarRec.
DL);
2100 AddrExpr, VarRec.
DL);
2103 if (const auto *Record = dyn_cast<DbgRecord *>(Assign))
2104 errs() <<
" > INSERT: " << *Record <<
"\n";
2106 errs() <<
" > INSERT: " << *cast<Instruction *>(Assign) <<
"\n";
2110#undef DEBUG_TYPE// Silence redefinition warning (from ConstantsContext.h). 2111#define DEBUG_TYPE "assignment-tracking" 2116// Early-exit if there are no interesting variables. 2120auto &Ctx = Start->getContext();
2121auto &
Module = *Start->getModule();
2123// Undef type doesn't matter, so long as it isn't void. Let's just use i1. 2127// Scan the instructions looking for stores to local variables' storage. 2129for (
auto BBI = Start; BBI !=
End; ++BBI) {
2132 std::optional<AssignmentInfo>
Info;
2133Value *ValueComponent =
nullptr;
2134Value *DestComponent =
nullptr;
2135if (
auto *AI = dyn_cast<AllocaInst>(&
I)) {
2136// We want to track the variable's stack home from its alloca's 2137// position onwards so we treat it as an assignment (where the stored 2140 ValueComponent = Undef;
2142 }
elseif (
auto *SI = dyn_cast<StoreInst>(&
I)) {
2144 ValueComponent = SI->getValueOperand();
2145 DestComponent = SI->getPointerOperand();
2146 }
elseif (
auto *
MI = dyn_cast<MemTransferInst>(&
I)) {
2148// May not be able to represent this value easily. 2149 ValueComponent = Undef;
2150 DestComponent =
MI->getOperand(0);
2151 }
elseif (
auto *
MI = dyn_cast<MemSetInst>(&
I)) {
2153// If we're zero-initing we can state the assigned value is zero, 2154// otherwise use undef. 2155auto *ConstValue = dyn_cast<ConstantInt>(
MI->getOperand(1));
2156if (ConstValue && ConstValue->isZero())
2157 ValueComponent = ConstValue;
2159 ValueComponent = Undef;
2160 DestComponent =
MI->getOperand(0);
2162// Not a store-like instruction. 2166assert(ValueComponent && DestComponent);
2169// Check if getAssignmentInfo failed to understand this store. 2170if (!
Info.has_value()) {
2173 <<
" | SKIP: Untrackable store (e.g. through non-const gep)\n");
2178// Check if the store destination is a local variable with debug info. 2179auto LocalIt = Vars.
find(
Info->Base);
2180if (LocalIt == Vars.
end()) {
2183 <<
" | SKIP: Base address not associated with local variable\n");
2188 cast_or_null<DIAssignID>(
I.getMetadata(LLVMContext::MD_DIAssignID));
2191I.setMetadata(LLVMContext::MD_DIAssignID,
ID);
2194for (
constVarRecord &R : LocalIt->second)
2200bool AssignmentTrackingPass::runOnFunction(
Function &
F) {
2201// No value in assignment tracking without optimisations. 2202if (
F.hasFnAttribute(Attribute::OptimizeNone))
2203return/*Changed*/false;
2206auto *
DL = &
F.getDataLayout();
2207// Collect a map of {backing storage : dbg.declares} (currently "backing 2208// storage" is limited to Allocas). We'll use this to find dbg.declares to 2209// delete after running `trackAssignments`. 2212// Create another similar map of {storage : variables} that we'll pass to 2215auto ProcessDeclare = [&](
auto *Declare,
auto &DeclareList) {
2216// FIXME: trackAssignments doesn't let you specify any modifiers to the 2217// variable (e.g. fragment) or location (e.g. offset), so we have to 2218// leave dbg.declares with non-empty expressions in place. 2219if (Declare->getExpression()->getNumElements() != 0)
2221if (!Declare->getAddress())
2224 dyn_cast<AllocaInst>(Declare->getAddress()->stripPointerCasts())) {
2225// FIXME: Skip VLAs for now (let these variables use dbg.declares). 2226if (!Alloca->isStaticAlloca())
2228// Similarly, skip scalable vectors (use dbg.declares instead). 2229if (
auto Sz = Alloca->getAllocationSize(*
DL); Sz && Sz->isScalable())
2231 DeclareList[Alloca].
insert(Declare);
2238if (DVR.isDbgDeclare())
2239 ProcessDeclare(&DVR, DVRDeclares);
2242 ProcessDeclare(DDI, DbgDeclares);
2246// FIXME: Locals can be backed by caller allocas (sret, byval). 2247// Note: trackAssignments doesn't respect dbg.declare's IR positions (as it 2248// doesn't "understand" dbg.declares). However, this doesn't appear to break 2249// any rules given this description of dbg.declare from 2250// llvm/docs/SourceLevelDebugging.rst: 2252// It is not control-dependent, meaning that if a call to llvm.dbg.declare 2253// exists and has a valid location argument, that address is considered to 2254// be the true home of the variable across its entire lifetime. 2257// Delete dbg.declares for variables now tracked with assignment tracking. 2258auto DeleteSubsumedDeclare = [&](
constauto &
Markers,
auto &Declares) {
2260for (
auto *Declare : Declares) {
2261// Assert that the alloca that Declare uses is now linked to a dbg.assign 2262// describing the same variable (i.e. check that this dbg.declare has 2263// been replaced by a dbg.assign). Use DebugVariableAggregate to Discard 2264// the fragment part because trackAssignments may alter the 2265// fragment. e.g. if the alloca is smaller than the variable, then 2266// trackAssignments will create an alloca-sized fragment for the 2272// Delete Declare because the variable location is now tracked using 2273// assignment tracking. 2274 Declare->eraseFromParent();
2278for (
auto &
P : DbgDeclares)
2280for (
auto &
P : DVRDeclares)
2286"debug-info-assignment-tracking";
2296returnValue && !cast<ConstantAsMetadata>(
Value)->getValue()->isZeroValue();
2305if (!runOnFunction(
F))
2308// Record that this module uses assignment tracking. It doesn't matter that 2309// some functons in the module may not use it - the debug info in those 2310// functions will still be handled properly. 2313// Q: Can we return a less conservative set than just CFGAnalyses? Can we 2314// return PreservedAnalyses::all()? 2324 Changed |= runOnFunction(
F);
2329// Record that this module uses assignment tracking. 2332// Q: Can we return a less conservative set than just CFGAnalyses? Can we 2333// return PreservedAnalyses::all()? MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
static DIImportedEntity * createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context, Metadata *NS, DIFile *File, unsigned Line, StringRef Name, DINodeArray Elements, SmallVectorImpl< TrackingMDNodeRef > &ImportedModules)
static void setAssignmentTrackingModuleFlag(Module &M)
static DISubprogram::DISPFlags pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized)
static Metadata * stripLoopMDLoc(const SmallPtrSetImpl< Metadata * > &AllDILocation, const SmallPtrSetImpl< Metadata * > &DIReachable, Metadata *MD)
static MDNode * updateLoopMetadataDebugLocationsImpl(MDNode *OrigLoopID, function_ref< Metadata *(Metadata *)> Updater)
static MDNode * stripDebugLocFromLoopID(MDNode *N)
bool calculateFragmentIntersectImpl(const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits, uint64_t SliceSizeInBits, const T *AssignRecord, std::optional< DIExpression::FragmentInfo > &Result)
FIXME: Remove this wrapper function and call DIExpression::calculateFragmentIntersect directly.
static const char * AssignmentTrackingModuleFlag
static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags)
static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang)
static void emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest, Instruction &StoreLikeInst, const VarRecord &VarRec, DIBuilder &DIB)
Returns nullptr if the assignment shouldn't be attributed to this variable.
static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags)
static void findDbgIntrinsics(SmallVectorImpl< IntrinsicT * > &Result, Value *V, SmallVectorImpl< DbgVariableRecord * > *DbgVariableRecords)
static bool getAssignmentTrackingModuleFlag(const Module &M)
static bool isAllDILocation(SmallPtrSetImpl< Metadata * > &Visited, SmallPtrSetImpl< Metadata * > &AllDILocation, const SmallPtrSetImpl< Metadata * > &DIReachable, Metadata *MD)
static bool isDILocationReachable(SmallPtrSetImpl< Metadata * > &Visited, SmallPtrSetImpl< Metadata * > &Reachable, Metadata *MD)
Return true if a node is a DILocation or if a DILocation is indirectly referenced by one of the node'...
DIT * unwrapDI(LLVMMetadataRef Ref)
static std::optional< AssignmentInfo > getAssignmentInfoImpl(const DataLayout &DL, const Value *StoreDest, TypeSize SizeInBits)
Collect constant properies (base, size, offset) of StoreDest.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static uint32_t getFlags(const Symbol *Sym)
Class for arbitrary precision integers.
bool isNegative() const
Determine sign of this APInt.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
an instruction to allocate memory on the stack
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
A container for analyses that lazily runs them and caches their results.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM Basic Block Representation.
Represents analyses that only rely on functions' control flow.
static ConstantAsMetadata * get(Constant *C)
List of ValueAsMetadata, to be used as an argument to a dbg.value intrinsic.
SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
static DIAssignID * getDistinct(LLVMContext &Context)
DbgInstPtr insertDbgAssign(Instruction *LinkedInstr, Value *Val, DILocalVariable *SrcVar, DIExpression *ValExpr, Value *Addr, DIExpression *AddrExpr, const DILocation *DL)
Insert a new llvm.dbg.assign intrinsic call.
static bool calculateFragmentIntersect(const DataLayout &DL, const Value *SliceStart, uint64_t SliceOffsetInBits, uint64_t SliceSizeInBits, const Value *DbgPtr, int64_t DbgPtrOffsetInBits, int64_t DbgExtractOffsetInBits, DIExpression::FragmentInfo VarFrag, std::optional< DIExpression::FragmentInfo > &Result, int64_t &OffsetFromLocationInBits)
Computes a fragment, bit-extract operation if needed, and new constant offset to describe a part of a...
static std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
A pair of DIGlobalVariable and DIExpression.
DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
static DILocation * getMergedLocation(DILocation *LocA, DILocation *LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Tagged DWARF-like metadata node.
Base class for scope-like contexts.
StringRef getName() const
DIScope * getScope() const
static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
DISPFlags
Debug info subprogram flags.
Type array for a subprogram.
std::optional< uint64_t > getSizeInBits() const
Determines the size of the variable's type.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
This represents the llvm.dbg.assign instruction.
This represents the llvm.dbg.declare instruction.
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
LLVMContext & getContext()
This represents the llvm.dbg.value instruction.
This is the common base class for debug info intrinsics for variables.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
static DbgVariableRecord * createLinkedDVRAssign(Instruction *LinkedInstr, Value *Val, DILocalVariable *Variable, DIExpression *Expression, Value *Address, DIExpression *AddressExpression, const DILocation *DI)
void processInstruction(const Module &M, const Instruction &I)
Process a single instruction and collect debug info anchors.
void processModule(const Module &M)
Process entire module and collect debug info anchors.
void processVariable(const Module &M, const DILocalVariable *DVI)
Process a DILocalVariable.
void processSubprogram(DISubprogram *SP)
Process subprogram.
void processLocation(const Module &M, const DILocation *Loc)
Process debug info location.
void reset()
Clear all lists.
void processDbgRecord(const Module &M, const DbgRecord &DR)
Process a DbgRecord (e.g, treat a DbgVariableRecord like a DbgVariableIntrinsic).
DILocation * get() const
Get the underlying DILocation.
MDNode * getScope() const
DILocation * getInlinedAt() const
Identifies a unique instance of a whole variable (discards/ignores fragment information).
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
BasicBlockListType::iterator iterator
DISubprogram * getSubprogram() const
Get the attached subprogram.
void mergeDIAssignID(ArrayRef< const Instruction * > SourceInstructions)
Merge the DIAssignID metadata from this instruction and those attached to instructions in SourceInstr...
void dropLocation()
Drop the instruction's debug location.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void updateLocationAfterHoist()
Updates the debug location given that the instruction has been hoisted from a block to a predecessor ...
void applyMergedLocation(DILocation *LocA, DILocation *LocB)
Merge 2 debug locations and apply it to the Instruction.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
DenseMap< DIAssignID *, SmallVector< Instruction *, 1 > > AssignmentIDToInstrs
Map DIAssignID -> Instructions with that attachment.
This is an important class for using LLVM in a threaded context.
LLVMContextImpl *const pImpl
static LocalAsMetadata * getIfExists(Value *Local)
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
static void deleteTemporary(MDNode *N)
Deallocate a node created by getTemporary.
const MDOperand & getOperand(unsigned I) const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
unsigned getNumOperands() const
Return number of MDNode operands.
LLVMContext & getContext() const
Tracking metadata reference owned by Metadata.
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
This is the common base class for memset/memcpy/memmove.
static MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Root of the metadata hierarchy.
A Module instance is used to store all the information related to an LLVM module.
@ Max
Takes the max of the two values, which are required to be integers.
StringRef getName() const
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void preserveSet()
Mark an analysis set as preserved.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
void push_back(EltTy NewVal)
static constexpr TypeSize getFixed(ScalarTy ExactSize)
The instances of the Type class are immutable: once they are created, they are never changed.
static IntegerType * getInt1Ty(LLVMContext &C)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr) const
Accumulate the constant offset this value has compared to a base pointer.
LLVMContext & getContext() const
All values hold a context through their type.
user_iterator_impl< User > user_iterator
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
A range adaptor for a pair of iterators.
LLVMMetadataRef LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags, LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode)
Create debugging information entry for Objective-C instance variable.
LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location)
Get the "inline at" location associated with this debug location.
LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder, LLVMMetadataRef *Data, size_t NumElements)
Create an array of DI Nodes.
LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements, unsigned NumElements, LLVMMetadataRef ClassTy)
Create debugging information entry for an enumeration.
LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M, LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements, unsigned NumElements)
Create a descriptor for an imported module.
uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType)
Get the size of this DIType in bits.
LLVMDWARFMacinfoRecordType
Describes the kind of macro declaration used for LLVMDIBuilderCreateMacro.
LLVMMetadataRef LLVMDIBuilderCreateFunction(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, const char *LinkageName, size_t LinkageNameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, LLVMBool IsLocalToUnit, LLVMBool IsDefinition, unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized)
Create a new descriptor for the specified subprogram.
LLVMDbgRecordRef LLVMDIBuilderInsertDeclareRecordAtEnd(LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo, LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block)
Only use in "new debug format" (LLVMIsNewDbgInfoFormat() is true).
LLVMMetadataRef LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits, LLVMDIFlags Flags, LLVMMetadataRef Type)
Create debugging information entry for a bit field member.
LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE)
Retrieves the DIVariable associated with this global variable expression.
LLVMMetadataRef LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder, LLVMMetadataRef Type)
Create a uniqued DIType* clone with FlagArtificial set.
LLVMMetadataRef LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder, LLVMMetadataRef Type, LLVMBool Implicit)
Create a uniqued DIType* clone with FlagObjectPointer.
void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder)
Construct any deferred debug info descriptors.
LLVMMetadataRef LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Discriminator)
Create a descriptor for a lexical block with a new file attached.
unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram)
Get the line associated with a given subprogram.
LLVMMetadataRef LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name, size_t NameLen)
Create a DWARF unspecified type.
LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope, const char *Name, size_t NameLen, LLVMBool ExportSymbols)
Creates a new descriptor for a namespace with the specified parent scope.
LLVMMetadataRef LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line, unsigned Column, LLVMMetadataRef Scope, LLVMMetadataRef InlinedAt)
Creates a new DebugLocation that describes a source location.
uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType)
Get the alignment of this DIType in bits.
LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(LLVMMetadataRef GVE)
Retrieves the DIExpression associated with this global variable expression.
LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var)
Get the metadata of the scope associated with a given variable.
LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst)
Get the debug location for the given instruction.
LLVMMetadataRef LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Type)
Create debugging information entry for a c++ style reference or rvalue reference type.
LLVMMetadataRef LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope, const char *Name, size_t NameLen, const char *ConfigMacros, size_t ConfigMacrosLen, const char *IncludePath, size_t IncludePathLen, const char *APINotesFile, size_t APINotesFileLen)
Creates a new descriptor for a module with the specified parent scope.
LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M)
Construct a builder for a module, and do not allow for unresolved nodes attached to the module.
void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP)
Set the subprogram attached to a function.
LLVMDWARFSourceLanguage
Source languages known by DWARF.
LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder, int64_t LowerBound, int64_t Count)
Create a descriptor for a value range.
LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M)
Construct a builder for a module and collect unresolved nodes attached to the module in order to reso...
void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode)
Deallocate a temporary node.
LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location)
Get the local scope associated with this debug location.
LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef NS, LLVMMetadataRef File, unsigned Line)
Create a descriptor for an imported namespace.
LLVMMetadataRef LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentMacroFile, unsigned Line, LLVMMetadataRef File)
Create debugging information temporary entry for a macro file.
void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc)
Set the debug location for the given instruction.
LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder, const char *Name, size_t NameLen, int64_t Value, LLVMBool IsUnsigned)
Create debugging information entry for an enumerator.
LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder, uint64_t *Addr, size_t Length)
Create a new descriptor for the specified variable which has a complex address expression for its add...
LLVMMetadataRef LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size, uint32_t AlignInBits, LLVMMetadataRef Ty, LLVMMetadataRef *Subscripts, unsigned NumSubscripts)
Create debugging information entry for a vector type.
LLVMMetadataRef LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeType, LLVMMetadataRef ClassType, uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags)
Create debugging information entry for a pointer to member.
unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location)
Get the column number of this debug location.
LLVMDIFlags
Debug info flags.
LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits)
Create a new descriptor for a local auto variable.
LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data, size_t NumElements)
Create a new temporary MDNode.
LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType)
Get the flags associated with this DIType.
const char * LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len)
Get the directory of a given file.
void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TempTargetMetadata, LLVMMetadataRef Replacement)
Replace all uses of temporary metadata.
const char * LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len)
Get the name of a given file.
LLVMMetadataRef LLVMDIBuilderCreateLabel(LLVMDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMBool AlwaysPreserve)
Create a new descriptor for a label.
unsigned LLVMDebugMetadataVersion(void)
The current debug metadata version number.
unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef Module)
The version of debug metadata that's present in the provided Module.
unsigned LLVMDITypeGetLine(LLVMMetadataRef DType)
Get the source line where this DIType is declared.
LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var)
Get the metadata of the file associated with a given variable.
LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements, unsigned NumElements)
Create a descriptor for an imported module that aliases another imported entity descriptor.
LLVMMetadataRef LLVMDIBuilderCreateStaticMemberType(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal, uint32_t AlignInBits)
Create debugging information entry for a C++ static data member.
uint16_t LLVMGetDINodeTag(LLVMMetadataRef MD)
Get the dwarf::Tag of a DINode.
LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit, LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits)
Create a new descriptor for the specified variable.
LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit, LLVMMetadataRef Decl, uint32_t AlignInBits)
Create a new descriptor for the specified global variable that is temporary and meant to be RAUWed.
LLVMMetadataRef LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Type)
Create debugging information entry for a qualified type, e.g.
LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata)
Obtain the enumerated type of a Metadata instance.
LLVMMetadataRef LLVMDIBuilderCreateUnionType(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags, LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang, const char *UniqueId, size_t UniqueIdLen)
Create debugging information entry for a union.
LLVMMetadataRef LLVMDIBuilderCreateForwardDecl(LLVMDIBuilderRef Builder, unsigned Tag, const char *Name, size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits, const char *UniqueIdentifier, size_t UniqueIdentifierLen)
Create a permanent forward-declared type.
LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags)
Create a new descriptor for a function parameter variable.
LLVMMetadataRef LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder, LLVMMetadataRef File, LLVMMetadataRef *ParameterTypes, unsigned NumParameterTypes, LLVMDIFlags Flags)
Create subroutine type.
LLVMMetadataRef LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, const char *GetterName, size_t GetterNameLen, const char *SetterName, size_t SetterNameLen, unsigned PropertyAttributes, LLVMMetadataRef Ty)
Create debugging information entry for Objective-C property.
LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentMacroFile, unsigned Line, LLVMDWARFMacinfoRecordType RecordType, const char *Name, size_t NameLen, const char *Value, size_t ValueLen)
Create debugging information entry for a macro.
LLVMDWARFEmissionKind
The amount of debug information to emit.
LLVMDbgRecordRef LLVMDIBuilderInsertLabelAtEnd(LLVMDIBuilderRef Builder, LLVMMetadataRef LabelInfo, LLVMMetadataRef Location, LLVMBasicBlockRef InsertAtEnd)
Insert a new llvm.dbg.label intrinsic call.
LLVMMetadataRef LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size, uint32_t AlignInBits, LLVMMetadataRef Ty, LLVMMetadataRef *Subscripts, unsigned NumSubscripts)
Create debugging information entry for an array.
LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueRecordAtEnd(LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo, LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block)
Only use in "new debug format" (LLVMIsNewDbgInfoFormat() is true).
LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope)
Get the metadata of the file associated with a given scope.
void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder, LLVMMetadataRef Subprogram)
Finalize a specific subprogram.
LLVMMetadataRef LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder, uint64_t Value)
Create a new descriptor for the specified variable that does not have an address, but does have a con...
LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags, LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements, unsigned NumElements, LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode, const char *UniqueIdentifier, size_t UniqueIdentifierLen)
Create debugging information entry for a class.
LLVMMetadataRef LLVMDIBuilderCreateMemberType(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags, LLVMMetadataRef Ty)
Create debugging information entry for a member.
unsigned LLVMDILocationGetLine(LLVMMetadataRef Location)
Get the line number of this debug location.
LLVMMetadataRef LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder)
Create C++11 nullptr type.
LLVMMetadataRef LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder, LLVMMetadataRef Ty, LLVMMetadataRef BaseTy, uint64_t BaseOffset, uint32_t VBPtrOffset, LLVMDIFlags Flags)
Create debugging information entry to establish inheritance relationship between two types.
LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang, LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen, LLVMBool isOptimized, const char *Flags, size_t FlagsLen, unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen, LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining, LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen, const char *SDK, size_t SDKLen)
A CompileUnit provides an anchor for all debugging information generated during this instance of comp...
LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef Module)
Strip debug info in the module if it exists.
LLVMDbgRecordRef LLVMDIBuilderInsertDeclareRecordBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo, LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr)
Only use in "new debug format" (LLVMIsNewDbgInfoFormat() is true).
LLVMDbgRecordRef LLVMDIBuilderInsertLabelBefore(LLVMDIBuilderRef Builder, LLVMMetadataRef LabelInfo, LLVMMetadataRef Location, LLVMValueRef InsertBefore)
Insert a new llvm.dbg.label intrinsic call.
LLVMMetadataRef LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name, size_t NameLen, uint64_t SizeInBits, LLVMDWARFTypeEncoding Encoding, LLVMDIFlags Flags)
Create debugging information entry for a basic type.
unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var)
Get the source line where this DIVariable is declared.
LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueRecordBefore(LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo, LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr)
Only use in "new debug format" (LLVMIsNewDbgInfoFormat() is true).
unsigned LLVMDWARFTypeEncoding
An LLVM DWARF type encoding.
LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line, unsigned Column)
Create a descriptor for a lexical block with the specified parent context.
LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder, LLVMMetadataRef *Data, size_t NumElements)
Create a type array.
LLVMMetadataRef LLVMDIBuilderCreateReplaceableCompositeType(LLVMDIBuilderRef Builder, unsigned Tag, const char *Name, size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags, const char *UniqueIdentifier, size_t UniqueIdentifierLen)
Create a temporary forward-declared type.
const char * LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len)
Get the source of a given file.
uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType)
Get the offset of this DIType in bits.
LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl, LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen, LLVMMetadataRef *Elements, unsigned NumElements)
Create a descriptor for an imported function, type, or variable.
LLVMMetadataRef LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename, size_t FilenameLen, const char *Directory, size_t DirectoryLen)
Create a file descriptor to hold debugging information for a file.
const char * LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length)
Get the name of this DIType.
unsigned LLVMMetadataKind
LLVMMetadataRef LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Scope, uint32_t AlignInBits)
Create debugging information entry for a typedef.
LLVMMetadataRef LLVMDIBuilderCreateStructType(LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags, LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder, const char *UniqueId, size_t UniqueIdLen)
Create debugging information entry for a struct.
void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder)
Deallocates the DIBuilder and everything it owns.
LLVMMetadataRef LLVMDIBuilderCreatePointerType(LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy, uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace, const char *Name, size_t NameLen)
Create debugging information entry for a pointer.
LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func)
Get the metadata of the subprogram attached to a function.
@ LLVMGenericDINodeMetadataKind
struct LLVMOpaqueValue * LLVMValueRef
Represents an individual value in LLVM IR.
struct LLVMOpaqueDbgRecord * LLVMDbgRecordRef
struct LLVMOpaqueContext * LLVMContextRef
The top-level container for all LLVM global data.
struct LLVMOpaqueBasicBlock * LLVMBasicBlockRef
Represents a basic block of instructions in LLVM IR.
struct LLVMOpaqueMetadata * LLVMMetadataRef
Represents an LLVM Metadata.
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
struct LLVMOpaqueDIBuilder * LLVMDIBuilderRef
Represents an LLVM debug info builder.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Assignment Tracking (at).
void deleteAll(Function *F)
Remove all Assignment Tracking related intrinsics and metadata from F.
AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
AssignmentMarkerRange getAssignmentMarkers(DIAssignID *ID)
Return a range of dbg.assign intrinsics which use \ID as an operand.
void trackAssignments(Function::iterator Start, Function::iterator End, const StorageToVarsMap &Vars, const DataLayout &DL, bool DebugPrints=false)
Track assignments to Vars between Start and End.
void remapAssignID(DenseMap< DIAssignID *, DIAssignID * > &Map, Instruction &I)
Replace DIAssignID uses and attachments with IDs from Map.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
std::optional< AssignmentInfo > getAssignmentInfo(const DataLayout &DL, const MemIntrinsic *I)
bool calculateFragmentIntersect(const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits, uint64_t SliceSizeInBits, const DbgAssignIntrinsic *DbgAssign, std::optional< DIExpression::FragmentInfo > &Result)
Calculate the fragment of the variable in DAI covered from (Dest + SliceOffsetInBits) to to (Dest + S...
void RAUW(DIAssignID *Old, DIAssignID *New)
Replace all uses (and attachments) of Old with New.
Calculates the starting offsets for various sections within the .debug_names section.
void prune(LinkGraph &G)
Removes dead symbols/blocks/addressables.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
TinyPtrVector< DbgDeclareInst * > findDbgDeclares(Value *V)
Finds dbg.declare intrinsics declaring local variables as living in the memory that 'V' points to.
bool stripDebugInfo(Function &F)
void findDbgUsers(SmallVectorImpl< DbgVariableIntrinsic * > &DbgInsts, Value *V, SmallVectorImpl< DbgVariableRecord * > *DbgVariableRecords=nullptr)
Finds the debug info intrinsics describing a value.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
@ Import
Import information from summary.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
void findDbgValues(SmallVectorImpl< DbgValueInst * > &DbgValues, Value *V, SmallVectorImpl< DbgVariableRecord * > *DbgVariableRecords=nullptr)
Finds the llvm.dbg.value intrinsics describing a value.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
bool stripNonLineTableDebugInfo(Module &M)
Downgrade the debug info in a module to contain only line table information.
DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII)
Produce a DebugLoc to use for each dbg.declare that is promoted to a dbg.value.
TinyPtrVector< DbgVariableRecord * > findDVRValues(Value *V)
As above, for DVRValues.
unsigned getDebugMetadataVersionFromModule(const Module &M)
Return Debug Info Metadata Version by checking module flags.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
@ Ref
The access may reference the value stored in memory.
Attribute unwrap(LLVMAttributeRef Attr)
bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
LLVMAttributeRef wrap(Attribute Attr)
TinyPtrVector< DbgVariableRecord * > findDVRDeclares(Value *V)
As above, for DVRDeclares.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
void updateLoopMetadataDebugLocations(Instruction &I, function_ref< Metadata *(Metadata *)> Updater)
Update the debug locations contained within the MD_loop metadata attached to the instruction I,...
DISubprogram * getDISubprogram(const MDNode *Scope)
Find subprogram that is enclosing this scope.
Helper object to track which of three possible relocation mechanisms are used for a particular value ...
Describes properties of a store that has a static size and offset into a some base storage.
Helper struct for trackAssignments, below.