65#define DEBUG_TYPE "dwarfdebug"
67STATISTIC(NumCSParams,
"Number of dbg call site params created");
70 "use-dwarf-ranges-base-address-specifier",
cl::Hidden,
80 cl::desc(
"Generate DWARF4 type units."),
91 cl::desc(
"Make an absence of debug location information explicit."),
99 "Default for platform"),
107 cl::desc(
"Use inlined strings rather than string section."),
115 cl::desc(
"Disable emission .debug_ranges section."),
120 cl::desc(
"Use sections+offset as references rather than labels."),
127 cl::desc(
"Emit the GNU .debug_macro format with DWARF <5"),
132 cl::desc(
"Enable use of the DWARFv5 DW_OP_convert operator"),
145 cl::desc(
"Which DWARF linkage-name attributes to emit."),
147 "Default for platform"),
150 "Abstract subprograms")),
155 cl::desc(
"Always use DW_AT_ranges in DWARFv5 whenever it could allow more "
156 "address pool entry sharing to reduce relocations/object size"),
158 "Default address minimization strategy"),
160 "Use rnglists for contiguous ranges if that allows "
161 "using a pre-existing base address"),
164 "Use exprloc addrx+offset expressions for any "
165 "address with a prior base address"),
167 "Use addrx+offset extension form for any address "
168 "with a prior base address"),
176 cl::desc(
"Set to false to ignore Key Instructions metadata"));
180void DebugLocDwarfExpression::emitOp(
uint8_t Op,
const char *Comment) {
186void DebugLocDwarfExpression::emitSigned(int64_t
Value) {
187 getActiveStreamer().emitSLEB128(
Value, Twine(
Value));
191 getActiveStreamer().emitULEB128(
Value, Twine(
Value));
194void DebugLocDwarfExpression::emitData1(uint8_t
Value) {
195 getActiveStreamer().emitInt8(
Value, Twine(
Value));
198void DebugLocDwarfExpression::emitBaseTypeRef(
uint64_t Idx) {
210 assert(!IsBuffering &&
"Already buffering?");
212 TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
219 return TmpBuf ? TmpBuf->Bytes.size() : 0;
225 for (
auto Byte :
enumerate(TmpBuf->Bytes)) {
226 const char *
Comment = (
Byte.index() < TmpBuf->Comments.size())
227 ? TmpBuf->Comments[
Byte.index()].c_str()
229 OutBS.emitInt8(
Byte.value(), Comment);
231 TmpBuf->Bytes.clear();
232 TmpBuf->Comments.clear();
243 const bool IsVariadic = !SingleLocExprOpt;
246 if (!IsVariadic && !
MI->isNonListDebugValue()) {
247 assert(
MI->getNumDebugOperands() == 1 &&
248 "Mismatched DIExpression and debug operands for debug instruction.");
249 Expr = *SingleLocExprOpt;
256 MI->isNonListDebugValue() &&
MI->isDebugOffsetImm());
258 }
else if (
Op.isTargetIndex()) {
261 }
else if (
Op.isGlobal()) {
264 }
else if (
Op.isImm())
266 else if (
Op.isFPImm())
268 else if (
Op.isCImm())
273 return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
292 Expr(ValueLoc.getExpression()) {
293 if (!Expr->getNumElements())
309 return FIE.Expr && FIE.Expr->isFragment();
311 "conflicting locations for variable");
315 bool GenerateTypeUnits,
324 if (GenerateTypeUnits && (DwarfVersion < 5 || !TT.isOSBinFormatELF()))
330 if (DwarfVersion >= 5)
340 SkeletonHolder(
A,
"skel_string", DIEValueAllocator),
341 IsDarwin(
A->TM.getTargetTriple().isOSDarwin()),
342 DebuggerTuning(
MMI->getModule()->getDebuggerTuning()),
344 const Triple &TT =
Asm->TM.getTargetTriple();
348 EmitDebugEntryValues =
Asm->TM.shouldEmitDebugEntryValues(DebuggerTuning);
361 HasSplitDwarf = !
Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
369 unsigned DwarfVersionNumber =
Asm->TM.Options.MCOptions.DwarfVersion;
370 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
371 :
MMI->getModule()->getDwarfVersion();
381 GenerateTypeUnits = (
A->TM.getTargetTriple().isOSBinFormatELF() ||
382 A->TM.getTargetTriple().isOSBinFormatWasm()) &&
395 const Triple &TT =
Asm->TM.getTargetTriple();
397 bool Dwarf64 = DwarfVersion >= 3 &&
406 ((
Asm->TM.Options.MCOptions.Dwarf64 ||
MMI->getModule()->isDwarf64()) &&
407 TT.isOSBinFormatELF()) ||
408 TT.isOSBinFormatXCOFF();
410 if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
421 UseGNUTLSOpcode =
tuneForGDB() || DwarfVersion < 3;
423 UseDWARF2Bitfields = DwarfVersion < 4;
429 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
433 UseDebugMacroSection =
441 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
450 return Name.starts_with(
"+") || Name.starts_with(
"-");
457 return Name.contains(
") ");
463 Class = In.slice(In.find(
'[') + 1, In.find(
' '));
468 Class = In.slice(In.find(
'[') + 1, In.find(
'('));
469 Category = In.slice(In.find(
'[') + 1, In.find(
' '));
473 return In.slice(In.find(
' ') + 1, In.find(
']'));
486 if (!SP->isDefinition())
489 if (SP->getName() !=
"")
520 if (Scope->isAbstractScope())
538 if (
auto *SkelCU =
CU.getSkeleton())
539 if (
CU.getCUNode()->getSplitDebugInlining())
550 auto &
CU = getOrCreateDwarfCompileUnit(SP->getUnit());
551 if (
CU.getSkeleton())
557void DwarfDebug::constructAbstractSubprogramScopeDIE(
DwarfCompileUnit &SrcCU,
559 assert(Scope && Scope->getScopeNode());
560 assert(Scope->isAbstractScope());
561 assert(!Scope->getInlinedAt());
567 auto &
CU = getOrCreateDwarfCompileUnit(SP->getUnit());
569 TargetCU.constructAbstractSubprogramScopeDIE(Scope);
570 if (
auto *SkelCU =
CU.getSkeleton())
571 if (
CU.getCUNode()->getSplitDebugInlining())
572 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
606template <
typename ValT>
610 for (
auto Param : DescribedParams) {
611 bool ShouldCombineExpressions = Expr && Param.Expr->
getNumElements() > 0;
621 "Combined debug expression is invalid");
636 auto &ParamsForFwdReg = Worklist[
Reg];
637 for (
auto Param : ParamsToAdd) {
640 return D.ParamReg == Param.ParamReg;
642 "Same parameter described twice by forwarding reg");
649 ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
669 auto IsRegClobberedInMeantime = [&](
Register Reg) ->
bool {
670 for (
auto &RegUnit : ClobberedRegUnits)
671 if (
TRI.hasRegUnit(
Reg, RegUnit))
676 auto DescribeFwdRegsByCalleeSavedCopy = [&](
const DestSourcePair &CopyInst) {
677 Register CopyDestReg = CopyInst.Destination->getReg();
678 Register CopySrcReg = CopyInst.Source->getReg();
679 if (IsRegClobberedInMeantime(CopyDestReg))
683 if (!
TRI.isCalleeSavedPhysReg(CopyDestReg, *MF))
690 for (
auto FwdRegIt = ForwardedRegWorklist.
begin();
691 FwdRegIt != ForwardedRegWorklist.
end();) {
693 if (FwdRegIt->first == CopySrcReg)
695 else if (
unsigned SubRegIdx =
696 TRI.getSubRegIndex(CopySrcReg, FwdRegIt->first))
697 if (
Register CopyDestSubReg =
TRI.getSubReg(CopyDestReg, SubRegIdx))
707 FwdRegIt = ForwardedRegWorklist.
erase(FwdRegIt);
715 if (
auto CopyInst =
TII.isCopyInstr(*CurMI))
716 DescribeFwdRegsByCalleeSavedCopy(*CopyInst);
744 if (
MI.isDebugInstr())
748 if (MO.getReg().isPhysical()) {
749 for (
auto &FwdReg : ForwardedRegWorklist)
750 if (
TRI.regsOverlap(FwdReg.first, MO.getReg()))
751 Defs.insert(FwdReg.first);
760 getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
761 if (FwdRegDefs.
empty()) {
767 for (
auto ParamFwdReg : FwdRegDefs) {
768 if (
auto ParamValue =
TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
769 if (ParamValue->first.isImm()) {
770 int64_t Val = ParamValue->first.getImm();
772 ForwardedRegWorklist[ParamFwdReg], Params);
773 }
else if (ParamValue->first.isReg()) {
774 Register RegLoc = ParamValue->first.getReg();
775 Register SP =
TLI.getStackPointerRegisterToSaveRestore();
777 bool IsSPorFP = (RegLoc == SP) || (RegLoc ==
FP);
780 if (!IsRegClobberedInMeantime(RegLoc) &&
781 (
TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP)) {
784 ForwardedRegWorklist[ParamFwdReg], Params);
793 ForwardedRegWorklist[ParamFwdReg]);
800 for (
auto ParamFwdReg : FwdRegDefs)
801 ForwardedRegWorklist.
erase(ParamFwdReg);
808 for (
auto &New : TmpWorklistItems)
810 TmpWorklistItems.
clear();
827 if (ForwardedRegWorklist.
empty())
834 interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);
845 auto CSInfo = CalleesMap.
find(CallMI);
848 if (CSInfo == CalleesMap.end())
862 for (
const auto &ArgReg : CSInfo->second.ArgRegPairs) {
864 ForwardedRegWorklist.
insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
866 assert(InsertedReg &&
"Single register used to forward two arguments?");
871 for (
const auto &MO : CallMI->
uses())
872 if (MO.isReg() && MO.isUndef())
873 ForwardedRegWorklist.
erase(MO.getReg());
883 bool ShouldTryEmitEntryVals =
MBB->getIterator() == MF->
begin();
892 assert(std::next(Suc) == BundleEnd &&
893 "More than one instruction in call delay slot");
900 for (;
I !=
MBB->rend(); ++
I) {
907 if (ShouldTryEmitEntryVals) {
911 for (
auto &RegEntry : ForwardedRegWorklist) {
918void DwarfDebug::constructCallSiteEntryDIEs(
const DISubprogram &SP,
923 if (!
SP.areAllCallsDescribed() || !
SP.isDefinition())
930 CU.addFlag(ScopeDIE,
CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
933 assert(
TII &&
"TargetInstrInfo not found: cannot label tail calls");
936 auto delaySlotSupported = [&](
const MachineInstr &
MI) {
937 if (!
MI.isBundledWithSucc())
939 auto Suc = std::next(
MI.getIterator());
941 (void)CallInstrBundle;
943 (void)DelaySlotBundle;
950 "Call and its successor instruction don't have same label after.");
955 auto addCallSiteTargetForIndirectCalls = [&](
const MachineInstr *
MI,
959 auto CSInfo = CalleesMap.
find(
MI);
961 if (CSInfo == CalleesMap.end() || !CSInfo->second.CallTarget)
964 MDNode *CallTarget = CSInfo->second.CallTarget;
966 assert(!CallSiteDIE.findAttribute(dwarf::DW_AT_LLVM_virtual_call_origin) &&
967 "DW_AT_LLVM_virtual_call_origin already exists");
969 DIE *CalleeDIE =
CU.getOrCreateSubprogramDIE(CalleeSP,
nullptr);
970 assert(CalleeDIE &&
"Could not create DIE for call site entry origin");
971 CU.addDIEEntry(CallSiteDIE,
972 CU.getDwarf5OrGNUAttr(dwarf::DW_AT_LLVM_virtual_call_origin),
975 CU.addLinkageNamesToDeclarations(*
this, *CalleeSP, *CalleeDIE);
979 for (
const MachineBasicBlock &
MBB : MF) {
989 if (!
MI.isCandidateForAdditionalCallInfo())
998 if (
MI.hasDelaySlot() && !delaySlotSupported(*&
MI))
1006 const MachineOperand &CalleeOp =
TII->getCalleeOperand(
MI);
1007 bool PhysRegCalleeOperand =
1009 MachineLocation CallTarget{0};
1011 const DISubprogram *CalleeSP =
nullptr;
1012 const Function *CalleeDecl =
nullptr;
1013 if (PhysRegCalleeOperand) {
1014 bool Scalable =
false;
1015 const MachineOperand *BaseOp =
nullptr;
1016 if (
TII->getMemOperandWithOffset(
MI, BaseOp,
Offset, Scalable)) {
1017 if (BaseOp && BaseOp->
isReg() && !Scalable)
1018 CallTarget = MachineLocation(BaseOp->
getReg(),
true);
1022 CallTarget = MachineLocation(CalleeOp.
getReg());
1031 if (CalleeSP ==
nullptr && CallTarget.
getReg() == 0 &&
1032 AllocSiteTy ==
nullptr)
1042 const MachineInstr *TopLevelCallMI =
1049 const MCSymbol *PCAddr = (!IsTail ||
CU.useGNUAnalogForDwarf5Feature())
1058 assert((IsTail || PCAddr) &&
"Non-tail call without return PC");
1061 dbgs() <<
"CallSiteEntry: " << MF.getName() <<
" -> "
1065 MF.getSubtarget().getRegisterInfo()->getName(
1067 << (IsTail ?
" [IsTail]" :
"") <<
"\n");
1069 DIE &CallSiteDIE =
CU.constructCallSiteEntryDIE(
1070 ScopeDIE, CalleeSP, CalleeDecl, IsTail, PCAddr, CallAddr, CallTarget,
1074 addCallSiteTargetForIndirectCalls(TopLevelCallMI, CallSiteDIE);
1081 CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
1088 if (!
U.hasDwarfPubSections())
1091 U.addFlag(
D, dwarf::DW_AT_GNU_pubnames);
1097 case dwarf::DW_LNAME_Fortran:
1098 case dwarf::DW_LNAME_Cobol:
1099 case dwarf::DW_LNAME_Pascal:
1106 case dwarf::DW_LANG_Cobol74:
1107 case dwarf::DW_LANG_Cobol85:
1108 case dwarf::DW_LANG_Fortran77:
1109 case dwarf::DW_LANG_Fortran90:
1110 case dwarf::DW_LANG_Fortran95:
1111 case dwarf::DW_LANG_Fortran03:
1112 case dwarf::DW_LANG_Fortran08:
1113 case dwarf::DW_LANG_Fortran18:
1114 case dwarf::DW_LANG_Fortran23:
1115 case dwarf::DW_LANG_Pascal83:
1122void DwarfDebug::finishUnitAttributes(
const DICompileUnit *DIUnit,
1130 std::string ProducerWithFlags =
Producer.str() +
" " +
Flags.str();
1131 NewCU.
addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
1133 NewCU.
addString(Die, dwarf::DW_AT_producer, Producer);
1136 NewCU.
addUInt(Die, dwarf::DW_AT_language_name, dwarf::DW_FORM_data2,
1139 if (uint32_t LangVersion = Lang.getVersion(); LangVersion != 0)
1140 NewCU.
addUInt(Die, dwarf::DW_AT_language_version, std::nullopt,
1143 NewCU.
addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1148 NewCU.
addUInt(Die, dwarf::DW_AT_identifier_case, dwarf::DW_FORM_data1,
1150 NewCU.
addString(Die, dwarf::DW_AT_name, FN);
1155 if (!SysRoot.
empty())
1156 NewCU.
addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
1157 StringRef SDK = DIUnit->
getSDK();
1159 NewCU.
addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
1170 if (!CompilationDir.empty())
1171 NewCU.
addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1172 addGnuPubAttributes(NewCU, Die);
1176 NewCU.
addFlag(Die, dwarf::DW_AT_APPLE_optimized);
1181 NewCU.
addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
1184 NewCU.
addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1185 dwarf::DW_FORM_data1, RVer);
1190 NewCU.
addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
1195 ? dwarf::DW_AT_dwo_name
1196 : dwarf::DW_AT_GNU_dwo_name;
1203 if (
auto *
CU = CUMap.lookup(DIUnit))
1210 return CUMap.begin()->second;
1218DwarfDebug::getOrCreateDwarfCompileUnit(
const DICompileUnit *DIUnit) {
1219 if (
auto *
CU = getDwarfCompileUnit(DIUnit))
1224 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
1226 DwarfCompileUnit &NewCU = *OwnedUnit;
1233 if (!
Asm->OutStreamer->hasRawTextSupport() || SingleCU)
1234 Asm->OutStreamer->emitDwarfFile0Directive(
1240 NewCU.
setSection(
Asm->getObjFileLowering().getDwarfInfoDWOSection());
1242 finishUnitAttributes(DIUnit, NewCU);
1243 NewCU.
setSection(
Asm->getObjFileLowering().getDwarfInfoSection());
1246 CUMap.insert({DIUnit, &NewCU});
1247 CUDieMap.insert({&NewCU.
getUnitDie(), &NewCU});
1261 if (!
A.Expr || !
B.Expr)
1263 auto FragmentA =
A.Expr->getFragmentInfo();
1264 auto FragmentB =
B.Expr->getFragmentInfo();
1265 if (!FragmentA || !FragmentB)
1267 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1272 return A.Expr ==
B.Expr;
1287 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
1288 M->debug_compile_units_end());
1289 if (NumDebugCUs == 0)
1292 assert(NumDebugCUs > 0 &&
"Asm unexpectedly initialized");
1293 SingleCU = NumDebugCUs == 1;
1300 .setStringOffsetsStartSym(
Asm->createTempSymbol(
"str_offsets_base"));
1308 Asm->createTempSymbol(
"rnglists_table_base"));
1312 Asm->createTempSymbol(
"rnglists_dwo_table_base"));
1317 AddrPool.setLabel(
Asm->createTempSymbol(
"addr_table_base"));
1318 DebugLocs.setSym(
Asm->createTempSymbol(
"loclists_table_base"));
1321 if (CUNode->getImportedEntities().empty() &&
1322 CUNode->getEnumTypes().empty() && CUNode->getRetainedTypes().empty() &&
1323 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1326 getOrCreateDwarfCompileUnit(CUNode);
1330void DwarfDebug::finishEntityDefinitions() {
1331 for (
const auto &Entity : ConcreteEntities) {
1332 DIE *Die = Entity->getDIE();
1339 Unit->finishEntityDefinition(Entity.get());
1343void DwarfDebug::finishSubprogramDefinitions() {
1344 for (
const DISubprogram *SP : ProcessedSPNodes) {
1347 getOrCreateDwarfCompileUnit(
SP->getUnit()),
1348 [&](DwarfCompileUnit &
CU) { CU.finishSubprogramDefinition(SP); });
1352void DwarfDebug::finalizeModuleInfo() {
1353 const TargetLoweringObjectFile &TLOF =
Asm->getObjFileLowering();
1355 finishSubprogramDefinitions();
1357 finishEntityDefinitions();
1359 bool HasEmittedSplitCU =
false;
1363 for (
const auto &
P : CUMap) {
1364 auto &TheCU = *
P.second;
1365 if (TheCU.getCUNode()->isDebugDirectivesOnly())
1367 TheCU.attachLexicalScopesAbstractOrigins();
1370 TheCU.constructContainingTypeDIEs();
1371 TheCU.constructPropertyForwardDIEs();
1376 auto *SkCU = TheCU.getSkeleton();
1378 bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1381 (void)HasEmittedSplitCU;
1383 "Multiple CUs emitted into a single dwo file");
1384 HasEmittedSplitCU =
true;
1386 ? dwarf::DW_AT_dwo_name
1387 : dwarf::DW_AT_GNU_dwo_name;
1388 finishUnitAttributes(TheCU.getCUNode(), TheCU);
1389 StringRef DWOName =
Asm->TM.Options.MCOptions.SplitDwarfFile;
1390 TheCU.addString(TheCU.getUnitDie(), attrDWOName, DWOName);
1391 SkCU->addString(SkCU->getUnitDie(), attrDWOName, DWOName);
1397 DIEHash(
Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
1402 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1403 dwarf::DW_FORM_data8, ID);
1404 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1405 dwarf::DW_FORM_data8, ID);
1408 if (
getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1410 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1414 finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1423 DwarfCompileUnit &
U = SkCU ? *SkCU : TheCU;
1425 if (
unsigned NumRanges = TheCU.getRanges().size()) {
1432 U.addUInt(
U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1435 U.setBaseAddress(TheCU.getRanges().front().Begin);
1436 U.attachRangesOrLowHighPC(
U.getUnitDie(), TheCU.takeRanges());
1443 U.addAddrTableBase();
1446 if (
U.hasRangeLists())
1447 U.addRnglistsBase();
1450 U.addSectionLabel(
U.getUnitDie(), dwarf::DW_AT_loclists_base,
1459 if (CUNode->getMacros()) {
1461 if (UseDebugMacroSection) {
1466 ? dwarf::DW_AT_macros
1467 : dwarf::DW_AT_GNU_macros;
1469 U.getMacroLabelBegin(), Section);
1475 dwarf::DW_AT_macro_info,
1476 U.getMacroLabelBegin(), Section);
1482 for (
auto *CUNode :
MMI->getModule()->debug_compile_units())
1483 if (CUNode->getDWOId())
1484 getOrCreateDwarfCompileUnit(CUNode);
1489 SkeletonHolder.computeSizeAndOffsets();
1493 AccelDebugNames.convertDieToOffset();
1502 assert(CurFn ==
nullptr);
1508 AllFunctionsProcessed =
true;
1510 for (
const auto &
CU : Holder->getUnits())
1511 CU->resolvePendingLocalScopeDIEs();
1520 Global.getDebugInfo(GVs);
1521 for (
auto *GVE : GVs)
1522 GVMap[GVE->getVariable()].push_back({&
Global, GVE->getExpression()});
1533 for (
auto *GVE : CUNode->getGlobalVariables()) {
1537 auto &GVMapEntry = GVMap[GVE->getVariable()];
1538 auto *Expr = GVE->getExpression();
1539 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1540 GVMapEntry.push_back({
nullptr, Expr});
1543 for (
auto *GVE : CUNode->getGlobalVariables()) {
1546 "Unexpected function-local entity in 'globals' CU field.");
1547 if (Processed.
insert(GV).second)
1552 for (
auto *Ty : CUNode->getEnumTypes()) {
1554 "Unexpected function-local entity in 'enums' CU field.");
1558 for (
auto *Ty : CUNode->getRetainedTypes()) {
1561 CU->getOrCreateTypeDIE(RT);
1566 for (
auto *IE : CUNode->getImportedEntities()) {
1568 "Unexpected function-local entity in 'imports' CU field.");
1569 CU->getOrCreateImportedEntityDIE(IE);
1573 const auto Unexpected = [](
const Metadata *
N) {
1576 for (
const auto *
D :
CU->getDeferredLocalDecls())
1577 DISubprogram::visitRetainedNode<void>(
1578 D, Unexpected, Unexpected,
1579 [
CU](
const auto *IE) {
CU->getOrCreateImportedEntityDIE(IE); },
1580 [
CU](
const auto *Ty) {
CU->getOrCreateTypeDIE(Ty); },
1581 [&](
const auto *GVE) {
1583 if (Processed.
insert(GV).second)
1589 CU->createBaseTypeDIEs();
1594 if (!
Asm || !
Asm->hasDebugInfo())
1598 finalizeModuleInfo();
1608 emitAbbreviations();
1614 if (UseARangesSection)
1622 emitDebugMacinfoDWO();
1632 emitDebugAbbrevDWO();
1634 emitDebugRangesDWO();
1644 emitAccelNamespaces();
1648 emitAccelDebugNames();
1657 emitDebugPubSections();
1665 if (
CU.getExistingAbstractEntity(
Node))
1670 CU.createAbstractEntity(
Node, Scope);
1679void DwarfDebug::collectVariableInfoFromMFTable(
1681 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1682 LLVM_DEBUG(
dbgs() <<
"DwarfDebug: collecting variables from MF side table\n");
1683 for (
const auto &VI :
Asm->MF->getVariableDbgInfo()) {
1686 assert(
VI.Var->isValidLocationForIntrinsic(
VI.Loc) &&
1687 "Expected inlined-at fields to agree");
1689 InlinedEntity Var(
VI.Var,
VI.Loc->getInlinedAt());
1696 <<
", no variable scope found\n");
1700 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first,
Scope->getScopeNode());
1704 if (DbgVariable *PreviousLoc = MFVars.
lookup(Var)) {
1705 auto *PreviousMMI = std::get_if<Loc::MMI>(PreviousLoc);
1706 auto *PreviousEntryValue = std::get_if<Loc::EntryValue>(PreviousLoc);
1708 if (PreviousMMI &&
VI.inStackSlot())
1709 PreviousMMI->addFrameIndexExpr(
VI.Expr,
VI.getStackSlot());
1711 else if (PreviousEntryValue &&
VI.inEntryValueRegister())
1712 PreviousEntryValue->addExpr(
VI.getEntryValueRegister(), *
VI.Expr);
1717 if (PreviousLoc->holds<Loc::MMI>())
1718 PreviousLoc->emplace<Loc::EntryValue>(
VI.getEntryValueRegister(),
1721 <<
", conflicting fragment location types\n");
1726 auto RegVar = std::make_unique<DbgVariable>(
1728 if (
VI.inStackSlot())
1729 RegVar->emplace<Loc::MMI>(
VI.Expr,
VI.getStackSlot());
1731 RegVar->emplace<Loc::EntryValue>(
VI.getEntryValueRegister(), *
VI.Expr);
1734 InfoHolder.addScopeVariable(Scope, RegVar.get());
1735 MFVars.
insert({Var, RegVar.get()});
1736 ConcreteEntities.push_back(std::move(RegVar));
1748 assert(
DbgValue->getDebugLoc() &&
"DBG_VALUE without a debug location");
1756 if (LSRange.size() == 0)
1759 const MachineInstr *LScopeBegin = LSRange.front().first;
1763 if (!Ordering.isBefore(
DbgValue, LScopeBegin)) {
1772 auto PredDL =
Pred->getDebugLoc();
1773 if (!PredDL ||
Pred->isMetaInstruction())
1777 if (
DL->getScope() == PredDL->getScope())
1780 if (!PredScope || LScope->dominates(PredScope))
1795 if (
MBB->pred_empty() &&
1797 return Op.isImm() || Op.isGlobal();
1803 if (Ordering.isBefore(RangeEnd, LScopeEnd))
1847 std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1849 bool isSafeForSingleLocation =
true;
1850 const MachineInstr *StartDebugMI =
nullptr;
1851 const MachineInstr *EndMI =
nullptr;
1853 for (
auto EB = Entries.
begin(), EI = EB, EE = Entries.
end(); EI != EE; ++EI) {
1854 const MachineInstr *
Instr = EI->getInstr();
1857 size_t Index = std::distance(EB, EI);
1858 erase_if(OpenRanges, [&](OpenRange &R) {
return R.first <=
Index; });
1865 "Forgot label before/after instruction starting a range!");
1868 if (std::next(EI) == Entries.
end()) {
1869 const MachineBasicBlock &EndMBB =
Asm->MF->back();
1871 if (EI->isClobber())
1872 EndMI = EI->getInstr();
1874 else if (std::next(EI)->isClobber())
1878 assert(EndLabel &&
"Forgot label after instruction ending a range!");
1880 if (EI->isDbgValue())
1886 if (EI->isDbgValue()) {
1893 if (!
Instr->isUndefDebugValue()) {
1898 if (
Instr->getDebugExpression()->isFragment())
1899 isSafeForSingleLocation =
false;
1902 StartDebugMI =
Instr;
1904 isSafeForSingleLocation =
false;
1910 if (OpenRanges.
empty())
1914 if (StartLabel == EndLabel) {
1915 LLVM_DEBUG(
dbgs() <<
"Omitting location list entry with empty range.\n");
1920 for (
auto &R : OpenRanges)
1928 if (
Asm->MF->hasBBSections() && StartLabel ==
Asm->getFunctionBegin() &&
1929 !
Instr->getParent()->sameSection(&
Asm->MF->front())) {
1930 for (
const auto &[MBBSectionId, MBBSectionRange] :
1931 Asm->MBBSectionRanges) {
1932 if (
Instr->getParent()->getSectionID() == MBBSectionId) {
1933 DebugLoc.emplace_back(MBBSectionRange.BeginLabel, EndLabel,
Values);
1936 DebugLoc.emplace_back(MBBSectionRange.BeginLabel,
1937 MBBSectionRange.EndLabel,
Values);
1947 dbgs() << CurEntry->getValues().size() <<
" Values:\n";
1948 for (
auto &
Value : CurEntry->getValues())
1950 dbgs() <<
"-----\n";
1953 auto PrevEntry = std::next(CurEntry);
1954 if (PrevEntry !=
DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1958 if (!isSafeForSingleLocation ||
1965 if (!
Asm->MF->hasBBSections())
1973 const MachineBasicBlock *RangeMBB =
nullptr;
1974 if (
DebugLoc[0].getBeginSym() ==
Asm->getFunctionBegin())
1975 RangeMBB = &
Asm->MF->front();
1977 RangeMBB = Entries.
begin()->getInstr()->getParent();
1979 assert(RangeIt !=
Asm->MBBSectionRanges.end() &&
1980 "Range MBB not found in MBBSectionRanges!");
1982 auto *NextEntry = std::next(CurEntry);
1983 auto NextRangeIt = std::next(RangeIt);
1984 while (NextEntry !=
DebugLoc.end()) {
1985 if (NextRangeIt ==
Asm->MBBSectionRanges.end())
1992 if ((RangeIt->second.EndLabel !=
Asm->getFunctionEnd() &&
1993 CurEntry->getEndSym() != RangeIt->second.EndLabel) ||
1994 NextEntry->getBeginSym() != NextRangeIt->second.BeginLabel ||
1995 CurEntry->getValues() != NextEntry->getValues())
1997 RangeIt = NextRangeIt;
1998 NextRangeIt = std::next(RangeIt);
1999 CurEntry = NextEntry;
2000 NextEntry = std::next(CurEntry);
2010 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node,
Scope.getScopeNode());
2012 ConcreteEntities.push_back(
2018 ConcreteEntities.push_back(
2024 return ConcreteEntities.back().get();
2032 collectVariableInfoFromMFTable(TheCU, Processed);
2035 InlinedEntity
IV =
I.first;
2040 const auto &HistoryMapEntries =
I.second;
2044 if (!
DbgValues.hasNonEmptyLocation(HistoryMapEntries))
2047 LexicalScope *
Scope =
nullptr;
2049 if (
const DILocation *IA =
IV.second)
2059 *Scope, LocalVar,
IV.second));
2061 const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
2067 size_t HistSize = HistoryMapEntries.size();
2068 bool SingleValueWithClobber =
2069 HistSize == 2 && HistoryMapEntries[1].isClobber();
2070 if (HistSize == 1 || SingleValueWithClobber) {
2072 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() :
nullptr;
2074 RegVar->emplace<Loc::Single>(MInsn);
2080 DebugLocStream::ListBuilder
List(DebugLocs, TheCU, *
Asm, *RegVar);
2084 bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
2089 if (isValidSingleLocation) {
2090 RegVar->emplace<Loc::Single>(Entries[0].getValues()[0]);
2101 for (
auto &Entry : Entries)
2108 InlinedEntity IL =
I.first;
2109 const MachineInstr *
MI =
I.second;
2113 LexicalScope *
Scope =
nullptr;
2116 const DILocalScope *LocalScope =
2117 Label->getScope()->getNonLexicalBlockFileScope();
2119 if (
const DILocation *IA = IL.second)
2132 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
2136 for (
const MDNode *
N :
SP->getRetainedNodes()) {
2140 if (!Processed.
insert(InlinedEntity(DN,
nullptr)).second)
2142 LexicalScope *LexS =
LScopes.findLexicalScope(LS);
2144 createConcreteEntity(TheCU, *LexS, DN,
nullptr);
2146 LocalDeclsPerLS[
LS].insert(
N);
2160 if (!
MI.isBundledWithSucc())
2162 auto Suc = std::next(
MI.getIterator());
2167 assert(Suc->isBundledWithPred() &&
2168 "Call bundle instructions are out of order");
2173 if (!NoDebug && SP->areAllCallsDescribed() &&
2175 (!
MI->hasDelaySlot() || delaySlotSupported(*
MI))) {
2177 bool IsTail =
TII->isTailCall(*
MI);
2195 auto RecordLineZero = [&]() {
2199 const MDNode *Scope =
nullptr;
2200 unsigned Column = 0;
2205 recordSourceLine(0, Column, Scope, 0);
2210 unsigned LastAsmLine =
2211 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
2216 if (
MI->isMetaInstruction())
2237 auto RecordSourceLine = [
this](
auto &
DL,
auto Flags) {
2239 if (
Asm->OutStreamer->isVerboseAsm()) {
2243 recordSourceLine(
DL.getLine(),
DL.getCol(),
DL.getScope(), Flags,
2252 bool ScopeUsesKeyInstructions =
2254 DL->getScope()->getSubprogram()->getKeyInstructionsEnabled();
2257 if (ScopeUsesKeyInstructions &&
DL &&
DL.getLine())
2258 IsKey = KeyInstructions.contains(
MI);
2264 assert(
MI->getParent() == &*
MI->getMF()->begin());
2265 recordSourceLine(SP->getScopeLine(), 0, SP,
2270 bool PrevInstInSameSection =
2272 PrevInstBB->getSectionID() ==
MI->getParent()->getSectionID());
2273 bool ForceIsStmt = ForceIsStmtInstrs.contains(
MI);
2274 if (PrevInstInSameSection && !ForceIsStmt &&
DL.isSameSourceLocation(
PrevInstLoc)) {
2284 if ((LastAsmLine == 0 &&
DL.getLine() != 0) || Flags) {
2286 RecordSourceLine(
DL, Flags);
2299 if (LastAsmLine == 0)
2320 if (
DL.getLine() == 0 && LastAsmLine == 0)
2327 if (ScopeUsesKeyInstructions) {
2334 if (
DL.getLine() && (
DL.getLine() != OldLine || ForceIsStmt))
2349 if (
Asm->OutStreamer->isVerboseAsm()) {
2353 recordSourceLine(
DL.getLine(),
DL.getCol(),
DL.getScope(), Flags,
2362static std::pair<const MachineInstr *, bool>
2373 bool IsEmptyPrologue =
2374 !(
F.hasPrologueData() ||
F.getMetadata(LLVMContext::MD_func_sanitize));
2379 -> std::optional<std::pair<const MachineInstr *, bool>> {
2381 bool isCopy = (
TII.isCopyInstr(
MI) ?
true :
false);
2382 bool isTrivRemat =
TII.isTriviallyReMaterializable(
MI);
2385 if (!isFrameSetup &&
MI.getDebugLoc()) {
2391 if (
MI.getDebugLoc().getLine())
2392 return std::make_pair(&
MI, IsEmptyPrologue);
2397 if (!
isCopy && !isTrivRemat && !isFrameSetup && !NonTrivialInst)
2398 NonTrivialInst = &
MI;
2400 IsEmptyPrologue =
false;
2401 return std::nullopt;
2409 auto CurBlock = MF->
begin();
2410 auto CurInst = CurBlock->begin();
2414 while (CurBlock->empty())
2415 CurInst = (++CurBlock)->begin();
2416 assert(CurInst != CurBlock->end());
2420 auto getNextInst = [&CurBlock, &CurInst, MF]() ->
bool {
2422 if (CurInst->isTerminator()) {
2431 if (CurBlock->pred_size() > 1)
2442 if (CurBlock == MF->
end())
2444 }
while (CurBlock->empty());
2445 CurInst = CurBlock->begin();
2451 if (!CurInst->isMetaInstruction()) {
2452 auto FoundInst = ExamineInst(*CurInst);
2463 if (CurInst->isCall()) {
2465 Loc &&
Loc->getLine() == 0) {
2467 unsigned ScopeLine = SP->getScopeLine();
2470 const_cast<MachineInstr *
>(&*CurInst)->setDebugLoc(ScopeLineDILoc);
2473 return std::make_pair(&*CurInst,
false);
2479 auto NextInst = std::next(CurInst);
2480 if (NextInst != CurInst->getParent()->end()) {
2497 if (NonTrivialInst && NonTrivialInst->
getParent() == &*MF->
begin()) {
2498 IsEmptyPrologue = NonTrivialInst == &*MF->
begin()->begin();
2499 return std::make_pair(NonTrivialInst, IsEmptyPrologue);
2503 return std::make_pair(
nullptr, IsEmptyPrologue);
2509 const MDNode *S,
unsigned Flags,
unsigned CUID,
2511 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs,
2514 unsigned FileNo = 1;
2517 Fn =
Scope->getFilename();
2518 if (Line != 0 && DwarfVersion >= 4)
2523 .getOrCreateSourceID(
Scope->getFile());
2525 Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
2526 Discriminator, Fn, Comment);
2537 bool IsEmptyPrologue = PrologEnd.second;
2540 if (IsEmptyPrologue) {
2548 if (!
DL ||
DL->getLine() != 0)
2559 (void)getOrCreateDwarfCompileUnit(SP->getUnit());
2569 KeyInstructions.clear();
2576 std::pair<uint8_t, SmallVector<const MachineInstr *, 2>>>
2593 for (
auto &
MBB : *MF) {
2603 uint64_t BuoyAtom = 0;
2605 for (
auto &
MI :
MBB) {
2606 if (
MI.isMetaInstruction())
2610 if (!
Loc || !
Loc->getLine())
2621 bool IsCallLike =
MI.isCall() ||
TII.isTailCall(
MI);
2626 KeyInstructions.insert(Buoy);
2632 if (!
Loc->getAtomGroup() || !
Loc->getAtomRank())
2636 auto *InlinedAt = Loc->getInlinedAt();
2639 if (!Group || !Rank)
2643 if (BuoyAtom && BuoyAtom != Group) {
2648 auto &[CandidateRank, CandidateInsts] =
2649 GroupCandidates[{InlinedAt, Group}];
2655 assert((CandidateRank == 0 && CandidateInsts.empty()) ||
2656 (CandidateRank != 0 && !CandidateInsts.empty()));
2658 assert(Rank &&
"expected nonzero rank");
2661 if (CandidateRank && CandidateRank < Rank)
2668 if (CandidateRank == Rank)
2672 else if (CandidateRank > Rank)
2673 CandidateInsts.clear();
2677 CandidateInsts.push_back(Buoy);
2678 CandidateRank = Rank;
2686 if (CandidateInsts.empty())
2692 for (
const auto &[
_, Insts] : GroupCandidates.
values())
2693 for (
auto *
I : Insts)
2694 KeyInstructions.insert(
I);
2702 ForceIsStmtInstrs.clear();
2734 SmallDenseSet<MachineBasicBlock *, 4> PredMBBsToExamine;
2735 SmallDenseMap<const MachineBasicBlock *, const MachineInstr *>
2736 PotentialIsStmtMBBInstrs;
2737 for (
const auto &
MBB : *MF) {
2740 for (
auto &
MI :
MBB) {
2741 if (
MI.getDebugLoc() &&
MI.getDebugLoc()->getLine()) {
2754 for (
auto *
MBB : PredMBBsToExamine) {
2755 auto CheckMBBEdge = [&](
const MachineBasicBlock *Succ,
2756 unsigned OutgoingLine) {
2757 auto MBBInstrIt = PotentialIsStmtMBBInstrs.
find(Succ);
2758 if (MBBInstrIt == PotentialIsStmtMBBInstrs.
end())
2760 const MachineInstr *
MI = MBBInstrIt->second;
2761 if (
MI->getDebugLoc()->getLine() == OutgoingLine)
2763 PotentialIsStmtMBBInstrs.
erase(MBBInstrIt);
2764 ForceIsStmtInstrs.insert(
MI);
2771 CheckMBBEdge(Succ, 0);
2777 return PotentialIsStmtMBBInstrs.contains(SuccMBB);
2785 const MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
2786 SmallVector<MachineOperand, 4>
Cond;
2792 if (!AnalyzeFailed && !
Cond.
empty() && FBB !=
nullptr &&
2795 assert(MIIt->isBranch() &&
"Bad result from analyzeBranch?");
2796 CheckMBBEdge(FBB, FBBLine);
2820 unsigned LastLine = 0;
2822 if (
auto DL = MIIt->getDebugLoc();
DL &&
DL->getLine()) {
2823 LastLine =
DL->getLine();
2828 for (
auto *Succ : SuccessorBBs)
2829 CheckMBBEdge(Succ, LastLine);
2844 FunctionLineTableLabel =
CU.emitFuncLineTableOffsets()
2845 ?
Asm->OutStreamer->emitLineTableLabel()
2848 Asm->OutStreamer->getContext().setDwarfCompileUnitID(
2856 *MF,
Asm->OutStreamer->getContext().getDwarfCompileUnitID());
2862 computeKeyInstructions(MF);
2863 findForceIsStmtInstrs(MF);
2871 if (
Asm->OutStreamer->hasRawTextSupport())
2875 return CU.getUniqueID();
2879 const auto &CURanges =
CU->getRanges();
2880 auto &LineTable =
Asm->OutStreamer->getContext().getMCDwarfLineTable(
2883 LineTable.getMCLineSections().addEndEntry(
2884 const_cast<MCSymbol *
>(CURanges.back().End));
2904 "endFunction should be called with the same function as beginFunction");
2907 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2919 collectEntityInfo(TheCU, SP, Processed);
2923 for (
const auto &R :
Asm->MBBSectionRanges)
2924 TheCU.
addRange({R.second.BeginLabel, R.second.EndLabel});
2931 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
2932 for (
const auto &R :
Asm->MBBSectionRanges)
2942 size_t NumAbstractSubprograms =
LScopes.getAbstractScopesList().size();
2946 for (
const MDNode *
N : SP->getRetainedNodes()) {
2949 auto *LexS =
LScopes.getOrCreateAbstractScope(LS);
2950 assert(LexS &&
"Expected the LexicalScope to be created.");
2954 if (!Processed.
insert(InlinedEntity(DN,
nullptr)).second ||
2960 LocalDeclsPerLS[LS].insert(
N);
2963 LScopes.getAbstractScopesList().size() == NumAbstractSubprograms &&
2964 "getOrCreateAbstractScope() inserted an abstract subprogram scope");
2966 constructAbstractSubprogramScopeDIE(TheCU, AScope);
2969 ProcessedSPNodes.insert(SP);
2973 if (!
LScopes.getAbstractScopesList().empty() &&
2975 SkelCU->constructSubprogramScopeDIE(SP,
F, FnScope,
2976 FunctionLineTableLabel);
2978 FunctionLineTableLabel =
nullptr;
2981 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2989 LocalDeclsPerLS.clear();
2996void DwarfDebug::recordSourceLine(
unsigned Line,
unsigned Col,
const MDNode *S,
3008void DwarfDebug::emitDebugInfo() {
3014void DwarfDebug::emitAbbreviations() {
3017 Holder.
emitAbbrevs(
Asm->getObjFileLowering().getDwarfAbbrevSection());
3020void DwarfDebug::emitStringOffsetsTableHeader() {
3023 *
Asm,
Asm->getObjFileLowering().getDwarfStrOffSection(),
3027template <
typename AccelTableT>
3028void DwarfDebug::emitAccel(AccelTableT &Accel,
MCSection *Section,
3030 Asm->OutStreamer->switchSection(Section);
3036void DwarfDebug::emitAccelDebugNames() {
3045void DwarfDebug::emitAccelNames() {
3046 emitAccel(AccelNames,
Asm->getObjFileLowering().getDwarfAccelNamesSection(),
3052void DwarfDebug::emitAccelObjC() {
3053 emitAccel(AccelObjC,
Asm->getObjFileLowering().getDwarfAccelObjCSection(),
3058void DwarfDebug::emitAccelNamespaces() {
3059 emitAccel(AccelNamespace,
3060 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
3065void DwarfDebug::emitAccelTypes() {
3066 emitAccel(AccelTypes,
Asm->getObjFileLowering().getDwarfAccelTypesSection(),
3096 if (Die->
getTag() == dwarf::DW_TAG_compile_unit)
3104 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
3111 case dwarf::DW_TAG_class_type:
3112 case dwarf::DW_TAG_structure_type:
3113 case dwarf::DW_TAG_union_type:
3114 case dwarf::DW_TAG_enumeration_type:
3119 case dwarf::DW_TAG_typedef:
3120 case dwarf::DW_TAG_base_type:
3121 case dwarf::DW_TAG_subrange_type:
3122 case dwarf::DW_TAG_template_alias:
3124 case dwarf::DW_TAG_namespace:
3126 case dwarf::DW_TAG_subprogram:
3128 case dwarf::DW_TAG_variable:
3130 case dwarf::DW_TAG_enumerator:
3140void DwarfDebug::emitDebugPubSections() {
3141 for (
const auto &NU : CUMap) {
3142 DwarfCompileUnit *TheU = NU.second;
3149 Asm->OutStreamer->switchSection(
3150 GnuStyle ?
Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
3151 :
Asm->getObjFileLowering().getDwarfPubNamesSection());
3152 emitDebugPubSection(GnuStyle,
"Names", TheU, TheU->
getGlobalNames());
3154 Asm->OutStreamer->switchSection(
3155 GnuStyle ?
Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
3156 :
Asm->getObjFileLowering().getDwarfPubTypesSection());
3157 emitDebugPubSection(GnuStyle,
"Types", TheU, TheU->
getGlobalTypes());
3163 Asm->emitDwarfOffset(
CU.getSection()->getBeginSymbol(),
3164 CU.getDebugSectionOffset());
3166 Asm->emitDwarfSymbolReference(
CU.getLabelBegin());
3169void DwarfDebug::emitDebugPubSection(
bool GnuStyle,
StringRef Name,
3177 "pub" + Name,
"Length of Public " + Name +
" Info");
3179 Asm->OutStreamer->AddComment(
"DWARF Version");
3182 Asm->OutStreamer->AddComment(
"Offset of Compilation Unit Info");
3183 emitSectionReference(*TheU);
3185 Asm->OutStreamer->AddComment(
"Compilation Unit Length");
3190 for (
const auto &GI : Globals)
3193 return A.second->getOffset() <
B.second->getOffset();
3195 for (
const auto &[Name, Entity] : Vec) {
3196 Asm->OutStreamer->AddComment(
"DIE offset");
3197 Asm->emitDwarfLengthOrOffset(Entity->getOffset());
3201 Asm->OutStreamer->AddComment(
3207 Asm->OutStreamer->AddComment(
"External Name");
3208 Asm->OutStreamer->emitBytes(StringRef(
Name.data(),
Name.size() + 1));
3211 Asm->OutStreamer->AddComment(
"End Mark");
3212 Asm->emitDwarfLengthOrOffset(0);
3213 Asm->OutStreamer->emitLabel(EndLabel);
3217void DwarfDebug::emitDebugStr() {
3218 MCSection *StringOffsetsSection =
nullptr;
3220 emitStringOffsetsTableHeader();
3221 StringOffsetsSection =
Asm->getObjFileLowering().getDwarfStrOffSection();
3224 Holder.
emitStrings(
Asm->getObjFileLowering().getDwarfStrSection(),
3225 StringOffsetsSection,
true);
3231 auto &&Comments = DebugLocs.getComments(Entry);
3232 auto Comment = Comments.begin();
3233 auto End = Comments.end();
3240 unsigned PtrSize =
Asm->MAI.getCodePointerSize();
3242 DebugLocs.getBytes(Entry).size()),
3243 Asm->getDataLayout().isLittleEndian(), PtrSize);
3248 for (
const auto &
Op : Expr) {
3249 assert(
Op.getCode() != dwarf::DW_OP_const_type &&
3250 "3 operand ops not yet supported");
3251 assert(!
Op.getSubCode() &&
"SubOps not yet supported");
3252 Streamer.emitInt8(
Op.getCode(), Comment !=
End ? *(Comment++) :
"");
3254 for (
unsigned I = 0;
I <
Op.getDescription().
Op.size(); ++
I) {
3255 if (
Op.getDescription().Op[
I] == Encoding::BaseTypeRef) {
3257 Streamer.emitDIERef(*
CU->ExprRefedBaseTypes[
Op.getRawOperand(
I)].Die);
3259 for (
unsigned J = 0; J <
Length; ++J)
3263 for (uint64_t J =
Offset; J <
Op.getOperandEndOffset(
I); ++J)
3264 Streamer.emitInt8(
Data.getData()[J], Comment !=
End ? *(Comment++) :
"");
3275 auto *DIExpr =
Value.getExpression();
3282 return Entry.isGlobalAddress();
3293 return Op.getOp() == dwarf::DW_OP_LLVM_implicit_pointer;
3301 if (DIExpr && DIExpr->isEntryValue()) {
3319 auto EmitValueLocEntry = [&DwarfExpr, &
BT,
3322 if (Entry.isInt()) {
3323 if (
BT && (
BT->getEncoding() == dwarf::DW_ATE_boolean)) {
3328 bool IsSigned =
BT && (
BT->getEncoding() == dwarf::DW_ATE_signed ||
3329 BT->getEncoding() == dwarf::DW_ATE_signed_char);
3340 uint64_t TypeBitSize =
BT->getSizeInBits();
3341 bool IsByteSized = TypeBitSize % 8 == 0;
3343 IsSigned ? !
isIntN(GenericBitSize, Entry.getInt())
3345 static_cast<uint64_t
>(Entry.getInt()));
3346 if (TypeBitSize > GenericBitSize && IsByteSized && IsOutOfRange) {
3348 APInt(
static_cast<unsigned>(TypeBitSize),
3349 static_cast<uint64_t
>(Entry.getInt()), IsSigned,
3360 }
else if (Entry.isLocation()) {
3362 if (Location.isIndirect())
3368 }
else if (Entry.isTargetIndexLocation()) {
3374 }
else if (Entry.isGlobalAddress()) {
3376 Entry.getGlobalOffset()))
3378 }
else if (Entry.isConstantFP()) {
3381 DwarfExpr.
addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
3382 }
else if (Entry.getConstantFP()
3385 .getBitWidth() <= 64 ) {
3387 Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
3390 dbgs() <<
"Skipped DwarfExpression creation for ConstantFP of size"
3391 << Entry.getConstantFP()
3402 if (!
Value.isVariadic()) {
3403 if (!EmitValueLocEntry(
Value.getLocEntries()[0], ExprCursor))
3412 return Entry.isLocation() && !Entry.getLoc().getReg();
3417 std::move(ExprCursor),
3418 [EmitValueLocEntry, &
Value](
unsigned Idx,
3420 return EmitValueLocEntry(
Value.getLocEntries()[Idx], Cursor);
3428 assert(!Values.empty() &&
3429 "location list entries without values are redundant");
3430 assert(Begin != End &&
"unexpected location list entry with empty range");
3435 if (
Value.isFragment()) {
3438 return P.isFragment();
3439 }) &&
"all values are expected to be fragments");
3442 for (
const auto &
Fragment : Values)
3446 assert(Values.size() == 1 &&
"only fragments may have >1 value");
3457 Asm->OutStreamer->AddComment(
"Loc expr size");
3459 Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
3460 else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
3461 Asm->emitInt16(DebugLocs.getBytes(Entry).size());
3480 Asm->OutStreamer->AddComment(
"Offset entry count");
3486 Asm->getDwarfOffsetByteSize());
3500 Asm->OutStreamer->AddComment(
"Offset entry count");
3501 Asm->emitInt32(DebugLocs.getLists().size());
3502 Asm->OutStreamer->emitLabel(DebugLocs.getSym());
3504 for (
const auto &List : DebugLocs.getLists())
3505 Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
3506 Asm->getDwarfOffsetByteSize());
3511template <
typename Ranges,
typename PayloadEmitter>
3515 unsigned OffsetPair,
unsigned StartxLength,
unsigned StartxEndx,
3517 bool ShouldUseBaseAddress, PayloadEmitter EmitPayload) {
3518 auto Size = Asm->MAI.getCodePointerSize();
3522 Asm->OutStreamer->emitLabel(Sym);
3529 for (
const auto &
Range : R)
3530 SectionRanges[&
Range.Begin->getSection()].push_back(&
Range);
3532 const MCSymbol *CUBase =
CU.getBaseAddress();
3533 bool BaseIsSet =
false;
3534 for (
const auto &
P : SectionRanges) {
3535 auto *
Base = CUBase;
3537 (DD.
useSplitDwarf() && UseDwarf5 &&
P.first->isLinkerRelaxable())) {
3540 }
else if (!
Base && ShouldUseBaseAddress) {
3541 const MCSymbol *Begin =
P.second.front()->Begin;
3546 Asm->OutStreamer->emitIntValue(-1,
Size);
3547 Asm->OutStreamer->AddComment(
" base address");
3548 Asm->OutStreamer->emitSymbolValue(
Base,
Size);
3549 }
else if (NewBase != Begin ||
P.second.size() > 1) {
3555 Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
3556 Asm->emitInt8(BaseAddressx);
3557 Asm->OutStreamer->AddComment(
" base address index");
3560 }
else if (BaseIsSet && !UseDwarf5) {
3563 Asm->OutStreamer->emitIntValue(-1,
Size);
3564 Asm->OutStreamer->emitIntValue(0,
Size);
3567 for (
const auto *RS :
P.second) {
3570 assert(Begin &&
"Range without a begin symbol?");
3571 assert(
End &&
"Range without an end symbol?");
3575 Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
3576 Asm->emitInt8(OffsetPair);
3577 Asm->OutStreamer->AddComment(
" starting offset");
3578 Asm->emitLabelDifferenceAsULEB128(Begin,
Base);
3579 Asm->OutStreamer->AddComment(
" ending offset");
3580 Asm->emitLabelDifferenceAsULEB128(
End,
Base);
3582 Asm->emitLabelDifference(Begin,
Base,
Size);
3585 }
else if (UseDwarf5) {
3593 Asm->OutStreamer->AddComment(StringifyEnum(StartxEndx));
3594 Asm->emitInt8(StartxEndx);
3595 Asm->OutStreamer->AddComment(
" start index");
3597 Asm->OutStreamer->AddComment(
" end index");
3600 Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
3601 Asm->emitInt8(StartxLength);
3602 Asm->OutStreamer->AddComment(
" start index");
3604 Asm->OutStreamer->AddComment(
" length");
3605 Asm->emitLabelDifferenceAsULEB128(
End, Begin);
3608 Asm->OutStreamer->emitSymbolValue(Begin,
Size);
3609 Asm->OutStreamer->emitSymbolValue(
End,
Size);
3616 Asm->OutStreamer->AddComment(StringifyEnum(
EndOfList));
3620 Asm->OutStreamer->emitIntValue(0,
Size);
3621 Asm->OutStreamer->emitIntValue(0,
Size);
3629 dwarf::DW_LLE_base_addressx, dwarf::DW_LLE_offset_pair,
3630 dwarf::DW_LLE_startx_length, dwarf::DW_LLE_startx_endx,
3633 DD.emitDebugLocEntryLocation(E, List.CU);
3637void DwarfDebug::emitDebugLocImpl(
MCSection *Sec) {
3638 if (DebugLocs.getLists().empty())
3641 Asm->OutStreamer->switchSection(Sec);
3647 for (
const auto &
List : DebugLocs.getLists())
3651 Asm->OutStreamer->emitLabel(TableEnd);
3655void DwarfDebug::emitDebugLoc() {
3658 ?
Asm->getObjFileLowering().getDwarfLoclistsSection()
3659 :
Asm->getObjFileLowering().getDwarfLocSection());
3663void DwarfDebug::emitDebugLocDWO() {
3666 Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
3671 for (
const auto &
List : DebugLocs.getLists()) {
3672 Asm->OutStreamer->switchSection(
3673 Asm->getObjFileLowering().getDwarfLocDWOSection());
3674 Asm->OutStreamer->emitLabel(
List.Label);
3676 for (
const auto &Entry : DebugLocs.getEntries(
List)) {
3685 Asm->emitInt8(dwarf::DW_LLE_startx_length);
3686 unsigned idx = AddrPool.getIndex(
Entry.Begin);
3687 Asm->emitULEB128(idx);
3693 Asm->emitInt8(dwarf::DW_LLE_end_of_list);
3703void DwarfDebug::emitDebugARanges() {
3704 if (ArangeLabels.empty())
3711 for (
const SymbolCU &SCU : ArangeLabels) {
3712 if (SCU.Sym->isInSection()) {
3714 MCSection *Section = &SCU.Sym->getSection();
3715 SectionMap[Section].push_back(SCU);
3720 SectionMap[
nullptr].push_back(SCU);
3724 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
3726 for (
auto &
I : SectionMap) {
3734 for (
const SymbolCU &Cur :
List) {
3736 Span.
Start = Cur.Sym;
3739 Spans[Cur.CU].push_back(Span);
3745 List.push_back(SymbolCU(
nullptr,
Asm->OutStreamer->endSection(Section)));
3749 for (
size_t n = 1, e =
List.size(); n < e; n++) {
3750 const SymbolCU &Prev =
List[n - 1];
3751 const SymbolCU &Cur =
List[n];
3754 if (Cur.
CU != Prev.
CU) {
3756 Span.
Start = StartSym;
3759 Spans[Prev.
CU].push_back(Span);
3766 Asm->OutStreamer->switchSection(
3767 Asm->getObjFileLowering().getDwarfARangesSection());
3769 unsigned PtrSize =
Asm->MAI.getCodePointerSize();
3772 std::vector<DwarfCompileUnit *> CUs;
3773 for (
const auto &it : Spans) {
3774 DwarfCompileUnit *
CU = it.first;
3779 llvm::sort(CUs, [](
const DwarfCompileUnit *
A,
const DwarfCompileUnit *
B) {
3780 return A->getUniqueID() <
B->getUniqueID();
3784 for (DwarfCompileUnit *
CU : CUs) {
3785 std::vector<ArangeSpan> &
List = Spans[
CU];
3788 if (
auto *Skel =
CU->getSkeleton())
3792 unsigned ContentSize =
3794 Asm->getDwarfOffsetByteSize() +
3799 unsigned TupleSize = PtrSize * 2;
3803 Asm->getUnitLengthFieldByteSize() + ContentSize,
Align(TupleSize));
3806 ContentSize += (
List.size() + 1) * TupleSize;
3809 Asm->emitDwarfUnitLength(ContentSize,
"Length of ARange Set");
3810 Asm->OutStreamer->AddComment(
"DWARF Arange version number");
3812 Asm->OutStreamer->AddComment(
"Offset Into Debug Info Section");
3813 emitSectionReference(*
CU);
3814 Asm->OutStreamer->AddComment(
"Address Size (in bytes)");
3815 Asm->emitInt8(PtrSize);
3816 Asm->OutStreamer->AddComment(
"Segment Size (in bytes)");
3819 Asm->OutStreamer->emitFill(Padding, 0xff);
3821 for (
const ArangeSpan &Span :
List) {
3822 Asm->emitLabelReference(Span.Start, PtrSize);
3829 auto SizeRef = SymSize.find(Span.Start);
3830 if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
3831 Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
3836 if (SizeRef == SymSize.end() || SizeRef->second == 0)
3839 Size = SizeRef->second;
3841 Asm->OutStreamer->emitIntValue(
Size, PtrSize);
3845 Asm->OutStreamer->AddComment(
"ARange terminator");
3846 Asm->OutStreamer->emitIntValue(0, PtrSize);
3847 Asm->OutStreamer->emitIntValue(0, PtrSize);
3855 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
3856 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_startx_endx,
3858 List.CU->getCUNode()->getRangesBaseAddress() ||
3870 return !Pair.second->getCUNode()->isDebugDirectivesOnly();
3873 Asm->OutStreamer->switchSection(Section);
3883 Asm->OutStreamer->emitLabel(TableEnd);
3888void DwarfDebug::emitDebugRanges() {
3891 emitDebugRangesImpl(Holder,
3893 ?
Asm->getObjFileLowering().getDwarfRnglistsSection()
3894 :
Asm->getObjFileLowering().getDwarfRangesSection());
3897void DwarfDebug::emitDebugRangesDWO() {
3899 Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
3906 enum HeaderFlagMask {
3907#define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
3908#include "llvm/BinaryFormat/Dwarf.def"
3910 Asm->OutStreamer->AddComment(
"Macro information version");
3911 Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
3914 if (Asm->isDwarf64()) {
3915 Asm->OutStreamer->AddComment(
"Flags: 64 bit, debug_line_offset present");
3916 Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3918 Asm->OutStreamer->AddComment(
"Flags: 32 bit, debug_line_offset present");
3919 Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
3921 Asm->OutStreamer->AddComment(
"debug_line_offset");
3923 Asm->emitDwarfLengthOrOffset(0);
3925 Asm->emitDwarfSymbolReference(
CU.getLineTableStartSym());
3928void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes,
DwarfCompileUnit &U) {
3929 for (
auto *MN : Nodes) {
3933 emitMacroFile(*
F, U);
3939void DwarfDebug::emitMacro(
DIMacro &M) {
3940 StringRef
Name =
M.getName();
3941 StringRef
Value =
M.getValue();
3947 if (UseDebugMacroSection) {
3950 ? dwarf::DW_MACRO_define_strx
3951 : dwarf::DW_MACRO_undef_strx;
3954 Asm->OutStreamer->AddComment(
"Line Number");
3955 Asm->emitULEB128(
M.getLine());
3956 Asm->OutStreamer->AddComment(
"Macro String");
3958 InfoHolder.getStringPool().getIndexedEntry(*
Asm, Str).getIndex());
3961 ? dwarf::DW_MACRO_GNU_define_indirect
3962 : dwarf::DW_MACRO_GNU_undef_indirect;
3965 Asm->OutStreamer->AddComment(
"Line Number");
3966 Asm->emitULEB128(
M.getLine());
3967 Asm->OutStreamer->AddComment(
"Macro String");
3968 Asm->emitDwarfSymbolReference(
3969 InfoHolder.getStringPool().getEntry(*
Asm, Str).getSymbol());
3973 Asm->emitULEB128(
M.getMacinfoType());
3974 Asm->OutStreamer->AddComment(
"Line Number");
3975 Asm->emitULEB128(
M.getLine());
3976 Asm->OutStreamer->AddComment(
"Macro String");
3977 Asm->OutStreamer->emitBytes(Str);
3978 Asm->emitInt8(
'\0');
3982void DwarfDebug::emitMacroFileImpl(
3984 StringRef (*MacroFormToString)(
unsigned Form)) {
3986 Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
3987 Asm->emitULEB128(StartFile);
3988 Asm->OutStreamer->AddComment(
"Line Number");
3990 Asm->OutStreamer->AddComment(
"File Number");
3993 Asm->emitULEB128(getDwoLineTable(U)->getFile(
3995 Asm->OutContext.getDwarfVersion(),
F.getSource()));
3997 Asm->emitULEB128(
U.getOrCreateSourceID(&
F));
3999 Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
4000 Asm->emitULEB128(EndFile);
4007 if (UseDebugMacroSection)
4009 F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
4016void DwarfDebug::emitDebugMacinfoImpl(
MCSection *Section) {
4017 for (
const auto &
P : CUMap) {
4018 auto &TheCU = *
P.second;
4020 DwarfCompileUnit &
U = SkCU ? *SkCU : TheCU;
4022 DIMacroNodeArray Macros = CUNode->getMacros();
4025 Asm->OutStreamer->switchSection(Section);
4026 Asm->OutStreamer->emitLabel(
U.getMacroLabelBegin());
4027 if (UseDebugMacroSection)
4029 handleMacroNodes(Macros, U);
4030 Asm->OutStreamer->AddComment(
"End Of Macro List Mark");
4036void DwarfDebug::emitDebugMacinfo() {
4037 auto &ObjLower =
Asm->getObjFileLowering();
4038 emitDebugMacinfoImpl(UseDebugMacroSection
4039 ? ObjLower.getDwarfMacroSection()
4040 : ObjLower.getDwarfMacinfoSection());
4043void DwarfDebug::emitDebugMacinfoDWO() {
4044 auto &ObjLower =
Asm->getObjFileLowering();
4045 emitDebugMacinfoImpl(UseDebugMacroSection
4046 ? ObjLower.getDwarfMacroDWOSection()
4047 : ObjLower.getDwarfMacinfoDWOSection());
4052void DwarfDebug::initSkeletonUnit(
const DwarfUnit &U,
DIE &Die,
4053 std::unique_ptr<DwarfCompileUnit> NewU) {
4055 if (!CompilationDir.empty())
4056 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
4057 addGnuPubAttributes(*NewU, Die);
4059 SkeletonHolder.addUnit(std::move(NewU));
4064 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
4065 CU.getUniqueID(),
CU.getCUNode(),
Asm,
this, &SkeletonHolder,
4067 DwarfCompileUnit &NewCU = *OwnedUnit;
4068 NewCU.
setSection(
Asm->getObjFileLowering().getDwarfInfoSection());
4075 initSkeletonUnit(
CU, NewCU.
getUnitDie(), std::move(OwnedUnit));
4082void DwarfDebug::emitDebugInfoDWO() {
4090void DwarfDebug::emitDebugAbbrevDWO() {
4092 InfoHolder.emitAbbrevs(
Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
4095void DwarfDebug::emitDebugLineDWO() {
4097 SplitTypeUnitFileTable.Emit(
4098 *
Asm->OutStreamer, MCDwarfLineTableParams(),
4099 Asm->getObjFileLowering().getDwarfLineDWOSection());
4102void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
4104 InfoHolder.getStringPool().emitStringOffsetsTableHeader(
4105 *
Asm,
Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
4112void DwarfDebug::emitDebugStrDWO() {
4114 emitStringOffsetsTableHeaderDWO();
4116 MCSection *OffSec =
Asm->getObjFileLowering().getDwarfStrOffDWOSection();
4117 InfoHolder.emitStrings(
Asm->getObjFileLowering().getDwarfStrDWOSection(),
4122void DwarfDebug::emitDebugAddr() {
4123 AddrPool.emit(*
Asm,
Asm->getObjFileLowering().getDwarfAddrSection());
4129 const DICompileUnit *DIUnit =
CU.getCUNode();
4130 SplitTypeUnitFileTable.maybeSetRootFile(
4133 return &SplitTypeUnitFileTable;
4144 return Result.high();
4153 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
4156 auto Ins = TypeSignatures.try_emplace(CTy);
4158 CU.addDIETypeSignature(RefDie, Ins.first->second);
4163 bool TopLevelType = TypeUnitsUnderConstruction.empty();
4164 AddrPool.resetUsedFlag();
4166 auto OwnedUnit = std::make_unique<DwarfTypeUnit>(
4170 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
4172 NewTU.
addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
4173 CU.getSourceLanguage());
4177 Ins.first->second = Signature;
4185 if (!CompilationDir.empty())
4186 NewTU.
addString(UnitDie, dwarf::DW_AT_comp_dir, CompilationDir);
4187 NewTU.
addString(UnitDie, dwarf::DW_AT_dwo_name,
4188 Asm->TM.Options.MCOptions.SplitDwarfFile);
4192 ?
Asm->getObjFileLowering().getDwarfTypesDWOSection()
4193 :
Asm->getObjFileLowering().getDwarfInfoDWOSection();
4198 ?
Asm->getObjFileLowering().getDwarfTypesSection(Signature)
4199 :
Asm->getObjFileLowering().getDwarfInfoSection(Signature);
4202 CU.applyStmtList(UnitDie);
4213 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
4214 TypeUnitsUnderConstruction.clear();
4218 if (AddrPool.hasBeenUsed()) {
4219 AccelTypeUnitsDebugNames.clear();
4223 for (
const auto &
TU : TypeUnitsToAdd)
4224 TypeSignatures.erase(
TU.second);
4232 CU.updateAcceleratorTables(CTy->
getScope(), CTy, RefDie);
4238 for (
auto &
TU : TypeUnitsToAdd) {
4239 InfoHolder.computeSizeAndOffsetsForUnit(
TU.first.get());
4244 AccelDebugNames.addTypeUnitSignature(*
TU.first);
4246 AccelDebugNames.addTypeUnitSymbol(*
TU.first);
4249 AccelTypeUnitsDebugNames.convertDieToOffset();
4250 AccelDebugNames.addTypeEntries(AccelTypeUnitsDebugNames);
4251 AccelTypeUnitsDebugNames.clear();
4254 CU.addDIETypeSignature(RefDie, Signature);
4261template <
typename DataT>
4262void DwarfDebug::addAccelNameImpl(
4267 Unit.getUnitDie().getTag() == dwarf::DW_TAG_skeleton_unit || Name.empty())
4284 assert(((&Current == &AccelTypeUnitsDebugNames) ||
4285 ((&Current == &AccelDebugNames) &&
4286 (Unit.getUnitDie().getTag() != dwarf::DW_TAG_type_unit))) &&
4287 "Kind is CU but TU is being processed.");
4288 assert(((&Current == &AccelDebugNames) ||
4289 ((&Current == &AccelTypeUnitsDebugNames) &&
4290 (Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit))) &&
4291 "Kind is TU but CU is being processed.");
4294 Current.
addName(
Ref, Die, Unit.getUniqueID(),
4295 Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit);
4309 addAccelNameImpl(Unit, NameTableKind, AccelNames, Name, Die);
4318 addAccelNameImpl(Unit, NameTableKind, AccelObjC, Name, Die);
4325 addAccelNameImpl(Unit, NameTableKind, AccelNamespace, Name, Die);
4331 const DIE &Die,
char Flags) {
4332 addAccelNameImpl(Unit, NameTableKind, AccelTypes, Name, Die);
4336 return Asm->OutStreamer->getContext().getDwarfVersion();
4340 if (
Asm->getDwarfVersion() >= 4)
4341 return dwarf::Form::DW_FORM_sec_offset;
4342 assert((!
Asm->isDwarf64() || (
Asm->getDwarfVersion() == 3)) &&
4343 "DWARF64 is not defined prior DWARFv3");
4344 return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
4345 : dwarf::Form::DW_FORM_data4;
4349 return SectionLabels.lookup(S);
4353 if (SectionLabels.insert(std::make_pair(&S->
getSection(), S)).second)
4358std::optional<MD5::MD5Result>
4362 return std::nullopt;
4363 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
4365 return std::nullopt;
4370 std::string ChecksumString =
fromHex(Checksum->Value);
4387 if (
MBB.getAlignment() ==
Align(1))
4390 auto *SP =
MBB.getParent()->getFunction().getSubprogram();
4397 auto PrevLoc =
Asm->OutStreamer->getContext().getCurrentDwarfLoc();
4398 if (PrevLoc.getLine()) {
4399 Asm->OutStreamer->emitDwarfLocDirective(
4400 PrevLoc.getFileNum(), 0, PrevLoc.getColumn(), 0, 0, 0,
StringRef());
4402 Asm->OutStreamer->getCurrentSectionOnly());
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static unsigned getDwarfVersion(const MachineFunction &MF)
Resolve the DWARF version the way DwarfDebug does.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define clEnumVal(ENUMVAL, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isObjCClass(StringRef Name)
static cl::opt< bool > NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, cl::desc("Disable emission .debug_ranges section."), cl::init(false))
static void finishCallSiteParams(ValT Val, const DIExpression *Expr, ArrayRef< FwdRegParamInfo > DescribedParams, ParamSet &Params)
Emit call site parameter entries that are described by the given value and debug expression.
static cl::opt< bool > UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden, cl::desc("Emit the GNU .debug_macro format with DWARF <5"), cl::init(false))
static cl::opt< DefaultOnOff > DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden, cl::desc("Use inlined strings rather than string section."), cl::values(clEnumVal(Default, "Default for platform"), clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), cl::init(Default))
static bool validThroughout(LexicalScopes &LScopes, const MachineInstr *DbgValue, const MachineInstr *RangeEnd, const InstructionOrdering &Ordering)
Determine whether a singular DBG_VALUE is valid for the entirety of its enclosing lexical scope.
static cl::opt< bool > GenerateARangeSection("generate-arange-section", cl::Hidden, cl::desc("Generate dwarf aranges"), cl::init(false))
static cl::opt< LinkageNameOption > DwarfLinkageNames("dwarf-linkage-names", cl::Hidden, cl::desc("Which DWARF linkage-name attributes to emit."), cl::values(clEnumValN(DefaultLinkageNames, "Default", "Default for platform"), clEnumValN(AllLinkageNames, "All", "All"), clEnumValN(AbstractLinkageNames, "Abstract", "Abstract subprograms")), cl::init(DefaultLinkageNames))
static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg, const DIExpression *Expr, ArrayRef< FwdRegParamInfo > ParamsToAdd)
Add Reg to the worklist, if it's not already present, and mark that the given parameter registers' va...
static cl::opt< bool > GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, cl::desc("Generate DWARF4 type units."), cl::init(false))
SmallSet< MCRegUnit, 16 > ClobberedRegUnitSet
Container for the set of register units known to be clobbered on the path to a call site.
static cl::opt< bool > KeyInstructionsAreStmts("dwarf-use-key-instructions", cl::Hidden, cl::init(true), cl::desc("Set to false to ignore Key Instructions metadata"))
Set to false to ignore Key Instructions metadata.
static bool interpretNextInstr(const MachineInstr *CurMI, FwdRegWorklist &ForwardedRegWorklist, ParamSet &Params, ClobberedRegUnitSet &ClobberedRegUnits)
static SmallVectorImpl< DwarfCompileUnit::GlobalExpr > & sortGlobalExprs(SmallVectorImpl< DwarfCompileUnit::GlobalExpr > &GVEs)
Sort and unique GVEs by comparing their fragment offset.
static bool isLangCaseSensitive(const DISourceLanguageName &Lang)
static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, const DIE *Die)
computeIndexValue - Compute the gdb index value for the DIE and CU.
static uint64_t getFragmentOffsetInBits(const DIExpression &Expr)
static cl::opt< DefaultOnOff > DwarfOpConvert("dwarf-op-convert", cl::Hidden, cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"), cl::values(clEnumVal(Default, "Default for platform"), clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), cl::init(Default))
static std::pair< const MachineInstr *, bool > findPrologueEndLoc(const MachineFunction *MF)
static void collectCallSiteParameters(const MachineInstr *CallMI, ParamSet &Params)
Try to interpret values loaded into registers that forward parameters for CallMI.
static MCSymbol * emitRnglistsTableHeader(AsmPrinter *Asm, const DwarfFile &Holder)
static cl::opt< bool > SplitDwarfCrossCuReferences("split-dwarf-cross-cu-references", cl::Hidden, cl::desc("Enable cross-cu references in DWO files"), cl::init(false))
static cl::opt< bool > UseDwarfRangesBaseAddressSpecifier("use-dwarf-ranges-base-address-specifier", cl::Hidden, cl::desc("Use base address specifiers in debug_ranges"), cl::init(false))
MapVector< Register, SmallVector< FwdRegParamInfo, 2 > > FwdRegWorklist
Register worklist for finding call site values.
static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List)
static constexpr unsigned ULEB128PadSize
static cl::opt< DefaultOnOff > DwarfSectionsAsReferences("dwarf-sections-as-references", cl::Hidden, cl::desc("Use sections+offset as references rather than labels."), cl::values(clEnumVal(Default, "Default for platform"), clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), cl::init(Default))
static AccelTableKind computeAccelTableKind(unsigned DwarfVersion, bool GenerateTypeUnits, DebuggerKind Tuning, const Triple &TT)
static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R, const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair, unsigned StartxLength, unsigned StartxEndx, unsigned EndOfList, StringRef(*StringifyEnum)(unsigned), bool ShouldUseBaseAddress, PayloadEmitter EmitPayload)
static void forBothCUs(DwarfCompileUnit &CU, Func F)
static MCSymbol * emitLoclistsTableHeader(AsmPrinter *Asm, const DwarfDebug &DD)
static const DILocalScope * getRetainedNodeScope(const MDNode *N)
static const DIExpression * combineDIExpressions(const DIExpression *Original, const DIExpression *Addition)
Append the expression Addition to Original and return the result.
static void interpretValues(const MachineInstr *CurMI, FwdRegWorklist &ForwardedRegWorklist, ParamSet &Params, ClobberedRegUnitSet &ClobberedRegUnits)
Interpret values loaded into registers by CurMI.
static cl::opt< DefaultOnOff > UnknownLocations("use-unknown-locations", cl::Hidden, cl::desc("Make an absence of debug location information explicit."), cl::values(clEnumVal(Default, "At top of block or after label"), clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")), cl::init(Default))
static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col, const MDNode *S, unsigned Flags, unsigned CUID, uint16_t DwarfVersion, ArrayRef< std::unique_ptr< DwarfCompileUnit > > DCUs, StringRef Comment={})
Register a source line with debug info.
static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD, const DwarfCompileUnit &CU, uint16_t DwarfVersion)
Emit the header of a DWARF 5 macro section, or the GNU extension for DWARF 4.
static cl::opt< AccelTableKind > AccelTables("accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), cl::values(clEnumValN(AccelTableKind::Default, "Default", "Default for platform"), clEnumValN(AccelTableKind::None, "Disable", "Disabled."), clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), cl::init(AccelTableKind::Default))
static cl::opt< DwarfDebug::MinimizeAddrInV5 > MinimizeAddrInV5Option("minimize-addr-in-v5", cl::Hidden, cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more " "address pool entry sharing to reduce relocations/object size"), cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default", "Default address minimization strategy"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges", "Use rnglists for contiguous ranges if that allows " "using a pre-existing base address"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions, "Expressions", "Use exprloc addrx+offset expressions for any " "address with a prior base address"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Form, "Form", "Use addrx+offset extension form for any address " "with a prior base address"), clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled", "Stuff")), cl::init(DwarfDebug::MinimizeAddrInV5::Default))
static StringRef getObjCMethodName(StringRef In)
static DbgValueLoc getDebugLocValue(const MachineInstr *MI)
Get .debug_loc entry for the instruction range starting at MI.
static void getObjCClassCategory(StringRef In, StringRef &Class, StringRef &Category)
const HexagonInstrInfo * TII
Module.h This file contains the declarations for the Module class.
#define DWARF2_FLAG_IS_STMT
#define DWARF2_FLAG_PROLOGUE_END
#define DWARF2_FLAG_EPILOGUE_BEGIN
Register const TargetRegisterInfo * TRI
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static const MCPhysReg CalleeSavedReg
SmallVector< MachineOperand, 4 > Cond
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
std::unique_ptr< MCStreamer > && Streamer
This file describes how to lower LLVM code to machine code.
static bool isCopy(MachineInstr *MI)
static const uint32_t IV[8]
Class recording the (high level) value of a variable.
Class for arbitrary precision integers.
This class holds an abstract representation of an Accelerator Table, consisting of a sequence of buck...
void addName(DwarfStringPoolEntryRef Name, Types &&... Args)
unsigned getIndex(const MCSymbol *Sym, bool TLS=false)
Returns the index into the address pool with the given label/symbol.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
std::vector< T > vec() const
This class is intended to be used as a driving class for all asm writers.
DwarfDebug * getDwarfDebug()
TargetMachine & TM
Target machine description.
MachineFunction * MF
The current machine function.
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
const MCAsmInfo & MAI
Target Asm Printer information.
uint16_t getDwarfVersion() const
virtual void emitInt8(uint8_t Byte, const Twine &Comment="")=0
Basic type, like 'int' or 'float'.
bool getDebugInfoForProfiling() const
bool isDebugDirectivesOnly() const
StringRef getFlags() const
static LLVM_ABI std::optional< DebugNameTableKind > getNameTableKind(StringRef Str)
unsigned getRuntimeVersion() const
bool getSplitDebugInlining() const
StringRef getSysRoot() const
StringRef getProducer() const
DISourceLanguageName getSourceLanguage() const
uint64_t getDWOId() const
StringRef getSplitDebugFilename() const
static LLVM_ABI std::optional< DebugEmissionKind > getEmissionKind(StringRef Str)
void setSection(MCSection *Section)
Set the section that this DIEUnit will be emitted into.
A structured debug information entry.
LLVM_ABI DIEValue findAttribute(dwarf::Attribute Attribute) const
Find a value in the DIE with the attribute given.
LLVM_ABI const DIE * getUnitDie() const
Climb up the parent chain to get the unit DIE that this DIE belongs to.
dwarf::Tag getTag() const
Holds a DIExpression and keeps track of how many operands have been consumed so far.
A lightweight wrapper around an expression operand.
static LLVM_ABI DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
unsigned getNumElements() const
LLVM_ABI bool isImplicit() const
Return whether this is an implicit location description.
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
static LLVM_ABI std::optional< const DIExpression * > convertToNonVariadicExpression(const DIExpression *Expr)
If Expr is a valid single-location expression, i.e.
ArrayRef< uint64_t > getElements() const
LLVM_ABI bool isValid() const
LLVM_ABI DILocalScope * getNonLexicalBlockFileScope() const
Get the first non DILexicalBlockFile scope of this scope.
uint64_t getAtomGroup() const
uint8_t getAtomRank() const
DIMacroNodeArray getElements() const
Tagged DWARF-like metadata node.
StringRef getFilename() const
StringRef getDirectory() const
std::optional< StringRef > getSource() const
Wrapper structure that holds source language identity metadata that includes language name,...
bool hasVersionedName() const
uint16_t getName() const
Returns a versioned or unversioned language name.
Subprogram description. Uses SubclassData1.
static LLVM_ABI DILocalScope * getRetainedNodeScope(MDNode *N)
DIScope * getScope() const
DIScope * getScope() const
Encoding
Size and signedness of expression operations' operands.
Used for tracking debug info about call site parameters.
This class is defined as the common parent of DbgVariable and DbgLabel such that it could levarage po...
SmallVector< Entry, 4 > Entries
A single location or constant within a variable location description, with either a single entry (wit...
The location of a single variable, composed of an expression and 0 or more DbgValueLocEntries.
const DILocalVariable * getVariable() const
const DIType * getType() const
const MachineInstr * CurMI
If nonnull, stores the current machine instruction we're processing.
AsmPrinter * Asm
Target of debug info emission.
MCSymbol * getLabelBeforeInsn(const MachineInstr *MI)
Return Label preceding the instruction.
MachineModuleInfo * MMI
Collected machine module information.
DebugLoc PrevInstLoc
Previous instruction's location information.
MCSymbol * getLabelAfterInsn(const MachineInstr *MI)
Return Label immediately following the instruction.
DebugHandlerBase(AsmPrinter *A)
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
const MachineBasicBlock * PrevInstBB
void requestLabelAfterInsn(const MachineInstr *MI)
Ensure that a label will be emitted after MI.
DbgValueHistoryMap DbgValues
History of DBG_VALUE and clobber instructions for each user variable.
DbgLabelInstrMap DbgLabels
Mapping of inlined labels and DBG_LABEL machine instruction.
void beginModule(Module *M) override
const InstructionOrdering & getInstOrdering() const
void requestLabelBeforeInsn(const MachineInstr *MI)
Ensure that a label will be emitted before MI.
const MachineBasicBlock * EpilogBeginBlock
This block includes epilogue instructions.
const MachineInstr * PrologEndLoc
This location indicates end of function prologue and beginning of function body.
DwarfExpression implementation for .debug_loc entries.
void finalize(const AsmPrinter &AP, DebugLocStream::ListBuilder &List, const DIBasicType *BT, DwarfCompileUnit &TheCU)
Lower this entry into a DWARF expression.
Builder for DebugLocStream entries.
Builder for DebugLocStream lists.
ArrayRef< Entry > getEntries(const List &L) const
LLVM_ABI unsigned getLine() const
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
void addRange(RangeSpan Range)
addRange - Add an address range to the list of ranges for this unit.
DIE & constructSubprogramScopeDIE(const DISubprogram *Sub, const Function &F, LexicalScope *Scope, MCSymbol *LineTableSym)
Construct a DIE for this subprogram scope.
void createAbstractEntity(const DINode *Node, LexicalScope *Scope)
DwarfCompileUnit * getSkeleton() const
void setSkeleton(DwarfCompileUnit &Skel)
Set the skeleton unit associated with this unit.
const StringMap< const DIE * > & getGlobalNames() const
DbgEntity * getExistingAbstractEntity(const DINode *Node)
const StringMap< const DIE * > & getGlobalTypes() const
bool hasDwarfPubSections() const
Collects and handles dwarf debug information.
bool useSegmentedStringOffsetsTable() const
Returns whether to generate a string offsets table with (possibly shared) contributions from each CU ...
virtual bool shouldResetBaseAddress(const MCSection &Section) const
Whether the target requires resetting the base address in range/loc lists.
std::optional< MD5::MD5Result > getMD5AsBytes(const DIFile *File) const
If the File has an MD5 checksum, return it as an MD5Result allocated in the MCContext.
virtual bool shouldAttachCompileUnitRanges() const
Whether to attach ranges/low_pc to the compile unit DIE in endModule.
bool emitDebugEntryValues() const
uint16_t getDwarfVersion() const
Returns the Dwarf Version.
void emitDebugLocEntry(ByteStreamer &Streamer, const DebugLocStream::Entry &Entry, const DwarfCompileUnit *CU)
Emit an entry for the debug loc section.
void addAccelNamespace(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
void setCurrentDWARF5AccelTable(const DWARF5AccelTableKind Kind)
Sets the current DWARF5AccelTable to use.
bool alwaysUseRanges(const DwarfCompileUnit &) const
Returns whether range encodings should be used for single entry range lists.
void beginModule(Module *M) override
Emit all Dwarf sections that should come prior to the content.
void addSubprogramNames(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, const DISubprogram *SP, DIE &Die)
bool useAllLinkageNames() const
Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
void insertSectionLabel(const MCSymbol *S)
void addAccelObjC(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
dwarf::Form getDwarfSectionOffsetForm() const
Returns a suitable DWARF form to represent a section offset, i.e.
bool useAppleExtensionAttributes() const
void skippedNonDebugFunction() override
void addArangeLabel(SymbolCU SCU)
Add a label so that arange data can be generated for it.
virtual void finishTargetUnitAttributes(const DICompileUnit &DIUnit, DwarfCompileUnit &NewCU)
Target-specific compile unit attribute finalization.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
AddressPool & getAddressPool()
DWARF5AccelTable & getCurrentDWARF5AccelTable()
Returns either CU or TU DWARF5AccelTable.
bool useSectionsAsReferences() const
Returns whether to use sections as labels rather than temp symbols.
const DebugLocStream & getDebugLocs() const
Returns the entries for the .debug_loc section.
void applyDwarfVersion(unsigned DwarfVersion)
Select DwarfVersion and (re)compute all state derived from it.
bool shareAcrossDWOCUs() const
void terminateLineTable(const DwarfCompileUnit *CU)
Terminate the line table by adding the last range label.
void endFunctionImpl(const MachineFunction *MF) override
Gather and emit post-function debug information.
DwarfCompileUnit & getOrCreateAbstractSubprogramCU(const DISubprogram *SP, DwarfCompileUnit &SrcCU)
Find the matching DwarfCompileUnit for the given SP referenced from SrcCU.
void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry, const DwarfCompileUnit *CU)
Emit the location for a debug loc entry, including the size header.
const SmallVectorImpl< std::unique_ptr< DwarfCompileUnit > > & getUnits()
const MCSymbol * getSectionLabel(const MCSection *S)
static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, const DbgValueLoc &Value, DwarfExpression &DwarfExpr)
bool useSplitDwarf() const
Returns whether or not to change the current debug info for split DWARF.
virtual void initializeTargetDebugInfo(const MachineFunction &MF)
Target-specific debug info initialization at function start.
unsigned getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU)
Get Dwarf compile unit ID for line table.
const MachineInstr * emitInitialLocDirective(const MachineFunction &MF, unsigned CUID)
Emits inital debug location directive.
bool useRangesSection() const
Returns whether ranges section should be emitted.
void addAccelName(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
virtual void recordTargetSourceLine(const DebugLoc &DL, unsigned Flags)
Target-specific source line recording.
bool isLexicalScopeDIENull(LexicalScope *Scope)
A helper function to check whether the DIE for a given Scope is going to be null.
void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier, DIE &Die, const DICompositeType *CTy)
Add a DIE to the set of types that we're going to pull into type units.
DwarfFile InfoHolder
Holder for the file specific debug information.
void endModule() override
Emit all Dwarf sections that should come after the content.
void addAccelType(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die, char Flags)
void beginCodeAlignment(const MachineBasicBlock &MBB) override
Process beginning of code alignment.
DwarfDebug(AsmPrinter *A)
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
AccelTableKind getAccelTableKind() const
Returns what kind (if any) of accelerator tables to emit.
static uint64_t makeTypeSignature(StringRef Identifier)
Perform an MD5 checksum of Identifier and return the lower 64 bits.
Base class containing the logic for constructing DWARF expressions independently of whether they are ...
void setLocation(const MachineLocation &Loc, const DIExpression *DIExpr)
Set the location (Loc) and DIExpression (DIExpr) to describe.
bool canAddGlobalAddress() const
Whether addGlobalAddress() can spell a global's address at all.
virtual void disableTemporaryBuffer()=0
Disable emission to the temporary buffer.
virtual unsigned getTemporaryBufferSize()=0
Return the emitted size, in number of bytes, for the data stored in the temporary buffer.
bool addGlobalAddress(const GlobalValue *GV, int64_t Offset)
Emit the address of GV displaced by Offset as an implicit location description, i....
void finalize()
This needs to be called last to commit any pending changes.
void addFragmentOffset(const DIExpression *Expr)
If applicable, emit an empty DW_OP_piece / DW_OP_bit_piece to advance to the fragment described by Ex...
void setMemoryLocationKind()
Lock this down to become a memory location description.
bool addExpression(DIExpressionCursor &&Expr)
Emit all remaining operations in the DIExpressionCursor.
std::optional< uint8_t > TagOffset
void addBooleanConstant(int64_t Value)
Emit a boolean constant.
void addConstantFP(const APFloat &Value, const AsmPrinter &AP)
Emit an floating point constant.
bool addMachineRegExpression(const TargetRegisterInfo &TRI, DIExpressionCursor &Expr, llvm::Register MachineReg, unsigned FragmentOffsetInBits=0)
Emit a machine register location.
void addUnsignedConstant(uint64_t Value)
Emit an unsigned constant.
void addImplicitValue(const APInt &Value, const AsmPrinter &AP)
Emit an implicit value.
void addSignedConstant(int64_t Value)
Emit a signed constant.
virtual void commitTemporaryBuffer()=0
Commit the data stored in the temporary buffer to the main output.
void addWasmLocation(unsigned Index, uint64_t Offset)
Emit location information expressed via WebAssembly location + offset The Index is an identifier for ...
virtual void enableTemporaryBuffer()=0
Start emitting data to the temporary buffer.
void beginEntryValueExpression(DIExpressionCursor &ExprCursor)
Begin emission of an entry value dwarf operation.
void setRnglistsTableBaseSym(MCSymbol *Sym)
void emitUnits(bool UseOffsets)
Emit all of the units to the section listed with the given abbreviation section.
const SmallVectorImpl< RangeSpanList > & getRangeLists() const
getRangeLists - Get the vector of range lists.
MCSymbol * getStringOffsetsStartSym() const
MCSymbol * getRnglistsTableBaseSym() const
DwarfStringPool & getStringPool()
Returns the string pool.
void emitAbbrevs(MCSection *)
Emit a set of abbreviations to the specific section.
void emitStrings(MCSection *StrSection, MCSection *OffsetSection=nullptr, bool UseRelativeOffsets=false)
Emit all of the strings to the section given.
DwarfStringPoolEntryRef: Dwarf string pool entry reference.
LLVM_ABI_FOR_TEST EntryRef getEntry(AsmPrinter &Asm, StringRef Str)
Get a reference to an entry in the string pool.
LLVM_ABI_FOR_TEST void emitStringOffsetsTableHeader(AsmPrinter &Asm, MCSection *OffsetSection, MCSymbol *StartSym)
void setTypeSignature(uint64_t Signature)
void setType(const DIE *Ty)
This dwarf writer support class manages information associated with a source file.
void addStringOffsetsStart()
Add the DW_AT_str_offsets_base attribute to the unit DIE.
void addUInt(DIEValueList &Die, dwarf::Attribute Attribute, std::optional< dwarf::Form > Form, uint64_t Integer)
Add an unsigned integer attribute data and value.
void addString(DIE &Die, dwarf::Attribute Attribute, StringRef Str)
Add a string attribute data and value.
DIE * createTypeDIE(const DIScope *Context, DIE &ContextDIE, const DIType *Ty)
Creates type DIE with specific context.
const DICompileUnit * getCUNode() const
void addSectionLabel(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Label, const MCSymbol *Sec)
Add a Dwarf section label attribute data and value.
void addFlag(DIE &Die, dwarf::Attribute Attribute)
Add a flag that is true to the DIE.
unsigned getUniqueID() const
Gets Unique ID for this unit.
DISubprogram * getSubprogram() const
Get the attached subprogram.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool isTailCall(const MachineInstr &MI) const override
Record instruction ordering so we can query their relative positions within a function.
This class is used to track scope information.
SmallVectorImpl< InsnRange > & getRanges()
const DILocalScope * getScopeNode() const
This class provides interface to collect and use lexical scoping information from machine instruction...
LLVM_ABI LexicalScope * findLexicalScope(const DILocation *DL)
Find lexical scope, either regular or inlined, for the given DebugLoc.
LexicalScope * findAbstractScope(const DILocalScope *N)
Find an abstract scope or return null.
Single(DbgValueLoc ValueLoc)
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
static LLVM_ABI void make(MCStreamer *MCOS, MCSection *Section)
MCSection * getDwarfLoclistsSection() const
MCSection * getDwarfRangesSection() const
MCSection * getDwarfMacroSection() const
MCSection * getDwarfMacinfoDWOSection() const
MCSection * getDwarfMacinfoSection() const
MCSection * getDwarfMacroDWOSection() const
static constexpr unsigned NoRegister
Instances of this class represent a uniqued identifier for a section in the current translation unit.
MCSymbol * getBeginSymbol()
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
uint32_t getIndex() const
Get the (implementation defined) index.
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
succ_iterator succ_begin()
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< const MachineInstr, true > const_reverse_iterator
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const CallSiteInfoMap & getCallSitesInfo() const
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
unsigned getNumOperands() const
Retuns the total number of operands.
bool hasDelaySlot(QueryType Type=AnyInBundle) const
Returns true if the specified instruction has a delay slot which must be filled by the code generator...
mop_range uses()
Returns all operands which may be register uses.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
bool isDebugValue() const
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
Register getReg() const
getReg - Returns the register number.
This class implements a map that also provides access to all stored values in a deterministic order.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
A Module instance is used to store all the information related to an LLVM module.
Wrapper class representing virtual and physical registers.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
bool empty() const
Determine if the SetVector is empty or not.
A SetVector that performs no allocations if smaller than a certain size.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
void insert_range(Range &&R)
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
TargetInstrInfo - Interface to description of machine instruction set.
const Triple & getTargetTriple() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
Triple - Helper class for working with autoconf configuration names.
bool isWasm() const
Tests whether the target is wasm (32- and 64-bit).
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM Value Representation.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
reverse_self_iterator getReverseIterator()
self_iterator getIterator()
A raw_ostream that writes to an SmallVector or SmallString.
LLVM_ABI StringRef RangeListEncodingString(unsigned Encoding)
LLVM_ABI StringRef GDBIndexEntryLinkageString(GDBIndexEntryLinkage Linkage)
LLVM_ABI StringRef MacroString(unsigned Encoding)
LLVM_ABI StringRef LocListEncodingString(unsigned Encoding)
LLVM_ABI StringRef GnuMacroString(unsigned Encoding)
LLVM_ABI StringRef MacinfoString(unsigned Encoding)
LLVM_ABI StringRef OperationEncodingString(unsigned Encoding)
LLVM_ABI StringRef GDBIndexEntryKindString(GDBIndexEntryKind Kind)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
bool isCPlusPlus(SourceLanguage S)
@ DW_ARANGES_VERSION
Section version number for .debug_aranges.
@ DW_PUBNAMES_VERSION
Section version number for .debug_pubnames.
@ DWARF_VERSION
Other constants.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
LLVM_ABI MCSymbol * emitListsTableHeaderStart(MCStreamer &S)
NodeAddr< InstrNode * > Instr
This is an optimization pass for GlobalISel generic memory operations.
bool operator<(int64_t V1, const APSInt &V2)
MachineBasicBlock::instr_iterator getBundleStart(MachineBasicBlock::instr_iterator I)
Returns an iterator to the first instruction in the bundle containing I.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
std::string fromHex(StringRef Input)
Convert hexadecimal string Input to its binary representation. The return string is half the size of ...
RelativeUniformCounterPtr Values
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool isRangeRelaxable(const MCSymbol *Begin, const MCSymbol *End)
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
auto cast_or_null(const Y &Val)
auto unique(Range &&R, Predicate P)
bool isa_and_nonnull(const Y &Val)
SmallVector< DbgCallSiteParam, 4 > ParamSet
Collection used for storing debug call site parameters.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void sort(IteratorTy Start, IteratorTy End)
AccelTableKind
The kind of accelerator tables we should emit.
@ Default
Platform default.
@ Apple
.apple_names, .apple_namespaces, .apple_types, .apple_objc.
@ Dwarf
DWARF v5 .debug_names.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
MachineBasicBlock::instr_iterator getBundleEnd(MachineBasicBlock::instr_iterator I)
Returns an iterator pointing beyond the bundle containing I.
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
@ Ref
The access may reference the value stored in memory.
auto remove_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly.
void emitAppleAccelTable(AsmPrinter *Asm, AccelTable< DataT > &Contents, StringRef Prefix, const MCSymbol *SecBegin)
Emit an Apple Accelerator Table consisting of entries in the specified AccelTable.
DWARFExpression::Operation Op
OutputIt copy(R &&Range, OutputIt Out)
LLVM_ABI void emitDWARF5AccelTable(AsmPrinter *Asm, DWARF5AccelTable &Contents, const DwarfDebug &DD, ArrayRef< std::unique_ptr< DwarfCompileUnit > > CUs)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
DebuggerKind
Identify a debugger for "tuning" the debug info.
@ LLDB
Tune debug info for lldb.
@ End
Run the machine verifier once, at the end of the pipeline.
Implement std::hash so that hash_code can be used in STL containers.
Represents a parameter whose call site value can be described by applying a debug expression to a reg...
uint64_t ParamReg
The described parameter register.
const DIExpression * Expr
Debug expression that has been built up when walking through the instruction chain that produces the ...
This struct is a compact representation of a valid (non-zero power of two) alignment.
A pair of GlobalVariable and DIExpression.
Represents an entry-value location, or a fragment of one.
This struct describes the address of a global, displaced by a constant.
void addFrameIndexExpr(const DIExpression *Expr, int FI)
std::set< FrameIndexExpr > FrameIndexExprs
const std::set< FrameIndexExpr > & getFrameIndexExprs() const
Get the FI entries, sorted by fragment offset.
A MapVector that performs no allocations if smaller than a certain size.
Helper used to pair up a symbol and its DWARF compile unit.
This struct describes target specific location.
Describes an entry of the various gnu_pub* debug sections.