DwarfDebug.cpp revision 344779
1327952Sdim//===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This file contains support for writing dwarf debug info into asm files. 11193323Sed// 12193323Sed//===----------------------------------------------------------------------===// 13204961Srdivacky 14280031Sdim#include "DwarfDebug.h" 15276479Sdim#include "ByteStreamer.h" 16261991Sdim#include "DIEHash.h" 17288943Sdim#include "DebugLocEntry.h" 18327952Sdim#include "DebugLocStream.h" 19280031Sdim#include "DwarfCompileUnit.h" 20280031Sdim#include "DwarfExpression.h" 21327952Sdim#include "DwarfFile.h" 22276479Sdim#include "DwarfUnit.h" 23327952Sdim#include "llvm/ADT/APInt.h" 24327952Sdim#include "llvm/ADT/DenseMap.h" 25327952Sdim#include "llvm/ADT/DenseSet.h" 26327952Sdim#include "llvm/ADT/MapVector.h" 27249423Sdim#include "llvm/ADT/STLExtras.h" 28327952Sdim#include "llvm/ADT/SmallVector.h" 29327952Sdim#include "llvm/ADT/StringRef.h" 30249423Sdim#include "llvm/ADT/Triple.h" 31327952Sdim#include "llvm/ADT/Twine.h" 32321369Sdim#include "llvm/BinaryFormat/Dwarf.h" 33341825Sdim#include "llvm/CodeGen/AccelTable.h" 34327952Sdim#include "llvm/CodeGen/AsmPrinter.h" 35280031Sdim#include "llvm/CodeGen/DIE.h" 36327952Sdim#include "llvm/CodeGen/LexicalScopes.h" 37327952Sdim#include "llvm/CodeGen/MachineBasicBlock.h" 38198090Srdivacky#include "llvm/CodeGen/MachineFunction.h" 39327952Sdim#include "llvm/CodeGen/MachineInstr.h" 40193323Sed#include "llvm/CodeGen/MachineModuleInfo.h" 41327952Sdim#include "llvm/CodeGen/MachineOperand.h" 42344779Sdim#include "llvm/CodeGen/TargetInstrInfo.h" 43327952Sdim#include "llvm/CodeGen/TargetRegisterInfo.h" 44327952Sdim#include "llvm/CodeGen/TargetSubtargetInfo.h" 45249423Sdim#include "llvm/IR/Constants.h" 46327952Sdim#include "llvm/IR/DebugInfoMetadata.h" 47327952Sdim#include "llvm/IR/DebugLoc.h" 48327952Sdim#include "llvm/IR/Function.h" 49327952Sdim#include "llvm/IR/GlobalVariable.h" 50249423Sdim#include "llvm/IR/Module.h" 51204961Srdivacky#include "llvm/MC/MCAsmInfo.h" 52327952Sdim#include "llvm/MC/MCContext.h" 53296417Sdim#include "llvm/MC/MCDwarf.h" 54198090Srdivacky#include "llvm/MC/MCSection.h" 55198090Srdivacky#include "llvm/MC/MCStreamer.h" 56204961Srdivacky#include "llvm/MC/MCSymbol.h" 57327952Sdim#include "llvm/MC/MCTargetOptions.h" 58327952Sdim#include "llvm/MC/MachineLocation.h" 59327952Sdim#include "llvm/MC/SectionKind.h" 60327952Sdim#include "llvm/Pass.h" 61327952Sdim#include "llvm/Support/Casting.h" 62207618Srdivacky#include "llvm/Support/CommandLine.h" 63198090Srdivacky#include "llvm/Support/Debug.h" 64198090Srdivacky#include "llvm/Support/ErrorHandling.h" 65261991Sdim#include "llvm/Support/MD5.h" 66327952Sdim#include "llvm/Support/MathExtras.h" 67193323Sed#include "llvm/Support/Timer.h" 68288943Sdim#include "llvm/Support/raw_ostream.h" 69341825Sdim#include "llvm/Target/TargetLoweringObjectFile.h" 70249423Sdim#include "llvm/Target/TargetMachine.h" 71249423Sdim#include "llvm/Target/TargetOptions.h" 72327952Sdim#include <algorithm> 73327952Sdim#include <cassert> 74327952Sdim#include <cstddef> 75327952Sdim#include <cstdint> 76327952Sdim#include <iterator> 77327952Sdim#include <string> 78327952Sdim#include <utility> 79327952Sdim#include <vector> 80309124Sdim 81193323Sedusing namespace llvm; 82193323Sed 83276479Sdim#define DEBUG_TYPE "dwarfdebug" 84276479Sdim 85261991Sdimstatic cl::opt<bool> 86261991SdimDisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, 87261991Sdim cl::desc("Disable debug info printing")); 88207618Srdivacky 89327952Sdimstatic cl::opt<bool> UseDwarfRangesBaseAddressSpecifier( 90327952Sdim "use-dwarf-ranges-base-address-specifier", cl::Hidden, 91327952Sdim cl::desc("Use base address specifiers in debug_ranges"), cl::init(false)); 92261991Sdim 93276479Sdimstatic cl::opt<bool> GenerateARangeSection("generate-arange-section", 94276479Sdim cl::Hidden, 95276479Sdim cl::desc("Generate dwarf aranges"), 96276479Sdim cl::init(false)); 97276479Sdim 98341825Sdimstatic cl::opt<bool> 99341825Sdim GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, 100341825Sdim cl::desc("Generate DWARF4 type units."), 101341825Sdim cl::init(false)); 102341825Sdim 103321369Sdimstatic cl::opt<bool> SplitDwarfCrossCuReferences( 104321369Sdim "split-dwarf-cross-cu-references", cl::Hidden, 105321369Sdim cl::desc("Enable cross-cu references in DWO files"), cl::init(false)); 106321369Sdim 107276479Sdimenum DefaultOnOff { Default, Enable, Disable }; 108243830Sdim 109314564Sdimstatic cl::opt<DefaultOnOff> UnknownLocations( 110314564Sdim "use-unknown-locations", cl::Hidden, 111314564Sdim cl::desc("Make an absence of debug location information explicit."), 112314564Sdim cl::values(clEnumVal(Default, "At top of block or after label"), 113314564Sdim clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")), 114314564Sdim cl::init(Default)); 115314564Sdim 116341825Sdimstatic cl::opt<AccelTableKind> AccelTables( 117341825Sdim "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), 118341825Sdim cl::values(clEnumValN(AccelTableKind::Default, "Default", 119341825Sdim "Default for platform"), 120341825Sdim clEnumValN(AccelTableKind::None, "Disable", "Disabled."), 121341825Sdim clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), 122341825Sdim clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), 123341825Sdim cl::init(AccelTableKind::Default)); 124341825Sdim 125261991Sdimstatic cl::opt<DefaultOnOff> 126341825SdimDwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden, 127341825Sdim cl::desc("Use inlined strings rather than string section."), 128261991Sdim cl::values(clEnumVal(Default, "Default for platform"), 129261991Sdim clEnumVal(Enable, "Enabled"), 130314564Sdim clEnumVal(Disable, "Disabled")), 131261991Sdim cl::init(Default)); 132234353Sdim 133341825Sdimstatic cl::opt<bool> 134341825Sdim NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, 135341825Sdim cl::desc("Disable emission .debug_ranges section."), 136341825Sdim cl::init(false)); 137341825Sdim 138341825Sdimstatic cl::opt<DefaultOnOff> DwarfSectionsAsReferences( 139341825Sdim "dwarf-sections-as-references", cl::Hidden, 140341825Sdim cl::desc("Use sections+offset as references rather than labels."), 141341825Sdim cl::values(clEnumVal(Default, "Default for platform"), 142341825Sdim clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), 143341825Sdim cl::init(Default)); 144341825Sdim 145309124Sdimenum LinkageNameOption { 146309124Sdim DefaultLinkageNames, 147309124Sdim AllLinkageNames, 148309124Sdim AbstractLinkageNames 149309124Sdim}; 150327952Sdim 151309124Sdimstatic cl::opt<LinkageNameOption> 152309124Sdim DwarfLinkageNames("dwarf-linkage-names", cl::Hidden, 153309124Sdim cl::desc("Which DWARF linkage-name attributes to emit."), 154309124Sdim cl::values(clEnumValN(DefaultLinkageNames, "Default", 155309124Sdim "Default for platform"), 156309124Sdim clEnumValN(AllLinkageNames, "All", "All"), 157309124Sdim clEnumValN(AbstractLinkageNames, "Abstract", 158314564Sdim "Abstract subprograms")), 159309124Sdim cl::init(DefaultLinkageNames)); 160296417Sdim 161314564Sdimstatic const char *const DWARFGroupName = "dwarf"; 162314564Sdimstatic const char *const DWARFGroupDescription = "DWARF Emission"; 163314564Sdimstatic const char *const DbgTimerName = "writer"; 164314564Sdimstatic const char *const DbgTimerDescription = "DWARF Debug Writer"; 165207618Srdivacky 166321369Sdimvoid DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) { 167288943Sdim BS.EmitInt8( 168288943Sdim Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op) 169288943Sdim : dwarf::OperationEncodingString(Op)); 170288943Sdim} 171288943Sdim 172321369Sdimvoid DebugLocDwarfExpression::emitSigned(int64_t Value) { 173288943Sdim BS.EmitSLEB128(Value, Twine(Value)); 174288943Sdim} 175288943Sdim 176321369Sdimvoid DebugLocDwarfExpression::emitUnsigned(uint64_t Value) { 177288943Sdim BS.EmitULEB128(Value, Twine(Value)); 178288943Sdim} 179288943Sdim 180309124Sdimbool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI, 181309124Sdim unsigned MachineReg) { 182288943Sdim // This information is not available while emitting .debug_loc entries. 183288943Sdim return false; 184288943Sdim} 185288943Sdim 186276479Sdimbool DbgVariable::isBlockByrefVariable() const { 187344779Sdim assert(getVariable() && "Invalid complex DbgVariable!"); 188344779Sdim return getVariable()->getType().resolve()->isBlockByrefStruct(); 189276479Sdim} 190276479Sdim 191288943Sdimconst DIType *DbgVariable::getType() const { 192344779Sdim DIType *Ty = getVariable()->getType().resolve(); 193221345Sdim // FIXME: isBlockByrefVariable should be reformulated in terms of complex 194221345Sdim // addresses instead. 195288943Sdim if (Ty->isBlockByrefStruct()) { 196221345Sdim /* Byref variables, in Blocks, are declared by the programmer as 197221345Sdim "SomeType VarName;", but the compiler creates a 198221345Sdim __Block_byref_x_VarName struct, and gives the variable VarName 199221345Sdim either the struct, or a pointer to the struct, as its type. This 200221345Sdim is necessary for various behind-the-scenes things the compiler 201221345Sdim needs to do with by-reference variables in blocks. 202249423Sdim 203221345Sdim However, as far as the original *programmer* is concerned, the 204221345Sdim variable should still have type 'SomeType', as originally declared. 205249423Sdim 206221345Sdim The following function dives into the __Block_byref_x_VarName 207221345Sdim struct to find the original type of the variable. This will be 208221345Sdim passed back to the code generating the type for the Debug 209221345Sdim Information Entry for the variable 'VarName'. 'VarName' will then 210221345Sdim have the original type 'SomeType' in its debug information. 211249423Sdim 212221345Sdim The original type 'SomeType' will be the type of the field named 213221345Sdim 'VarName' inside the __Block_byref_x_VarName struct. 214249423Sdim 215221345Sdim NOTE: In order for this to not completely fail on the debugger 216221345Sdim side, the Debug Information Entry for the variable VarName needs to 217221345Sdim have a DW_AT_location that tells the debugger how to unwind through 218221345Sdim the pointers and __Block_byref_x_VarName struct to find the actual 219221345Sdim value of the variable. The function addBlockByrefType does this. */ 220288943Sdim DIType *subType = Ty; 221288943Sdim uint16_t tag = Ty->getTag(); 222249423Sdim 223261991Sdim if (tag == dwarf::DW_TAG_pointer_type) 224288943Sdim subType = resolve(cast<DIDerivedType>(Ty)->getBaseType()); 225249423Sdim 226296417Sdim auto Elements = cast<DICompositeType>(subType)->getElements(); 227288943Sdim for (unsigned i = 0, N = Elements.size(); i < N; ++i) { 228296417Sdim auto *DT = cast<DIDerivedType>(Elements[i]); 229288943Sdim if (getName() == DT->getName()) 230288943Sdim return resolve(DT->getBaseType()); 231221345Sdim } 232212904Sdim } 233221345Sdim return Ty; 234221345Sdim} 235193323Sed 236314564SdimArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const { 237321369Sdim if (FrameIndexExprs.size() == 1) 238321369Sdim return FrameIndexExprs; 239321369Sdim 240327952Sdim assert(llvm::all_of(FrameIndexExprs, 241327952Sdim [](const FrameIndexExpr &A) { 242327952Sdim return A.Expr->isFragment(); 243327952Sdim }) && 244321369Sdim "multiple FI expressions without DW_OP_LLVM_fragment"); 245344779Sdim llvm::sort(FrameIndexExprs, 246341825Sdim [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool { 247341825Sdim return A.Expr->getFragmentInfo()->OffsetInBits < 248341825Sdim B.Expr->getFragmentInfo()->OffsetInBits; 249341825Sdim }); 250327952Sdim 251314564Sdim return FrameIndexExprs; 252314564Sdim} 253314564Sdim 254327952Sdimvoid DbgVariable::addMMIEntry(const DbgVariable &V) { 255327952Sdim assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry"); 256327952Sdim assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry"); 257344779Sdim assert(V.getVariable() == getVariable() && "conflicting variable"); 258344779Sdim assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location"); 259327952Sdim 260327952Sdim assert(!FrameIndexExprs.empty() && "Expected an MMI entry"); 261327952Sdim assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry"); 262327952Sdim 263327952Sdim // FIXME: This logic should not be necessary anymore, as we now have proper 264327952Sdim // deduplication. However, without it, we currently run into the assertion 265327952Sdim // below, which means that we are likely dealing with broken input, i.e. two 266327952Sdim // non-fragment entries for the same variable at different frame indices. 267327952Sdim if (FrameIndexExprs.size()) { 268327952Sdim auto *Expr = FrameIndexExprs.back().Expr; 269327952Sdim if (!Expr || !Expr->isFragment()) 270327952Sdim return; 271327952Sdim } 272327952Sdim 273327952Sdim for (const auto &FIE : V.FrameIndexExprs) 274327952Sdim // Ignore duplicate entries. 275327952Sdim if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) { 276327952Sdim return FIE.FI == Other.FI && FIE.Expr == Other.Expr; 277327952Sdim })) 278327952Sdim FrameIndexExprs.push_back(FIE); 279327952Sdim 280327952Sdim assert((FrameIndexExprs.size() == 1 || 281327952Sdim llvm::all_of(FrameIndexExprs, 282327952Sdim [](FrameIndexExpr &FIE) { 283327952Sdim return FIE.Expr && FIE.Expr->isFragment(); 284327952Sdim })) && 285327952Sdim "conflicting locations for variable"); 286327952Sdim} 287327952Sdim 288341825Sdimstatic AccelTableKind computeAccelTableKind(unsigned DwarfVersion, 289341825Sdim bool GenerateTypeUnits, 290341825Sdim DebuggerKind Tuning, 291341825Sdim const Triple &TT) { 292341825Sdim // Honor an explicit request. 293341825Sdim if (AccelTables != AccelTableKind::Default) 294341825Sdim return AccelTables; 295193323Sed 296341825Sdim // Accelerator tables with type units are currently not supported. 297341825Sdim if (GenerateTypeUnits) 298341825Sdim return AccelTableKind::None; 299341825Sdim 300341825Sdim // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5 301341825Sdim // always implies debug_names. For lower standard versions we use apple 302341825Sdim // accelerator tables on apple platforms and debug_names elsewhere. 303341825Sdim if (DwarfVersion >= 5) 304341825Sdim return AccelTableKind::Dwarf; 305341825Sdim if (Tuning == DebuggerKind::LLDB) 306341825Sdim return TT.isOSBinFormatMachO() ? AccelTableKind::Apple 307341825Sdim : AccelTableKind::Dwarf; 308341825Sdim return AccelTableKind::None; 309341825Sdim} 310341825Sdim 311206274SrdivackyDwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 312309124Sdim : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()), 313309124Sdim InfoHolder(A, "info_string", DIEValueAllocator), 314288943Sdim SkeletonHolder(A, "skel_string", DIEValueAllocator), 315341825Sdim IsDarwin(A->TM.getTargetTriple().isOSDarwin()) { 316314564Sdim const Triple &TT = Asm->TM.getTargetTriple(); 317234353Sdim 318296417Sdim // Make sure we know our "debugger tuning." The target option takes 319296417Sdim // precedence; fall back to triple-based defaults. 320296417Sdim if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default) 321296417Sdim DebuggerTuning = Asm->TM.Options.DebuggerTuning; 322296417Sdim else if (IsDarwin) 323296417Sdim DebuggerTuning = DebuggerKind::LLDB; 324296417Sdim else if (TT.isPS4CPU()) 325296417Sdim DebuggerTuning = DebuggerKind::SCE; 326296417Sdim else 327296417Sdim DebuggerTuning = DebuggerKind::GDB; 328296417Sdim 329341825Sdim if (DwarfInlinedStrings == Default) 330341825Sdim UseInlineStrings = TT.isNVPTX(); 331261991Sdim else 332341825Sdim UseInlineStrings = DwarfInlinedStrings == Enable; 333243830Sdim 334341825Sdim UseLocSection = !TT.isNVPTX(); 335341825Sdim 336309124Sdim HasAppleExtensionAttributes = tuneForLLDB(); 337309124Sdim 338321369Sdim // Handle split DWARF. 339321369Sdim HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty(); 340249423Sdim 341309124Sdim // SCE defaults to linkage names only for abstract subprograms. 342309124Sdim if (DwarfLinkageNames == DefaultLinkageNames) 343309124Sdim UseAllLinkageNames = !tuneForSCE(); 344296417Sdim else 345309124Sdim UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames; 346296417Sdim 347276479Sdim unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion; 348314564Sdim unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber 349276479Sdim : MMI->getModule()->getDwarfVersion(); 350341825Sdim // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2. 351341825Sdim DwarfVersion = 352341825Sdim TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION); 353261991Sdim 354341825Sdim UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX(); 355341825Sdim 356341825Sdim // Use sections as references. Force for NVPTX. 357341825Sdim if (DwarfSectionsAsReferences == Default) 358341825Sdim UseSectionsAsReferences = TT.isNVPTX(); 359341825Sdim else 360341825Sdim UseSectionsAsReferences = DwarfSectionsAsReferences == Enable; 361341825Sdim 362341825Sdim // Don't generate type units for unsupported object file formats. 363341825Sdim GenerateTypeUnits = 364341825Sdim A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits; 365341825Sdim 366341825Sdim TheAccelTableKind = computeAccelTableKind( 367341825Sdim DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple()); 368341825Sdim 369296417Sdim // Work around a GDB bug. GDB doesn't support the standard opcode; 370296417Sdim // SCE doesn't support GNU's; LLDB prefers the standard opcode, which 371296417Sdim // is defined as of DWARF 3. 372296417Sdim // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented 373296417Sdim // https://sourceware.org/bugzilla/show_bug.cgi?id=11616 374296417Sdim UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3; 375276479Sdim 376309124Sdim // GDB does not fully support the DWARF 4 representation for bitfields. 377309124Sdim UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB(); 378309124Sdim 379341825Sdim // The DWARF v5 string offsets table has - possibly shared - contributions 380341825Sdim // from each compile and type unit each preceded by a header. The string 381341825Sdim // offsets table used by the pre-DWARF v5 split-DWARF implementation uses 382341825Sdim // a monolithic string offsets table without any header. 383341825Sdim UseSegmentedStringOffsetsTable = DwarfVersion >= 5; 384341825Sdim 385288943Sdim Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion); 386193323Sed} 387193323Sed 388276479Sdim// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h. 389327952SdimDwarfDebug::~DwarfDebug() = default; 390276479Sdim 391234353Sdimstatic bool isObjCClass(StringRef Name) { 392234353Sdim return Name.startswith("+") || Name.startswith("-"); 393234353Sdim} 394234353Sdim 395234353Sdimstatic bool hasObjCCategory(StringRef Name) { 396276479Sdim if (!isObjCClass(Name)) 397276479Sdim return false; 398234353Sdim 399261991Sdim return Name.find(") ") != StringRef::npos; 400234353Sdim} 401234353Sdim 402234353Sdimstatic void getObjCClassCategory(StringRef In, StringRef &Class, 403234353Sdim StringRef &Category) { 404234353Sdim if (!hasObjCCategory(In)) { 405234353Sdim Class = In.slice(In.find('[') + 1, In.find(' ')); 406234353Sdim Category = ""; 407234353Sdim return; 408234353Sdim } 409234353Sdim 410234353Sdim Class = In.slice(In.find('[') + 1, In.find('(')); 411234353Sdim Category = In.slice(In.find('[') + 1, In.find(' ')); 412234353Sdim} 413234353Sdim 414234353Sdimstatic StringRef getObjCMethodName(StringRef In) { 415234353Sdim return In.slice(In.find(' ') + 1, In.find(']')); 416234353Sdim} 417234353Sdim 418234353Sdim// Add the various names to the Dwarf accelerator table names. 419344779Sdimvoid DwarfDebug::addSubprogramNames(const DICompileUnit &CU, 420344779Sdim const DISubprogram *SP, DIE &Die) { 421344779Sdim if (getAccelTableKind() != AccelTableKind::Apple && 422344779Sdim CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 423344779Sdim return; 424344779Sdim 425288943Sdim if (!SP->isDefinition()) 426276479Sdim return; 427234353Sdim 428341825Sdim if (SP->getName() != "") 429344779Sdim addAccelName(CU, SP->getName(), Die); 430341825Sdim 431341825Sdim // If the linkage name is different than the name, go ahead and output that as 432341825Sdim // well into the name table. Only do that if we are going to actually emit 433341825Sdim // that name. 434341825Sdim if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() && 435341825Sdim (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP))) 436344779Sdim addAccelName(CU, SP->getLinkageName(), Die); 437234353Sdim 438234353Sdim // If this is an Objective-C selector name add it to the ObjC accelerator 439234353Sdim // too. 440288943Sdim if (isObjCClass(SP->getName())) { 441234353Sdim StringRef Class, Category; 442288943Sdim getObjCClassCategory(SP->getName(), Class, Category); 443344779Sdim addAccelObjC(CU, Class, Die); 444234353Sdim if (Category != "") 445344779Sdim addAccelObjC(CU, Category, Die); 446234353Sdim // Also add the base method name to the name table. 447344779Sdim addAccelName(CU, getObjCMethodName(SP->getName()), Die); 448234353Sdim } 449234353Sdim} 450234353Sdim 451261991Sdim/// Check whether we should create a DIE for the given Scope, return true 452261991Sdim/// if we don't create a DIE (the corresponding DIE is null). 453261991Sdimbool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) { 454261991Sdim if (Scope->isAbstractScope()) 455261991Sdim return false; 456261991Sdim 457261991Sdim // We don't create a DIE if there is no Range. 458261991Sdim const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges(); 459261991Sdim if (Ranges.empty()) 460261991Sdim return true; 461261991Sdim 462261991Sdim if (Ranges.size() > 1) 463261991Sdim return false; 464261991Sdim 465261991Sdim // We don't create a DIE if we have a single Range and the end label 466261991Sdim // is null. 467280031Sdim return !getLabelAfterInsn(Ranges.front().second); 468261991Sdim} 469261991Sdim 470314564Sdimtemplate <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) { 471280031Sdim F(CU); 472280031Sdim if (auto *SkelCU = CU.getSkeleton()) 473314564Sdim if (CU.getCUNode()->getSplitDebugInlining()) 474314564Sdim F(*SkelCU); 475276479Sdim} 476276479Sdim 477321369Sdimbool DwarfDebug::shareAcrossDWOCUs() const { 478321369Sdim return SplitDwarfCrossCuReferences; 479321369Sdim} 480321369Sdim 481321369Sdimvoid DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, 482321369Sdim LexicalScope *Scope) { 483276479Sdim assert(Scope && Scope->getScopeNode()); 484276479Sdim assert(Scope->isAbstractScope()); 485276479Sdim assert(!Scope->getInlinedAt()); 486276479Sdim 487314564Sdim auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 488276479Sdim 489276479Sdim // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 490276479Sdim // was inlined from another compile unit. 491321369Sdim if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining()) 492321369Sdim // Avoid building the original CU if it won't be used 493321369Sdim SrcCU.constructAbstractSubprogramScopeDIE(Scope); 494321369Sdim else { 495321369Sdim auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 496321369Sdim if (auto *SkelCU = CU.getSkeleton()) { 497321369Sdim (shareAcrossDWOCUs() ? CU : SrcCU) 498321369Sdim .constructAbstractSubprogramScopeDIE(Scope); 499321369Sdim if (CU.getCUNode()->getSplitDebugInlining()) 500321369Sdim SkelCU->constructAbstractSubprogramScopeDIE(Scope); 501321369Sdim } else 502321369Sdim CU.constructAbstractSubprogramScopeDIE(Scope); 503321369Sdim } 504276479Sdim} 505276479Sdim 506344779Sdimvoid DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP, 507344779Sdim DwarfCompileUnit &CU, DIE &ScopeDIE, 508344779Sdim const MachineFunction &MF) { 509344779Sdim // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if 510344779Sdim // the subprogram is required to have one. 511344779Sdim if (!SP.areAllCallsDescribed() || !SP.isDefinition()) 512344779Sdim return; 513344779Sdim 514344779Sdim // Use DW_AT_call_all_calls to express that call site entries are present 515344779Sdim // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls 516344779Sdim // because one of its requirements is not met: call site entries for 517344779Sdim // optimized-out calls are elided. 518344779Sdim CU.addFlag(ScopeDIE, dwarf::DW_AT_call_all_calls); 519344779Sdim 520344779Sdim const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 521344779Sdim assert(TII && "TargetInstrInfo not found: cannot label tail calls"); 522344779Sdim 523344779Sdim // Emit call site entries for each call or tail call in the function. 524344779Sdim for (const MachineBasicBlock &MBB : MF) { 525344779Sdim for (const MachineInstr &MI : MBB.instrs()) { 526344779Sdim // Skip instructions which aren't calls. Both calls and tail-calling jump 527344779Sdim // instructions (e.g TAILJMPd64) are classified correctly here. 528344779Sdim if (!MI.isCall()) 529344779Sdim continue; 530344779Sdim 531344779Sdim // TODO: Add support for targets with delay slots (see: beginInstruction). 532344779Sdim if (MI.hasDelaySlot()) 533344779Sdim return; 534344779Sdim 535344779Sdim // If this is a direct call, find the callee's subprogram. 536344779Sdim const MachineOperand &CalleeOp = MI.getOperand(0); 537344779Sdim if (!CalleeOp.isGlobal()) 538344779Sdim continue; 539344779Sdim const Function *CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal()); 540344779Sdim if (!CalleeDecl || !CalleeDecl->getSubprogram()) 541344779Sdim continue; 542344779Sdim 543344779Sdim // TODO: Omit call site entries for runtime calls (objc_msgSend, etc). 544344779Sdim // TODO: Add support for indirect calls. 545344779Sdim 546344779Sdim bool IsTail = TII->isTailCall(MI); 547344779Sdim 548344779Sdim // For tail calls, no return PC information is needed. For regular calls, 549344779Sdim // the return PC is needed to disambiguate paths in the call graph which 550344779Sdim // could lead to some target function. 551344779Sdim const MCExpr *PCOffset = 552344779Sdim IsTail ? nullptr : getFunctionLocalOffsetAfterInsn(&MI); 553344779Sdim 554344779Sdim assert((IsTail || PCOffset) && "Call without return PC information"); 555344779Sdim LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> " 556344779Sdim << CalleeDecl->getName() << (IsTail ? " [tail]" : "") 557344779Sdim << "\n"); 558344779Sdim CU.constructCallSiteEntryDIE(ScopeDIE, *CalleeDecl->getSubprogram(), 559344779Sdim IsTail, PCOffset); 560344779Sdim } 561344779Sdim } 562344779Sdim} 563344779Sdim 564321369Sdimvoid DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const { 565327952Sdim if (!U.hasDwarfPubSections()) 566276479Sdim return; 567261991Sdim 568276479Sdim U.addFlag(D, dwarf::DW_AT_GNU_pubnames); 569193323Sed} 570193323Sed 571344779Sdimvoid DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit, 572344779Sdim DwarfCompileUnit &NewCU) { 573344779Sdim DIE &Die = NewCU.getUnitDie(); 574288943Sdim StringRef FN = DIUnit->getFilename(); 575193323Sed 576321369Sdim StringRef Producer = DIUnit->getProducer(); 577321369Sdim StringRef Flags = DIUnit->getFlags(); 578344779Sdim if (!Flags.empty() && !useAppleExtensionAttributes()) { 579321369Sdim std::string ProducerWithFlags = Producer.str() + " " + Flags.str(); 580321369Sdim NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags); 581321369Sdim } else 582321369Sdim NewCU.addString(Die, dwarf::DW_AT_producer, Producer); 583321369Sdim 584276479Sdim NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 585288943Sdim DIUnit->getSourceLanguage()); 586276479Sdim NewCU.addString(Die, dwarf::DW_AT_name, FN); 587251662Sdim 588341825Sdim // Add DW_str_offsets_base to the unit DIE, except for split units. 589341825Sdim if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 590341825Sdim NewCU.addStringOffsetsStart(); 591341825Sdim 592251662Sdim if (!useSplitDwarf()) { 593288943Sdim NewCU.initStmtList(); 594261991Sdim 595261991Sdim // If we're using split dwarf the compilation dir is going to be in the 596261991Sdim // skeleton CU and so we don't need to duplicate it here. 597261991Sdim if (!CompilationDir.empty()) 598276479Sdim NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 599261991Sdim 600276479Sdim addGnuPubAttributes(NewCU, Die); 601251662Sdim } 602193323Sed 603309124Sdim if (useAppleExtensionAttributes()) { 604309124Sdim if (DIUnit->isOptimized()) 605309124Sdim NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized); 606193323Sed 607309124Sdim StringRef Flags = DIUnit->getFlags(); 608309124Sdim if (!Flags.empty()) 609309124Sdim NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 610249423Sdim 611309124Sdim if (unsigned RVer = DIUnit->getRuntimeVersion()) 612309124Sdim NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 613309124Sdim dwarf::DW_FORM_data1, RVer); 614309124Sdim } 615193323Sed 616296417Sdim if (DIUnit->getDWOId()) { 617296417Sdim // This CU is either a clang module DWO or a skeleton CU. 618296417Sdim NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 619296417Sdim DIUnit->getDWOId()); 620296417Sdim if (!DIUnit->getSplitDebugFilename().empty()) 621296417Sdim // This is a prefabricated skeleton CU. 622296417Sdim NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name, 623296417Sdim DIUnit->getSplitDebugFilename()); 624296417Sdim } 625344779Sdim} 626344779Sdim// Create new DwarfCompileUnit for the given metadata node with tag 627344779Sdim// DW_TAG_compile_unit. 628344779SdimDwarfCompileUnit & 629344779SdimDwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) { 630344779Sdim if (auto *CU = CUMap.lookup(DIUnit)) 631344779Sdim return *CU; 632296417Sdim 633344779Sdim CompilationDir = DIUnit->getDirectory(); 634344779Sdim 635344779Sdim auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 636344779Sdim InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder); 637344779Sdim DwarfCompileUnit &NewCU = *OwnedUnit; 638344779Sdim InfoHolder.addUnit(std::move(OwnedUnit)); 639344779Sdim 640344779Sdim for (auto *IE : DIUnit->getImportedEntities()) 641344779Sdim NewCU.addImportedEntity(IE); 642344779Sdim 643344779Sdim // LTO with assembly output shares a single line table amongst multiple CUs. 644344779Sdim // To avoid the compilation directory being ambiguous, let the line table 645344779Sdim // explicitly describe the directory of all files, never relying on the 646344779Sdim // compilation directory. 647344779Sdim if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU) 648344779Sdim Asm->OutStreamer->emitDwarfFile0Directive( 649344779Sdim CompilationDir, DIUnit->getFilename(), 650344779Sdim NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(), 651344779Sdim NewCU.getUniqueID()); 652344779Sdim 653344779Sdim if (useSplitDwarf()) { 654344779Sdim NewCU.setSkeleton(constructSkeletonCU(NewCU)); 655344779Sdim NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection()); 656344779Sdim } else { 657344779Sdim finishUnitAttributes(DIUnit, NewCU); 658344779Sdim NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 659344779Sdim } 660344779Sdim 661314564Sdim CUMap.insert({DIUnit, &NewCU}); 662344779Sdim CUDieMap.insert({&NewCU.getUnitDie(), &NewCU}); 663226633Sdim return NewCU; 664193323Sed} 665193323Sed 666280031Sdimvoid DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU, 667288943Sdim const DIImportedEntity *N) { 668327952Sdim if (isa<DILocalScope>(N->getScope())) 669327952Sdim return; 670288943Sdim if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope())) 671288943Sdim D->addChild(TheCU.constructImportedEntityDIE(N)); 672251662Sdim} 673251662Sdim 674314564Sdim/// Sort and unique GVEs by comparing their fragment offset. 675314564Sdimstatic SmallVectorImpl<DwarfCompileUnit::GlobalExpr> & 676314564SdimsortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) { 677344779Sdim llvm::sort( 678344779Sdim GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) { 679344779Sdim // Sort order: first null exprs, then exprs without fragment 680344779Sdim // info, then sort by fragment offset in bits. 681344779Sdim // FIXME: Come up with a more comprehensive comparator so 682344779Sdim // the sorting isn't non-deterministic, and so the following 683344779Sdim // std::unique call works correctly. 684344779Sdim if (!A.Expr || !B.Expr) 685344779Sdim return !!B.Expr; 686344779Sdim auto FragmentA = A.Expr->getFragmentInfo(); 687344779Sdim auto FragmentB = B.Expr->getFragmentInfo(); 688344779Sdim if (!FragmentA || !FragmentB) 689344779Sdim return !!FragmentB; 690344779Sdim return FragmentA->OffsetInBits < FragmentB->OffsetInBits; 691344779Sdim }); 692314564Sdim GVEs.erase(std::unique(GVEs.begin(), GVEs.end(), 693314564Sdim [](DwarfCompileUnit::GlobalExpr A, 694314564Sdim DwarfCompileUnit::GlobalExpr B) { 695314564Sdim return A.Expr == B.Expr; 696314564Sdim }), 697314564Sdim GVEs.end()); 698314564Sdim return GVEs; 699314564Sdim} 700314564Sdim 701249423Sdim// Emit all Dwarf sections that should come prior to the content. Create 702249423Sdim// global DIEs and emit initial debug info sections. This is invoked by 703249423Sdim// the target AsmPrinter. 704249423Sdimvoid DwarfDebug::beginModule() { 705314564Sdim NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName, 706314564Sdim DWARFGroupDescription, TimePassesIsEnabled); 707344779Sdim if (DisableDebugInfoPrinting) { 708344779Sdim MMI->setDebugInfoAvailability(false); 709207618Srdivacky return; 710344779Sdim } 711193323Sed 712249423Sdim const Module *M = MMI->getModule(); 713249423Sdim 714309124Sdim unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(), 715309124Sdim M->debug_compile_units_end()); 716309124Sdim // Tell MMI whether we have debug info. 717344779Sdim assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) && 718344779Sdim "DebugInfoAvailabilty initialized unexpectedly"); 719309124Sdim SingleCU = NumDebugCUs == 1; 720314564Sdim DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>> 721314564Sdim GVMap; 722314564Sdim for (const GlobalVariable &Global : M->globals()) { 723314564Sdim SmallVector<DIGlobalVariableExpression *, 1> GVs; 724314564Sdim Global.getDebugInfo(GVs); 725314564Sdim for (auto *GVE : GVs) 726314564Sdim GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()}); 727314564Sdim } 728195098Sed 729341825Sdim // Create the symbol that designates the start of the unit's contribution 730341825Sdim // to the string offsets table. In a split DWARF scenario, only the skeleton 731341825Sdim // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol). 732341825Sdim if (useSegmentedStringOffsetsTable()) 733341825Sdim (useSplitDwarf() ? SkeletonHolder : InfoHolder) 734341825Sdim .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base")); 735341825Sdim 736341825Sdim 737344779Sdim // Create the symbols that designates the start of the DWARF v5 range list 738344779Sdim // and locations list tables. They are located past the table headers. 739344779Sdim if (getDwarfVersion() >= 5) { 740344779Sdim DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 741344779Sdim Holder.setRnglistsTableBaseSym( 742344779Sdim Asm->createTempSymbol("rnglists_table_base")); 743344779Sdim Holder.setLoclistsTableBaseSym( 744344779Sdim Asm->createTempSymbol("loclists_table_base")); 745344779Sdim 746344779Sdim if (useSplitDwarf()) 747344779Sdim InfoHolder.setRnglistsTableBaseSym( 748344779Sdim Asm->createTempSymbol("rnglists_dwo_table_base")); 749344779Sdim } 750344779Sdim 751344779Sdim // Create the symbol that points to the first entry following the debug 752344779Sdim // address table (.debug_addr) header. 753344779Sdim AddrPool.setLabel(Asm->createTempSymbol("addr_table_base")); 754344779Sdim 755309124Sdim for (DICompileUnit *CUNode : M->debug_compile_units()) { 756327952Sdim // FIXME: Move local imported entities into a list attached to the 757327952Sdim // subprogram, then this search won't be needed and a 758327952Sdim // getImportedEntities().empty() test should go below with the rest. 759327952Sdim bool HasNonLocalImportedEntities = llvm::any_of( 760327952Sdim CUNode->getImportedEntities(), [](const DIImportedEntity *IE) { 761327952Sdim return !isa<DILocalScope>(IE->getScope()); 762327952Sdim }); 763327952Sdim 764327952Sdim if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() && 765327952Sdim CUNode->getRetainedTypes().empty() && 766327952Sdim CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty()) 767321369Sdim continue; 768321369Sdim 769321369Sdim DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode); 770314564Sdim 771314564Sdim // Global Variables. 772327952Sdim for (auto *GVE : CUNode->getGlobalVariables()) { 773327952Sdim // Don't bother adding DIGlobalVariableExpressions listed in the CU if we 774327952Sdim // already know about the variable and it isn't adding a constant 775327952Sdim // expression. 776327952Sdim auto &GVMapEntry = GVMap[GVE->getVariable()]; 777327952Sdim auto *Expr = GVE->getExpression(); 778327952Sdim if (!GVMapEntry.size() || (Expr && Expr->isConstant())) 779327952Sdim GVMapEntry.push_back({nullptr, Expr}); 780327952Sdim } 781314564Sdim DenseSet<DIGlobalVariable *> Processed; 782314564Sdim for (auto *GVE : CUNode->getGlobalVariables()) { 783314564Sdim DIGlobalVariable *GV = GVE->getVariable(); 784314564Sdim if (Processed.insert(GV).second) 785314564Sdim CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV])); 786314564Sdim } 787314564Sdim 788288943Sdim for (auto *Ty : CUNode->getEnumTypes()) { 789280031Sdim // The enum types array by design contains pointers to 790280031Sdim // MDNodes rather than DIRefs. Unique them here. 791309124Sdim CU.getOrCreateTypeDIE(cast<DIType>(Ty)); 792280031Sdim } 793288943Sdim for (auto *Ty : CUNode->getRetainedTypes()) { 794276479Sdim // The retained types array by design contains pointers to 795276479Sdim // MDNodes rather than DIRefs. Unique them here. 796309124Sdim if (DIType *RT = dyn_cast<DIType>(Ty)) 797309124Sdim // There is no point in force-emitting a forward declaration. 798309124Sdim CU.getOrCreateTypeDIE(RT); 799276479Sdim } 800251662Sdim // Emit imported_modules last so that the relevant context is already 801251662Sdim // available. 802288943Sdim for (auto *IE : CUNode->getImportedEntities()) 803288943Sdim constructAndAddImportedEntityDIE(CU, IE); 804249423Sdim } 805193323Sed} 806193323Sed 807344779Sdimvoid DwarfDebug::finishEntityDefinitions() { 808344779Sdim for (const auto &Entity : ConcreteEntities) { 809344779Sdim DIE *Die = Entity->getDIE(); 810344779Sdim assert(Die); 811276479Sdim // FIXME: Consider the time-space tradeoff of just storing the unit pointer 812344779Sdim // in the ConcreteEntities list, rather than looking it up again here. 813276479Sdim // DIE::getUnit isn't simple - it walks parent pointers, etc. 814344779Sdim DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie()); 815276479Sdim assert(Unit); 816344779Sdim Unit->finishEntityDefinition(Entity.get()); 817249423Sdim } 818249423Sdim} 819249423Sdim 820276479Sdimvoid DwarfDebug::finishSubprogramDefinitions() { 821321369Sdim for (const DISubprogram *SP : ProcessedSPNodes) { 822321369Sdim assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug); 823321369Sdim forBothCUs( 824321369Sdim getOrCreateDwarfCompileUnit(SP->getUnit()), 825321369Sdim [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); }); 826321369Sdim } 827276479Sdim} 828276479Sdim 829276479Sdimvoid DwarfDebug::finalizeModuleInfo() { 830288943Sdim const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 831288943Sdim 832276479Sdim finishSubprogramDefinitions(); 833261991Sdim 834344779Sdim finishEntityDefinitions(); 835261991Sdim 836321369Sdim // Include the DWO file name in the hash if there's more than one CU. 837321369Sdim // This handles ThinLTO's situation where imported CUs may very easily be 838321369Sdim // duplicate with the same CU partially imported into another ThinLTO unit. 839321369Sdim StringRef DWOName; 840321369Sdim if (CUMap.size() > 1) 841321369Sdim DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile; 842321369Sdim 843276479Sdim // Handle anything that needs to be done on a per-unit basis after 844276479Sdim // all other generation. 845280031Sdim for (const auto &P : CUMap) { 846280031Sdim auto &TheCU = *P.second; 847344779Sdim if (TheCU.getCUNode()->isDebugDirectivesOnly()) 848344779Sdim continue; 849261991Sdim // Emit DW_AT_containing_type attribute to connect types with their 850261991Sdim // vtable holding type. 851280031Sdim TheCU.constructContainingTypeDIEs(); 852261991Sdim 853276479Sdim // Add CU specific attributes if we need to add any. 854280031Sdim // If we're splitting the dwarf out now that we've got the entire 855280031Sdim // CU then add the dwo id to it. 856280031Sdim auto *SkCU = TheCU.getSkeleton(); 857344779Sdim if (useSplitDwarf() && !empty(TheCU.getUnitDie().children())) { 858344779Sdim finishUnitAttributes(TheCU.getCUNode(), TheCU); 859344779Sdim TheCU.addString(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_name, 860344779Sdim Asm->TM.Options.MCOptions.SplitDwarfFile); 861344779Sdim SkCU->addString(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_name, 862344779Sdim Asm->TM.Options.MCOptions.SplitDwarfFile); 863280031Sdim // Emit a unique identifier for this CU. 864321369Sdim uint64_t ID = 865321369Sdim DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie()); 866341825Sdim if (getDwarfVersion() >= 5) { 867341825Sdim TheCU.setDWOId(ID); 868341825Sdim SkCU->setDWOId(ID); 869341825Sdim } else { 870341825Sdim TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 871341825Sdim dwarf::DW_FORM_data8, ID); 872341825Sdim SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 873341825Sdim dwarf::DW_FORM_data8, ID); 874341825Sdim } 875344779Sdim 876344779Sdim if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) { 877288943Sdim const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol(); 878280031Sdim SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base, 879288943Sdim Sym, Sym); 880288943Sdim } 881344779Sdim } else if (SkCU) { 882344779Sdim finishUnitAttributes(SkCU->getCUNode(), *SkCU); 883280031Sdim } 884276479Sdim 885280031Sdim // If we have code split among multiple sections or non-contiguous 886280031Sdim // ranges of code then emit a DW_AT_ranges attribute on the unit that will 887280031Sdim // remain in the .o file, otherwise add a DW_AT_low_pc. 888280031Sdim // FIXME: We should use ranges allow reordering of code ala 889280031Sdim // .subsections_via_symbols in mach-o. This would mean turning on 890280031Sdim // ranges for all subprogram DIEs for mach-o. 891280031Sdim DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 892344779Sdim 893344779Sdim // We don't keep track of which addresses are used in which CU so this 894344779Sdim // is a bit pessimistic under LTO. 895344779Sdim if (!AddrPool.isEmpty() && 896344779Sdim (getDwarfVersion() >= 5 || 897344779Sdim (SkCU && !empty(TheCU.getUnitDie().children())))) 898344779Sdim U.addAddrTableBase(); 899344779Sdim 900280031Sdim if (unsigned NumRanges = TheCU.getRanges().size()) { 901341825Sdim if (NumRanges > 1 && useRangesSection()) 902280031Sdim // A DW_AT_low_pc attribute may also be specified in combination with 903280031Sdim // DW_AT_ranges to specify the default base address for use in 904280031Sdim // location lists (see Section 2.6.2) and range lists (see Section 905280031Sdim // 2.17.3). 906280031Sdim U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0); 907280031Sdim else 908288943Sdim U.setBaseAddress(TheCU.getRanges().front().getStart()); 909280031Sdim U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges()); 910261991Sdim } 911296417Sdim 912344779Sdim if (getDwarfVersion() >= 5) { 913344779Sdim if (U.hasRangeLists()) 914344779Sdim U.addRnglistsBase(); 915341825Sdim 916344779Sdim if (!DebugLocs.getLists().empty() && !useSplitDwarf()) 917344779Sdim U.addLoclistsBase(); 918344779Sdim } 919344779Sdim 920296417Sdim auto *CUNode = cast<DICompileUnit>(P.first); 921309124Sdim // If compile Unit has macros, emit "DW_AT_macro_info" attribute. 922309124Sdim if (CUNode->getMacros()) 923309124Sdim U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info, 924309124Sdim U.getMacroLabelBegin(), 925309124Sdim TLOF.getDwarfMacinfoSection()->getBeginSymbol()); 926200581Srdivacky } 927200581Srdivacky 928327952Sdim // Emit all frontend-produced Skeleton CUs, i.e., Clang modules. 929327952Sdim for (auto *CUNode : MMI->getModule()->debug_compile_units()) 930327952Sdim if (CUNode->getDWOId()) 931327952Sdim getOrCreateDwarfCompileUnit(CUNode); 932327952Sdim 933261991Sdim // Compute DIE offsets and sizes. 934249423Sdim InfoHolder.computeSizeAndOffsets(); 935249423Sdim if (useSplitDwarf()) 936249423Sdim SkeletonHolder.computeSizeAndOffsets(); 937249423Sdim} 938249423Sdim 939249423Sdim// Emit all Dwarf sections that should come after the content. 940249423Sdimvoid DwarfDebug::endModule() { 941276479Sdim assert(CurFn == nullptr); 942276479Sdim assert(CurMI == nullptr); 943193323Sed 944280031Sdim // If we aren't actually generating debug info (check beginModule - 945280031Sdim // conditionalized on !DisableDebugInfoPrinting and the presence of the 946280031Sdim // llvm.dbg.cu metadata node) 947288943Sdim if (!MMI->hasDebugInfo()) 948276479Sdim return; 949193323Sed 950249423Sdim // Finalize the debug info for the module. 951249423Sdim finalizeModuleInfo(); 952249423Sdim 953276479Sdim emitDebugStr(); 954261991Sdim 955288943Sdim if (useSplitDwarf()) 956288943Sdim emitDebugLocDWO(); 957288943Sdim else 958288943Sdim // Emit info into a debug loc section. 959288943Sdim emitDebugLoc(); 960249423Sdim 961276479Sdim // Corresponding abbreviations into a abbrev section. 962276479Sdim emitAbbreviations(); 963249423Sdim 964288943Sdim // Emit all the DIEs into a debug info section. 965288943Sdim emitDebugInfo(); 966288943Sdim 967276479Sdim // Emit info into a debug aranges section. 968276479Sdim if (GenerateARangeSection) 969249423Sdim emitDebugARanges(); 970249423Sdim 971276479Sdim // Emit info into a debug ranges section. 972276479Sdim emitDebugRanges(); 973249423Sdim 974296417Sdim // Emit info into a debug macinfo section. 975296417Sdim emitDebugMacinfo(); 976296417Sdim 977276479Sdim if (useSplitDwarf()) { 978276479Sdim emitDebugStrDWO(); 979249423Sdim emitDebugInfoDWO(); 980249423Sdim emitDebugAbbrevDWO(); 981276479Sdim emitDebugLineDWO(); 982344779Sdim emitDebugRangesDWO(); 983288943Sdim } 984249423Sdim 985344779Sdim emitDebugAddr(); 986344779Sdim 987243830Sdim // Emit info into the dwarf accelerator table sections. 988341825Sdim switch (getAccelTableKind()) { 989341825Sdim case AccelTableKind::Apple: 990234353Sdim emitAccelNames(); 991234353Sdim emitAccelObjC(); 992234353Sdim emitAccelNamespaces(); 993234353Sdim emitAccelTypes(); 994341825Sdim break; 995341825Sdim case AccelTableKind::Dwarf: 996341825Sdim emitAccelDebugNames(); 997341825Sdim break; 998341825Sdim case AccelTableKind::None: 999341825Sdim break; 1000341825Sdim case AccelTableKind::Default: 1001341825Sdim llvm_unreachable("Default should have already been resolved."); 1002234353Sdim } 1003249423Sdim 1004261991Sdim // Emit the pubnames and pubtypes sections if requested. 1005327952Sdim emitDebugPubSections(); 1006249423Sdim 1007212904Sdim // clean up. 1008321369Sdim // FIXME: AbstractVariables.clear(); 1009193323Sed} 1010193323Sed 1011344779Sdimvoid DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU, 1012344779Sdim const DINode *Node, 1013344779Sdim const MDNode *ScopeNode) { 1014344779Sdim if (CU.getExistingAbstractEntity(Node)) 1015276479Sdim return; 1016276479Sdim 1017344779Sdim CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope( 1018288943Sdim cast<DILocalScope>(ScopeNode))); 1019276479Sdim} 1020276479Sdim 1021344779Sdimvoid DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU, 1022344779Sdim const DINode *Node, const MDNode *ScopeNode) { 1023344779Sdim if (CU.getExistingAbstractEntity(Node)) 1024276479Sdim return; 1025276479Sdim 1026288943Sdim if (LexicalScope *Scope = 1027288943Sdim LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode))) 1028344779Sdim CU.createAbstractEntity(Node, Scope); 1029276479Sdim} 1030327952Sdim 1031314564Sdim// Collect variable information from side table maintained by MF. 1032314564Sdimvoid DwarfDebug::collectVariableInfoFromMFTable( 1033344779Sdim DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) { 1034344779Sdim SmallDenseMap<InlinedEntity, DbgVariable *> MFVars; 1035314564Sdim for (const auto &VI : Asm->MF->getVariableDbgInfo()) { 1036276479Sdim if (!VI.Var) 1037276479Sdim continue; 1038288943Sdim assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 1039288943Sdim "Expected inlined-at fields to agree"); 1040288943Sdim 1041344779Sdim InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt()); 1042288943Sdim Processed.insert(Var); 1043276479Sdim LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 1044199481Srdivacky 1045199481Srdivacky // If variable scope is not found then skip this variable. 1046276479Sdim if (!Scope) 1047199481Srdivacky continue; 1048199481Srdivacky 1049344779Sdim ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode()); 1050344779Sdim auto RegVar = llvm::make_unique<DbgVariable>( 1051344779Sdim cast<DILocalVariable>(Var.first), Var.second); 1052288943Sdim RegVar->initializeMMI(VI.Expr, VI.Slot); 1053327952Sdim if (DbgVariable *DbgVar = MFVars.lookup(Var)) 1054327952Sdim DbgVar->addMMIEntry(*RegVar); 1055327952Sdim else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) { 1056327952Sdim MFVars.insert({Var, RegVar.get()}); 1057344779Sdim ConcreteEntities.push_back(std::move(RegVar)); 1058327952Sdim } 1059198090Srdivacky } 1060208599Srdivacky} 1061205218Srdivacky 1062249423Sdim// Get .debug_loc entry for the instruction range starting at MI. 1063276479Sdimstatic DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) { 1064288943Sdim const DIExpression *Expr = MI->getDebugExpression(); 1065280031Sdim assert(MI->getNumOperands() == 4); 1066261991Sdim if (MI->getOperand(0).isReg()) { 1067327952Sdim auto RegOp = MI->getOperand(0); 1068327952Sdim auto Op1 = MI->getOperand(1); 1069261991Sdim // If the second operand is an immediate, this is a 1070261991Sdim // register-indirect address. 1071327952Sdim assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"); 1072327952Sdim MachineLocation MLoc(RegOp.getReg(), Op1.isImm()); 1073288943Sdim return DebugLocEntry::Value(Expr, MLoc); 1074224145Sdim } 1075224145Sdim if (MI->getOperand(0).isImm()) 1076288943Sdim return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm()); 1077224145Sdim if (MI->getOperand(0).isFPImm()) 1078288943Sdim return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm()); 1079224145Sdim if (MI->getOperand(0).isCImm()) 1080288943Sdim return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm()); 1081224145Sdim 1082280031Sdim llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!"); 1083224145Sdim} 1084224145Sdim 1085341825Sdim/// If this and Next are describing different fragments of the same 1086296417Sdim/// variable, merge them by appending Next's values to the current 1087296417Sdim/// list of values. 1088296417Sdim/// Return true if the merge was successful. 1089296417Sdimbool DebugLocEntry::MergeValues(const DebugLocEntry &Next) { 1090296417Sdim if (Begin == Next.Begin) { 1091296417Sdim auto *FirstExpr = cast<DIExpression>(Values[0].Expression); 1092296417Sdim auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression); 1093314564Sdim if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment()) 1094296417Sdim return false; 1095296417Sdim 1096314564Sdim // We can only merge entries if none of the fragments overlap any others. 1097296417Sdim // In doing so, we can take advantage of the fact that both lists are 1098296417Sdim // sorted. 1099296417Sdim for (unsigned i = 0, j = 0; i < Values.size(); ++i) { 1100296417Sdim for (; j < Next.Values.size(); ++j) { 1101341825Sdim int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp( 1102309124Sdim cast<DIExpression>(Next.Values[j].Expression)); 1103296417Sdim if (res == 0) // The two expressions overlap, we can't merge. 1104296417Sdim return false; 1105296417Sdim // Values[i] is entirely before Next.Values[j], 1106296417Sdim // so go back to the next entry of Values. 1107296417Sdim else if (res == -1) 1108296417Sdim break; 1109296417Sdim // Next.Values[j] is entirely before Values[i], so go on to the 1110296417Sdim // next entry of Next.Values. 1111296417Sdim } 1112296417Sdim } 1113296417Sdim 1114296417Sdim addValues(Next.Values); 1115296417Sdim End = Next.End; 1116296417Sdim return true; 1117296417Sdim } 1118296417Sdim return false; 1119296417Sdim} 1120296417Sdim 1121280031Sdim/// Build the location list for all DBG_VALUEs in the function that 1122280031Sdim/// describe the same variable. If the ranges of several independent 1123314564Sdim/// fragments of the same variable overlap partially, split them up and 1124280031Sdim/// combine the ranges. The resulting DebugLocEntries are will have 1125280031Sdim/// strict monotonically increasing begin addresses and will never 1126280031Sdim/// overlap. 1127280031Sdim// 1128280031Sdim// Input: 1129280031Sdim// 1130314564Sdim// Ranges History [var, loc, fragment ofs size] 1131314564Sdim// 0 | [x, (reg0, fragment 0, 32)] 1132314564Sdim// 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry 1133280031Sdim// 2 | | ... 1134280031Sdim// 3 | [clobber reg0] 1135314564Sdim// 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of 1136288943Sdim// x. 1137280031Sdim// 1138280031Sdim// Output: 1139280031Sdim// 1140314564Sdim// [0-1] [x, (reg0, fragment 0, 32)] 1141314564Sdim// [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)] 1142314564Sdim// [3-4] [x, (reg1, fragment 32, 32)] 1143314564Sdim// [4- ] [x, (mem, fragment 0, 64)] 1144280031Sdimvoid 1145280031SdimDwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 1146280031Sdim const DbgValueHistoryMap::InstrRanges &Ranges) { 1147280031Sdim SmallVector<DebugLocEntry::Value, 4> OpenRanges; 1148280031Sdim 1149280031Sdim for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 1150280031Sdim const MachineInstr *Begin = I->first; 1151280031Sdim const MachineInstr *End = I->second; 1152280031Sdim assert(Begin->isDebugValue() && "Invalid History entry"); 1153280031Sdim 1154280031Sdim // Check if a variable is inaccessible in this range. 1155280031Sdim if (Begin->getNumOperands() > 1 && 1156280031Sdim Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) { 1157280031Sdim OpenRanges.clear(); 1158280031Sdim continue; 1159280031Sdim } 1160280031Sdim 1161314564Sdim // If this fragment overlaps with any open ranges, truncate them. 1162288943Sdim const DIExpression *DIExpr = Begin->getDebugExpression(); 1163314564Sdim auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) { 1164341825Sdim return DIExpr->fragmentsOverlap(R.getExpression()); 1165280031Sdim }); 1166280031Sdim OpenRanges.erase(Last, OpenRanges.end()); 1167280031Sdim 1168280031Sdim const MCSymbol *StartLabel = getLabelBeforeInsn(Begin); 1169280031Sdim assert(StartLabel && "Forgot label before DBG_VALUE starting a range!"); 1170280031Sdim 1171280031Sdim const MCSymbol *EndLabel; 1172280031Sdim if (End != nullptr) 1173280031Sdim EndLabel = getLabelAfterInsn(End); 1174280031Sdim else if (std::next(I) == Ranges.end()) 1175288943Sdim EndLabel = Asm->getFunctionEnd(); 1176280031Sdim else 1177280031Sdim EndLabel = getLabelBeforeInsn(std::next(I)->first); 1178280031Sdim assert(EndLabel && "Forgot label after instruction ending a range!"); 1179280031Sdim 1180341825Sdim LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n"); 1181280031Sdim 1182280031Sdim auto Value = getDebugLocValue(Begin); 1183344779Sdim 1184344779Sdim // Omit entries with empty ranges as they do not have any effect in DWARF. 1185344779Sdim if (StartLabel == EndLabel) { 1186344779Sdim // If this is a fragment, we must still add the value to the list of 1187344779Sdim // open ranges, since it may describe non-overlapping parts of the 1188344779Sdim // variable. 1189344779Sdim if (DIExpr->isFragment()) 1190344779Sdim OpenRanges.push_back(Value); 1191344779Sdim LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n"); 1192344779Sdim continue; 1193344779Sdim } 1194344779Sdim 1195280031Sdim DebugLocEntry Loc(StartLabel, EndLabel, Value); 1196280031Sdim bool couldMerge = false; 1197280031Sdim 1198314564Sdim // If this is a fragment, it may belong to the current DebugLocEntry. 1199314564Sdim if (DIExpr->isFragment()) { 1200280031Sdim // Add this value to the list of open ranges. 1201280031Sdim OpenRanges.push_back(Value); 1202280031Sdim 1203314564Sdim // Attempt to add the fragment to the last entry. 1204280031Sdim if (!DebugLoc.empty()) 1205280031Sdim if (DebugLoc.back().MergeValues(Loc)) 1206280031Sdim couldMerge = true; 1207280031Sdim } 1208280031Sdim 1209280031Sdim if (!couldMerge) { 1210280031Sdim // Need to add a new DebugLocEntry. Add all values from still 1211314564Sdim // valid non-overlapping fragments. 1212280031Sdim if (OpenRanges.size()) 1213280031Sdim Loc.addValues(OpenRanges); 1214280031Sdim 1215280031Sdim DebugLoc.push_back(std::move(Loc)); 1216280031Sdim } 1217280031Sdim 1218280031Sdim // Attempt to coalesce the ranges of two otherwise identical 1219280031Sdim // DebugLocEntries. 1220280031Sdim auto CurEntry = DebugLoc.rbegin(); 1221341825Sdim LLVM_DEBUG({ 1222280031Sdim dbgs() << CurEntry->getValues().size() << " Values:\n"; 1223288943Sdim for (auto &Value : CurEntry->getValues()) 1224309124Sdim Value.dump(); 1225280031Sdim dbgs() << "-----\n"; 1226280031Sdim }); 1227288943Sdim 1228288943Sdim auto PrevEntry = std::next(CurEntry); 1229288943Sdim if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 1230288943Sdim DebugLoc.pop_back(); 1231280031Sdim } 1232280031Sdim} 1233280031Sdim 1234344779SdimDbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU, 1235344779Sdim LexicalScope &Scope, 1236344779Sdim const DINode *Node, 1237344779Sdim const DILocation *Location, 1238344779Sdim const MCSymbol *Sym) { 1239344779Sdim ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode()); 1240344779Sdim if (isa<const DILocalVariable>(Node)) { 1241344779Sdim ConcreteEntities.push_back( 1242344779Sdim llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node), 1243344779Sdim Location)); 1244344779Sdim InfoHolder.addScopeVariable(&Scope, 1245344779Sdim cast<DbgVariable>(ConcreteEntities.back().get())); 1246344779Sdim } else if (isa<const DILabel>(Node)) { 1247344779Sdim ConcreteEntities.push_back( 1248344779Sdim llvm::make_unique<DbgLabel>(cast<const DILabel>(Node), 1249344779Sdim Location, Sym)); 1250344779Sdim InfoHolder.addScopeLabel(&Scope, 1251344779Sdim cast<DbgLabel>(ConcreteEntities.back().get())); 1252344779Sdim } 1253344779Sdim return ConcreteEntities.back().get(); 1254288943Sdim} 1255280031Sdim 1256321369Sdim/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its 1257321369Sdim/// enclosing lexical scope. The check ensures there are no other instructions 1258321369Sdim/// in the same lexical scope preceding the DBG_VALUE and that its range is 1259321369Sdim/// either open or otherwise rolls off the end of the scope. 1260321369Sdimstatic bool validThroughout(LexicalScopes &LScopes, 1261321369Sdim const MachineInstr *DbgValue, 1262321369Sdim const MachineInstr *RangeEnd) { 1263321369Sdim assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location"); 1264321369Sdim auto MBB = DbgValue->getParent(); 1265321369Sdim auto DL = DbgValue->getDebugLoc(); 1266321369Sdim auto *LScope = LScopes.findLexicalScope(DL); 1267321369Sdim // Scope doesn't exist; this is a dead DBG_VALUE. 1268321369Sdim if (!LScope) 1269309124Sdim return false; 1270321369Sdim auto &LSRange = LScope->getRanges(); 1271321369Sdim if (LSRange.size() == 0) 1272321369Sdim return false; 1273321369Sdim 1274321369Sdim // Determine if the DBG_VALUE is valid at the beginning of its lexical block. 1275321369Sdim const MachineInstr *LScopeBegin = LSRange.front().first; 1276321369Sdim // Early exit if the lexical scope begins outside of the current block. 1277321369Sdim if (LScopeBegin->getParent() != MBB) 1278321369Sdim return false; 1279321369Sdim MachineBasicBlock::const_reverse_iterator Pred(DbgValue); 1280321369Sdim for (++Pred; Pred != MBB->rend(); ++Pred) { 1281321369Sdim if (Pred->getFlag(MachineInstr::FrameSetup)) 1282321369Sdim break; 1283321369Sdim auto PredDL = Pred->getDebugLoc(); 1284321369Sdim if (!PredDL || Pred->isMetaInstruction()) 1285321369Sdim continue; 1286321369Sdim // Check whether the instruction preceding the DBG_VALUE is in the same 1287321369Sdim // (sub)scope as the DBG_VALUE. 1288321369Sdim if (DL->getScope() == PredDL->getScope()) 1289309124Sdim return false; 1290321369Sdim auto *PredScope = LScopes.findLexicalScope(PredDL); 1291321369Sdim if (!PredScope || LScope->dominates(PredScope)) 1292321369Sdim return false; 1293321369Sdim } 1294321369Sdim 1295321369Sdim // If the range of the DBG_VALUE is open-ended, report success. 1296321369Sdim if (!RangeEnd) 1297321369Sdim return true; 1298321369Sdim 1299321369Sdim // Fail if there are instructions belonging to our scope in another block. 1300321369Sdim const MachineInstr *LScopeEnd = LSRange.back().second; 1301321369Sdim if (LScopeEnd->getParent() != MBB) 1302321369Sdim return false; 1303321369Sdim 1304321369Sdim // Single, constant DBG_VALUEs in the prologue are promoted to be live 1305321369Sdim // throughout the function. This is a hack, presumably for DWARF v2 and not 1306321369Sdim // necessarily correct. It would be much better to use a dbg.declare instead 1307321369Sdim // if we know the constant is live throughout the scope. 1308321369Sdim if (DbgValue->getOperand(0).isImm() && MBB->pred_empty()) 1309321369Sdim return true; 1310321369Sdim 1311321369Sdim return false; 1312309124Sdim} 1313309124Sdim 1314249423Sdim// Find variables for each lexical scope. 1315344779Sdimvoid DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU, 1316344779Sdim const DISubprogram *SP, 1317344779Sdim DenseSet<InlinedEntity> &Processed) { 1318261991Sdim // Grab the variable info that was squirreled away in the MMI side-table. 1319321369Sdim collectVariableInfoFromMFTable(TheCU, Processed); 1320208599Srdivacky 1321276479Sdim for (const auto &I : DbgValues) { 1322344779Sdim InlinedEntity IV = I.first; 1323288943Sdim if (Processed.count(IV)) 1324221345Sdim continue; 1325206083Srdivacky 1326288943Sdim // Instruction ranges, specifying where IV is accessible. 1327276479Sdim const auto &Ranges = I.second; 1328276479Sdim if (Ranges.empty()) 1329208599Srdivacky continue; 1330207618Srdivacky 1331276479Sdim LexicalScope *Scope = nullptr; 1332344779Sdim const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first); 1333288943Sdim if (const DILocation *IA = IV.second) 1334344779Sdim Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA); 1335288943Sdim else 1336344779Sdim Scope = LScopes.findLexicalScope(LocalVar->getScope()); 1337208599Srdivacky // If variable scope is not found then skip this variable. 1338208599Srdivacky if (!Scope) 1339208599Srdivacky continue; 1340208599Srdivacky 1341288943Sdim Processed.insert(IV); 1342344779Sdim DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU, 1343344779Sdim *Scope, LocalVar, IV.second)); 1344288943Sdim 1345276479Sdim const MachineInstr *MInsn = Ranges.front().first; 1346221345Sdim assert(MInsn->isDebugValue() && "History must begin with debug value"); 1347221345Sdim 1348321369Sdim // Check if there is a single DBG_VALUE, valid throughout the var's scope. 1349309124Sdim if (Ranges.size() == 1 && 1350321369Sdim validThroughout(LScopes, MInsn, Ranges.front().second)) { 1351288943Sdim RegVar->initializeDbgValue(MInsn); 1352208599Srdivacky continue; 1353288943Sdim } 1354341825Sdim // Do not emit location lists if .debug_loc secton is disabled. 1355341825Sdim if (!useLocSection()) 1356341825Sdim continue; 1357208599Srdivacky 1358249423Sdim // Handle multiple DBG_VALUE instructions describing one variable. 1359288943Sdim DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 1360221345Sdim 1361288943Sdim // Build the location list for this variable. 1362288943Sdim SmallVector<DebugLocEntry, 8> Entries; 1363288943Sdim buildLocationList(Entries, Ranges); 1364212904Sdim 1365309124Sdim // If the variable has a DIBasicType, extract it. Basic types cannot have 1366288943Sdim // unique identifiers, so don't bother resolving the type with the 1367288943Sdim // identifier map. 1368288943Sdim const DIBasicType *BT = dyn_cast<DIBasicType>( 1369344779Sdim static_cast<const Metadata *>(LocalVar->getType())); 1370288943Sdim 1371288943Sdim // Finalize the entry by lowering it into a DWARF bytestream. 1372288943Sdim for (auto &Entry : Entries) 1373288943Sdim Entry.finalize(*Asm, List, BT); 1374208599Srdivacky } 1375205218Srdivacky 1376344779Sdim // For each InlinedEntity collected from DBG_LABEL instructions, convert to 1377344779Sdim // DWARF-related DbgLabel. 1378344779Sdim for (const auto &I : DbgLabels) { 1379344779Sdim InlinedEntity IL = I.first; 1380344779Sdim const MachineInstr *MI = I.second; 1381344779Sdim if (MI == nullptr) 1382344779Sdim continue; 1383344779Sdim 1384344779Sdim LexicalScope *Scope = nullptr; 1385344779Sdim const DILabel *Label = cast<DILabel>(IL.first); 1386344779Sdim // Get inlined DILocation if it is inlined label. 1387344779Sdim if (const DILocation *IA = IL.second) 1388344779Sdim Scope = LScopes.findInlinedScope(Label->getScope(), IA); 1389344779Sdim else 1390344779Sdim Scope = LScopes.findLexicalScope(Label->getScope()); 1391344779Sdim // If label scope is not found then skip this label. 1392344779Sdim if (!Scope) 1393344779Sdim continue; 1394344779Sdim 1395344779Sdim Processed.insert(IL); 1396344779Sdim /// At this point, the temporary label is created. 1397344779Sdim /// Save the temporary label to DbgLabel entity to get the 1398344779Sdim /// actually address when generating Dwarf DIE. 1399344779Sdim MCSymbol *Sym = getLabelBeforeInsn(MI); 1400344779Sdim createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym); 1401344779Sdim } 1402344779Sdim 1403344779Sdim // Collect info for variables/labels that were optimized out. 1404341825Sdim for (const DINode *DN : SP->getRetainedNodes()) { 1405344779Sdim if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1406344779Sdim continue; 1407344779Sdim LexicalScope *Scope = nullptr; 1408341825Sdim if (auto *DV = dyn_cast<DILocalVariable>(DN)) { 1409344779Sdim Scope = LScopes.findLexicalScope(DV->getScope()); 1410344779Sdim } else if (auto *DL = dyn_cast<DILabel>(DN)) { 1411344779Sdim Scope = LScopes.findLexicalScope(DL->getScope()); 1412341825Sdim } 1413344779Sdim 1414344779Sdim if (Scope) 1415344779Sdim createConcreteEntity(TheCU, *Scope, DN, nullptr); 1416205218Srdivacky } 1417198090Srdivacky} 1418198090Srdivacky 1419249423Sdim// Process beginning of an instruction. 1420218893Sdimvoid DwarfDebug::beginInstruction(const MachineInstr *MI) { 1421309124Sdim DebugHandlerBase::beginInstruction(MI); 1422309124Sdim assert(CurMI); 1423309124Sdim 1424327952Sdim const auto *SP = MI->getMF()->getFunction().getSubprogram(); 1425321369Sdim if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1426321369Sdim return; 1427321369Sdim 1428314564Sdim // Check if source location changes, but ignore DBG_VALUE and CFI locations. 1429341825Sdim // If the instruction is part of the function frame setup code, do not emit 1430341825Sdim // any line record, as there is no correspondence with any user code. 1431341825Sdim if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup)) 1432314564Sdim return; 1433314564Sdim const DebugLoc &DL = MI->getDebugLoc(); 1434314564Sdim // When we emit a line-0 record, we don't update PrevInstLoc; so look at 1435314564Sdim // the last line number actually emitted, to see if it was line 0. 1436314564Sdim unsigned LastAsmLine = 1437314564Sdim Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine(); 1438234353Sdim 1439344779Sdim // Request a label after the call in order to emit AT_return_pc information 1440344779Sdim // in call site entries. TODO: Add support for targets with delay slots. 1441344779Sdim if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot()) 1442344779Sdim requestLabelAfterInsn(MI); 1443344779Sdim 1444314564Sdim if (DL == PrevInstLoc) { 1445314564Sdim // If we have an ongoing unspecified location, nothing to do here. 1446314564Sdim if (!DL) 1447314564Sdim return; 1448314564Sdim // We have an explicit location, same as the previous location. 1449314564Sdim // But we might be coming back to it after a line 0 record. 1450314564Sdim if (LastAsmLine == 0 && DL.getLine() != 0) { 1451314564Sdim // Reinstate the source location but not marked as a statement. 1452314564Sdim const MDNode *Scope = DL.getScope(); 1453314564Sdim recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0); 1454314564Sdim } 1455314564Sdim return; 1456314564Sdim } 1457314564Sdim 1458314564Sdim if (!DL) { 1459314564Sdim // We have an unspecified location, which might want to be line 0. 1460314564Sdim // If we have already emitted a line-0 record, don't repeat it. 1461314564Sdim if (LastAsmLine == 0) 1462314564Sdim return; 1463314564Sdim // If user said Don't Do That, don't do that. 1464314564Sdim if (UnknownLocations == Disable) 1465314564Sdim return; 1466314564Sdim // See if we have a reason to emit a line-0 record now. 1467314564Sdim // Reasons to emit a line-0 record include: 1468314564Sdim // - User asked for it (UnknownLocations). 1469314564Sdim // - Instruction has a label, so it's referenced from somewhere else, 1470314564Sdim // possibly debug information; we want it to have a source location. 1471314564Sdim // - Instruction is at the top of a block; we don't want to inherit the 1472314564Sdim // location from the physically previous (maybe unrelated) block. 1473314564Sdim if (UnknownLocations == Enable || PrevLabel || 1474314564Sdim (PrevInstBB && PrevInstBB != MI->getParent())) { 1475314564Sdim // Preserve the file and column numbers, if we can, to save space in 1476314564Sdim // the encoded line table. 1477314564Sdim // Do not update PrevInstLoc, it remembers the last non-0 line. 1478314564Sdim const MDNode *Scope = nullptr; 1479314564Sdim unsigned Column = 0; 1480314564Sdim if (PrevInstLoc) { 1481314564Sdim Scope = PrevInstLoc.getScope(); 1482314564Sdim Column = PrevInstLoc.getCol(); 1483288943Sdim } 1484314564Sdim recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0); 1485221345Sdim } 1486314564Sdim return; 1487208599Srdivacky } 1488314564Sdim 1489314564Sdim // We have an explicit location, different from the previous location. 1490314564Sdim // Don't repeat a line-0 record, but otherwise emit the new location. 1491314564Sdim // (The new location might be an explicit line 0, which we do emit.) 1492314564Sdim if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0) 1493314564Sdim return; 1494314564Sdim unsigned Flags = 0; 1495314564Sdim if (DL == PrologEndLoc) { 1496314564Sdim Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT; 1497314564Sdim PrologEndLoc = DebugLoc(); 1498314564Sdim } 1499314564Sdim // If the line changed, we call that a new statement; unless we went to 1500314564Sdim // line 0 and came back, in which case it is not a new statement. 1501314564Sdim unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine; 1502314564Sdim if (DL.getLine() && DL.getLine() != OldLine) 1503314564Sdim Flags |= DWARF2_FLAG_IS_STMT; 1504314564Sdim 1505314564Sdim const MDNode *Scope = DL.getScope(); 1506314564Sdim recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1507314564Sdim 1508314564Sdim // If we're not at line 0, remember this location. 1509314564Sdim if (DL.getLine()) 1510314564Sdim PrevInstLoc = DL; 1511221345Sdim} 1512206083Srdivacky 1513276479Sdimstatic DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1514276479Sdim // First known non-DBG_VALUE and non-frame setup location marks 1515276479Sdim // the beginning of the function body. 1516276479Sdim for (const auto &MBB : *MF) 1517276479Sdim for (const auto &MI : MBB) 1518321369Sdim if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1519296417Sdim MI.getDebugLoc()) 1520276479Sdim return MI.getDebugLoc(); 1521223017Sdim return DebugLoc(); 1522218893Sdim} 1523218893Sdim 1524249423Sdim// Gather pre-function debug information. Assumes being called immediately 1525249423Sdim// after the function entry point has been emitted. 1526321369Sdimvoid DwarfDebug::beginFunctionImpl(const MachineFunction *MF) { 1527276479Sdim CurFn = MF; 1528261991Sdim 1529327952Sdim auto *SP = MF->getFunction().getSubprogram(); 1530321369Sdim assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode()); 1531321369Sdim if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1532261991Sdim return; 1533261991Sdim 1534321369Sdim DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 1535280031Sdim 1536276479Sdim // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1537261991Sdim // belongs to so that we add to the correct per-cu line table in the 1538261991Sdim // non-asm case. 1539288943Sdim if (Asm->OutStreamer->hasRawTextSupport()) 1540276479Sdim // Use a single line table if we are generating assembly. 1541288943Sdim Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1542251662Sdim else 1543321369Sdim Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID()); 1544249423Sdim 1545223017Sdim // Record beginning of function. 1546276479Sdim PrologEndLoc = findPrologueEndLoc(MF); 1547321369Sdim if (PrologEndLoc) { 1548288943Sdim // We'd like to list the prologue as "not statements" but GDB behaves 1549288943Sdim // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1550321369Sdim auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram(); 1551288943Sdim recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT); 1552223017Sdim } 1553193323Sed} 1554193323Sed 1555321369Sdimvoid DwarfDebug::skippedNonDebugFunction() { 1556321369Sdim // If we don't have a subprogram for this function then there will be a hole 1557321369Sdim // in the range information. Keep note of this by setting the previously used 1558321369Sdim // section to nullptr. 1559321369Sdim PrevCU = nullptr; 1560321369Sdim CurFn = nullptr; 1561321369Sdim} 1562321369Sdim 1563249423Sdim// Gather and emit post-function debug information. 1564321369Sdimvoid DwarfDebug::endFunctionImpl(const MachineFunction *MF) { 1565327952Sdim const DISubprogram *SP = MF->getFunction().getSubprogram(); 1566321369Sdim 1567280031Sdim assert(CurFn == MF && 1568280031Sdim "endFunction should be called with the same function as beginFunction"); 1569193323Sed 1570276479Sdim // Set DwarfDwarfCompileUnitID in MCContext to default value. 1571288943Sdim Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1572249423Sdim 1573280031Sdim LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1574314564Sdim assert(!FnScope || SP == FnScope->getScopeNode()); 1575309124Sdim DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit()); 1576344779Sdim if (TheCU.getCUNode()->isDebugDirectivesOnly()) { 1577344779Sdim PrevLabel = nullptr; 1578344779Sdim CurFn = nullptr; 1579344779Sdim return; 1580344779Sdim } 1581280031Sdim 1582344779Sdim DenseSet<InlinedEntity> Processed; 1583344779Sdim collectEntityInfo(TheCU, SP, Processed); 1584249423Sdim 1585280031Sdim // Add the range of this function to the list of ranges for the CU. 1586288943Sdim TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd())); 1587208599Srdivacky 1588280031Sdim // Under -gmlt, skip building the subprogram if there are no inlined 1589321369Sdim // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram 1590321369Sdim // is still needed as we need its source location. 1591321369Sdim if (!TheCU.getCUNode()->getDebugInfoForProfiling() && 1592321369Sdim TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly && 1593280031Sdim LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1594280031Sdim assert(InfoHolder.getScopeVariables().empty()); 1595280031Sdim PrevLabel = nullptr; 1596280031Sdim CurFn = nullptr; 1597280031Sdim return; 1598280031Sdim } 1599280031Sdim 1600280031Sdim#ifndef NDEBUG 1601280031Sdim size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1602280031Sdim#endif 1603226633Sdim // Construct abstract scopes. 1604276479Sdim for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1605288943Sdim auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 1606341825Sdim for (const DINode *DN : SP->getRetainedNodes()) { 1607344779Sdim if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1608344779Sdim continue; 1609344779Sdim 1610344779Sdim const MDNode *Scope = nullptr; 1611344779Sdim if (auto *DV = dyn_cast<DILocalVariable>(DN)) 1612344779Sdim Scope = DV->getScope(); 1613344779Sdim else if (auto *DL = dyn_cast<DILabel>(DN)) 1614344779Sdim Scope = DL->getScope(); 1615344779Sdim else 1616344779Sdim llvm_unreachable("Unexpected DI type!"); 1617344779Sdim 1618344779Sdim // Collect info for variables/labels that were optimized out. 1619344779Sdim ensureAbstractEntityIsCreated(TheCU, DN, Scope); 1620344779Sdim assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1621344779Sdim && "ensureAbstractEntityIsCreated inserted abstract scopes"); 1622210299Sed } 1623321369Sdim constructAbstractSubprogramScopeDIE(TheCU, AScope); 1624226633Sdim } 1625249423Sdim 1626314564Sdim ProcessedSPNodes.insert(SP); 1627344779Sdim DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope); 1628280031Sdim if (auto *SkelCU = TheCU.getSkeleton()) 1629314564Sdim if (!LScopes.getAbstractScopesList().empty() && 1630314564Sdim TheCU.getCUNode()->getSplitDebugInlining()) 1631314564Sdim SkelCU->constructSubprogramScopeDIE(SP, FnScope); 1632249423Sdim 1633344779Sdim // Construct call site entries. 1634344779Sdim constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF); 1635344779Sdim 1636193323Sed // Clear debug info 1637276479Sdim // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1638276479Sdim // DbgVariables except those that are also in AbstractVariables (since they 1639276479Sdim // can be used cross-function) 1640280031Sdim InfoHolder.getScopeVariables().clear(); 1641344779Sdim InfoHolder.getScopeLabels().clear(); 1642276479Sdim PrevLabel = nullptr; 1643276479Sdim CurFn = nullptr; 1644193323Sed} 1645193323Sed 1646249423Sdim// Register a source line with debug info. Returns the unique label that was 1647249423Sdim// emitted and which provides correspondence to the source line list. 1648223017Sdimvoid DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1649223017Sdim unsigned Flags) { 1650199989Srdivacky StringRef Fn; 1651341825Sdim unsigned FileNo = 1; 1652276479Sdim unsigned Discriminator = 0; 1653288943Sdim if (auto *Scope = cast_or_null<DIScope>(S)) { 1654288943Sdim Fn = Scope->getFilename(); 1655327952Sdim if (Line != 0 && getDwarfVersion() >= 4) 1656327952Sdim if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 1657314564Sdim Discriminator = LBF->getDiscriminator(); 1658193323Sed 1659288943Sdim unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID(); 1660341825Sdim FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID]) 1661341825Sdim .getOrCreateSourceID(Scope->getFile()); 1662208599Srdivacky } 1663341825Sdim Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0, 1664288943Sdim Discriminator, Fn); 1665193323Sed} 1666193323Sed 1667193323Sed//===----------------------------------------------------------------------===// 1668193323Sed// Emit Methods 1669193323Sed//===----------------------------------------------------------------------===// 1670193323Sed 1671249423Sdim// Emit the debug info section. 1672249423Sdimvoid DwarfDebug::emitDebugInfo() { 1673276479Sdim DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1674288943Sdim Holder.emitUnits(/* UseOffsets */ false); 1675249423Sdim} 1676249423Sdim 1677249423Sdim// Emit the abbreviation section. 1678249423Sdimvoid DwarfDebug::emitAbbreviations() { 1679276479Sdim DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1680249423Sdim 1681276479Sdim Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1682193323Sed} 1683193323Sed 1684341825Sdimvoid DwarfDebug::emitStringOffsetsTableHeader() { 1685341825Sdim DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1686341825Sdim Holder.getStringPool().emitStringOffsetsTableHeader( 1687341825Sdim *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(), 1688341825Sdim Holder.getStringOffsetsStartSym()); 1689341825Sdim} 1690341825Sdim 1691341825Sdimtemplate <typename AccelTableT> 1692341825Sdimvoid DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section, 1693288943Sdim StringRef TableName) { 1694288943Sdim Asm->OutStreamer->SwitchSection(Section); 1695212904Sdim 1696234353Sdim // Emit the full data. 1697341825Sdim emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol()); 1698234353Sdim} 1699212904Sdim 1700341825Sdimvoid DwarfDebug::emitAccelDebugNames() { 1701341825Sdim // Don't emit anything if we have no compilation units to index. 1702341825Sdim if (getUnits().empty()) 1703341825Sdim return; 1704341825Sdim 1705341825Sdim emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits()); 1706341825Sdim} 1707341825Sdim 1708280031Sdim// Emit visible names into a hashed accelerator table section. 1709280031Sdimvoid DwarfDebug::emitAccelNames() { 1710280031Sdim emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1711288943Sdim "Names"); 1712280031Sdim} 1713280031Sdim 1714249423Sdim// Emit objective C classes and categories into a hashed accelerator table 1715249423Sdim// section. 1716234353Sdimvoid DwarfDebug::emitAccelObjC() { 1717280031Sdim emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1718288943Sdim "ObjC"); 1719234353Sdim} 1720212904Sdim 1721249423Sdim// Emit namespace dies into a hashed accelerator table. 1722234353Sdimvoid DwarfDebug::emitAccelNamespaces() { 1723280031Sdim emitAccel(AccelNamespace, 1724280031Sdim Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1725288943Sdim "namespac"); 1726234353Sdim} 1727234353Sdim 1728249423Sdim// Emit type dies into a hashed accelerator table. 1729234353Sdimvoid DwarfDebug::emitAccelTypes() { 1730280031Sdim emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1731288943Sdim "types"); 1732193323Sed} 1733193323Sed 1734261991Sdim// Public name handling. 1735261991Sdim// The format for the various pubnames: 1736261991Sdim// 1737261991Sdim// dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1738261991Sdim// for the DIE that is named. 1739261991Sdim// 1740261991Sdim// gnu pubnames - offset/index value/name tuples where the offset is the offset 1741261991Sdim// into the CU and the index value is computed according to the type of value 1742261991Sdim// for the DIE that is named. 1743261991Sdim// 1744261991Sdim// For type units the offset is the offset of the skeleton DIE. For split dwarf 1745261991Sdim// it's the offset within the debug_info/debug_types dwo section, however, the 1746261991Sdim// reference in the pubname header doesn't change. 1747261991Sdim 1748261991Sdim/// computeIndexValue - Compute the gdb index value for the DIE and CU. 1749276479Sdimstatic dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1750276479Sdim const DIE *Die) { 1751321369Sdim // Entities that ended up only in a Type Unit reference the CU instead (since 1752321369Sdim // the pub entry has offsets within the CU there's no real offset that can be 1753321369Sdim // provided anyway). As it happens all such entities (namespaces and types, 1754321369Sdim // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out 1755321369Sdim // not to be true it would be necessary to persist this information from the 1756321369Sdim // point at which the entry is added to the index data structure - since by 1757321369Sdim // the time the index is built from that, the original type/namespace DIE in a 1758321369Sdim // type unit has already been destroyed so it can't be queried for properties 1759321369Sdim // like tag, etc. 1760321369Sdim if (Die->getTag() == dwarf::DW_TAG_compile_unit) 1761321369Sdim return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, 1762321369Sdim dwarf::GIEL_EXTERNAL); 1763261991Sdim dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1764261991Sdim 1765261991Sdim // We could have a specification DIE that has our most of our knowledge, 1766261991Sdim // look for that now. 1767288943Sdim if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 1768288943Sdim DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 1769276479Sdim if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1770261991Sdim Linkage = dwarf::GIEL_EXTERNAL; 1771261991Sdim } else if (Die->findAttribute(dwarf::DW_AT_external)) 1772261991Sdim Linkage = dwarf::GIEL_EXTERNAL; 1773261991Sdim 1774261991Sdim switch (Die->getTag()) { 1775261991Sdim case dwarf::DW_TAG_class_type: 1776261991Sdim case dwarf::DW_TAG_structure_type: 1777261991Sdim case dwarf::DW_TAG_union_type: 1778261991Sdim case dwarf::DW_TAG_enumeration_type: 1779261991Sdim return dwarf::PubIndexEntryDescriptor( 1780261991Sdim dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1781261991Sdim ? dwarf::GIEL_STATIC 1782261991Sdim : dwarf::GIEL_EXTERNAL); 1783261991Sdim case dwarf::DW_TAG_typedef: 1784261991Sdim case dwarf::DW_TAG_base_type: 1785261991Sdim case dwarf::DW_TAG_subrange_type: 1786261991Sdim return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1787261991Sdim case dwarf::DW_TAG_namespace: 1788261991Sdim return dwarf::GIEK_TYPE; 1789261991Sdim case dwarf::DW_TAG_subprogram: 1790261991Sdim return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1791261991Sdim case dwarf::DW_TAG_variable: 1792261991Sdim return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1793261991Sdim case dwarf::DW_TAG_enumerator: 1794261991Sdim return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1795261991Sdim dwarf::GIEL_STATIC); 1796261991Sdim default: 1797261991Sdim return dwarf::GIEK_NONE; 1798261991Sdim } 1799261991Sdim} 1800261991Sdim 1801327952Sdim/// emitDebugPubSections - Emit visible names and types into debug pubnames and 1802327952Sdim/// pubtypes sections. 1803327952Sdimvoid DwarfDebug::emitDebugPubSections() { 1804276479Sdim for (const auto &NU : CUMap) { 1805276479Sdim DwarfCompileUnit *TheU = NU.second; 1806327952Sdim if (!TheU->hasDwarfPubSections()) 1807327952Sdim continue; 1808276479Sdim 1809344779Sdim bool GnuStyle = TheU->getCUNode()->getNameTableKind() == 1810344779Sdim DICompileUnit::DebugNameTableKind::GNU; 1811276479Sdim 1812327952Sdim Asm->OutStreamer->SwitchSection( 1813327952Sdim GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1814327952Sdim : Asm->getObjFileLowering().getDwarfPubNamesSection()); 1815327952Sdim emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames()); 1816276479Sdim 1817327952Sdim Asm->OutStreamer->SwitchSection( 1818327952Sdim GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1819327952Sdim : Asm->getObjFileLowering().getDwarfPubTypesSection()); 1820327952Sdim emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes()); 1821327952Sdim } 1822327952Sdim} 1823276479Sdim 1824341825Sdimvoid DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) { 1825341825Sdim if (useSectionsAsReferences()) 1826341825Sdim Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(), 1827341825Sdim CU.getDebugSectionOffset()); 1828341825Sdim else 1829341825Sdim Asm->emitDwarfSymbolReference(CU.getLabelBegin()); 1830341825Sdim} 1831341825Sdim 1832327952Sdimvoid DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name, 1833327952Sdim DwarfCompileUnit *TheU, 1834327952Sdim const StringMap<const DIE *> &Globals) { 1835327952Sdim if (auto *Skeleton = TheU->getSkeleton()) 1836327952Sdim TheU = Skeleton; 1837249423Sdim 1838327952Sdim // Emit the header. 1839327952Sdim Asm->OutStreamer->AddComment("Length of Public " + Name + " Info"); 1840327952Sdim MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 1841327952Sdim MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 1842327952Sdim Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1843249423Sdim 1844327952Sdim Asm->OutStreamer->EmitLabel(BeginLabel); 1845249423Sdim 1846327952Sdim Asm->OutStreamer->AddComment("DWARF Version"); 1847341825Sdim Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); 1848249423Sdim 1849327952Sdim Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 1850341825Sdim emitSectionReference(*TheU); 1851249423Sdim 1852327952Sdim Asm->OutStreamer->AddComment("Compilation Unit Length"); 1853341825Sdim Asm->emitInt32(TheU->getLength()); 1854249423Sdim 1855327952Sdim // Emit the pubnames for this compilation unit. 1856327952Sdim for (const auto &GI : Globals) { 1857327952Sdim const char *Name = GI.getKeyData(); 1858327952Sdim const DIE *Entity = GI.second; 1859249423Sdim 1860327952Sdim Asm->OutStreamer->AddComment("DIE offset"); 1861341825Sdim Asm->emitInt32(Entity->getOffset()); 1862249423Sdim 1863327952Sdim if (GnuStyle) { 1864327952Sdim dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1865327952Sdim Asm->OutStreamer->AddComment( 1866344779Sdim Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + 1867344779Sdim ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1868341825Sdim Asm->emitInt8(Desc.toBits()); 1869249423Sdim } 1870249423Sdim 1871327952Sdim Asm->OutStreamer->AddComment("External Name"); 1872327952Sdim Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1873249423Sdim } 1874249423Sdim 1875327952Sdim Asm->OutStreamer->AddComment("End Mark"); 1876341825Sdim Asm->emitInt32(0); 1877327952Sdim Asm->OutStreamer->EmitLabel(EndLabel); 1878276479Sdim} 1879261991Sdim 1880309124Sdim/// Emit null-terminated strings into a debug str section. 1881276479Sdimvoid DwarfDebug::emitDebugStr() { 1882341825Sdim MCSection *StringOffsetsSection = nullptr; 1883341825Sdim if (useSegmentedStringOffsetsTable()) { 1884341825Sdim emitStringOffsetsTableHeader(); 1885341825Sdim StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection(); 1886341825Sdim } 1887276479Sdim DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1888341825Sdim Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(), 1889341825Sdim StringOffsetsSection, /* UseRelativeOffsets = */ true); 1890276479Sdim} 1891261991Sdim 1892276479Sdimvoid DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 1893288943Sdim const DebugLocStream::Entry &Entry) { 1894288943Sdim auto &&Comments = DebugLocs.getComments(Entry); 1895288943Sdim auto Comment = Comments.begin(); 1896288943Sdim auto End = Comments.end(); 1897288943Sdim for (uint8_t Byte : DebugLocs.getBytes(Entry)) 1898288943Sdim Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : ""); 1899280031Sdim} 1900280031Sdim 1901288943Sdimstatic void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 1902288943Sdim const DebugLocEntry::Value &Value, 1903314564Sdim DwarfExpression &DwarfExpr) { 1904321369Sdim auto *DIExpr = Value.getExpression(); 1905321369Sdim DIExpressionCursor ExprCursor(DIExpr); 1906321369Sdim DwarfExpr.addFragmentOffset(DIExpr); 1907280031Sdim // Regular entry. 1908276479Sdim if (Value.isInt()) { 1909288943Sdim if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 1910288943Sdim BT->getEncoding() == dwarf::DW_ATE_signed_char)) 1911321369Sdim DwarfExpr.addSignedConstant(Value.getInt()); 1912280031Sdim else 1913321369Sdim DwarfExpr.addUnsignedConstant(Value.getInt()); 1914276479Sdim } else if (Value.isLocation()) { 1915321369Sdim MachineLocation Location = Value.getLoc(); 1916321369Sdim if (Location.isIndirect()) 1917321369Sdim DwarfExpr.setMemoryLocationKind(); 1918327952Sdim DIExpressionCursor Cursor(DIExpr); 1919314564Sdim const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo(); 1920321369Sdim if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1921321369Sdim return; 1922321369Sdim return DwarfExpr.addExpression(std::move(Cursor)); 1923309124Sdim } else if (Value.isConstantFP()) { 1924309124Sdim APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt(); 1925321369Sdim DwarfExpr.addUnsignedConstant(RawBytes); 1926199989Srdivacky } 1927321369Sdim DwarfExpr.addExpression(std::move(ExprCursor)); 1928199989Srdivacky} 1929199989Srdivacky 1930288943Sdimvoid DebugLocEntry::finalize(const AsmPrinter &AP, 1931288943Sdim DebugLocStream::ListBuilder &List, 1932288943Sdim const DIBasicType *BT) { 1933344779Sdim assert(Begin != End && "unexpected location list entry with empty range"); 1934288943Sdim DebugLocStream::EntryBuilder Entry(List, Begin, End); 1935288943Sdim BufferByteStreamer Streamer = Entry.getStreamer(); 1936314564Sdim DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer); 1937288943Sdim const DebugLocEntry::Value &Value = Values[0]; 1938314564Sdim if (Value.isFragment()) { 1939314564Sdim // Emit all fragments that belong to the same variable and range. 1940327952Sdim assert(llvm::all_of(Values, [](DebugLocEntry::Value P) { 1941314564Sdim return P.isFragment(); 1942314564Sdim }) && "all values are expected to be fragments"); 1943288943Sdim assert(std::is_sorted(Values.begin(), Values.end()) && 1944314564Sdim "fragments are expected to be sorted"); 1945288943Sdim 1946314564Sdim for (auto Fragment : Values) 1947341825Sdim emitDebugLocValue(AP, BT, Fragment, DwarfExpr); 1948314564Sdim 1949288943Sdim } else { 1950314564Sdim assert(Values.size() == 1 && "only fragments may have >1 value"); 1951341825Sdim emitDebugLocValue(AP, BT, Value, DwarfExpr); 1952288943Sdim } 1953314564Sdim DwarfExpr.finalize(); 1954288943Sdim} 1955288943Sdim 1956288943Sdimvoid DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) { 1957288943Sdim // Emit the size. 1958288943Sdim Asm->OutStreamer->AddComment("Loc expr size"); 1959344779Sdim if (getDwarfVersion() >= 5) 1960344779Sdim Asm->EmitULEB128(DebugLocs.getBytes(Entry).size()); 1961344779Sdim else 1962344779Sdim Asm->emitInt16(DebugLocs.getBytes(Entry).size()); 1963276479Sdim // Emit the entry. 1964276479Sdim APByteStreamer Streamer(*Asm); 1965276479Sdim emitDebugLocEntry(Streamer, Entry); 1966193323Sed} 1967193323Sed 1968344779Sdim// Emit the common part of the DWARF 5 range/locations list tables header. 1969344779Sdimstatic void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder, 1970344779Sdim MCSymbol *TableStart, 1971344779Sdim MCSymbol *TableEnd) { 1972344779Sdim // Build the table header, which starts with the length field. 1973344779Sdim Asm->OutStreamer->AddComment("Length"); 1974344779Sdim Asm->EmitLabelDifference(TableEnd, TableStart, 4); 1975344779Sdim Asm->OutStreamer->EmitLabel(TableStart); 1976344779Sdim // Version number (DWARF v5 and later). 1977344779Sdim Asm->OutStreamer->AddComment("Version"); 1978344779Sdim Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion()); 1979344779Sdim // Address size. 1980344779Sdim Asm->OutStreamer->AddComment("Address size"); 1981344779Sdim Asm->emitInt8(Asm->MAI->getCodePointerSize()); 1982344779Sdim // Segment selector size. 1983344779Sdim Asm->OutStreamer->AddComment("Segment selector size"); 1984344779Sdim Asm->emitInt8(0); 1985344779Sdim} 1986344779Sdim 1987344779Sdim// Emit the header of a DWARF 5 range list table list table. Returns the symbol 1988344779Sdim// that designates the end of the table for the caller to emit when the table is 1989344779Sdim// complete. 1990344779Sdimstatic MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm, 1991344779Sdim const DwarfFile &Holder) { 1992344779Sdim MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start"); 1993344779Sdim MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end"); 1994344779Sdim emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 1995344779Sdim 1996344779Sdim Asm->OutStreamer->AddComment("Offset entry count"); 1997344779Sdim Asm->emitInt32(Holder.getRangeLists().size()); 1998344779Sdim Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym()); 1999344779Sdim 2000344779Sdim for (const RangeSpanList &List : Holder.getRangeLists()) 2001344779Sdim Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(), 2002344779Sdim 4); 2003344779Sdim 2004344779Sdim return TableEnd; 2005344779Sdim} 2006344779Sdim 2007344779Sdim// Emit the header of a DWARF 5 locations list table. Returns the symbol that 2008344779Sdim// designates the end of the table for the caller to emit when the table is 2009344779Sdim// complete. 2010344779Sdimstatic MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm, 2011344779Sdim const DwarfFile &Holder) { 2012344779Sdim MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start"); 2013344779Sdim MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end"); 2014344779Sdim emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 2015344779Sdim 2016344779Sdim // FIXME: Generate the offsets table and use DW_FORM_loclistx with the 2017344779Sdim // DW_AT_loclists_base attribute. Until then set the number of offsets to 0. 2018344779Sdim Asm->OutStreamer->AddComment("Offset entry count"); 2019344779Sdim Asm->emitInt32(0); 2020344779Sdim Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym()); 2021344779Sdim 2022344779Sdim return TableEnd; 2023344779Sdim} 2024344779Sdim 2025344779Sdim// Emit locations into the .debug_loc/.debug_rnglists section. 2026199989Srdivackyvoid DwarfDebug::emitDebugLoc() { 2027321369Sdim if (DebugLocs.getLists().empty()) 2028321369Sdim return; 2029321369Sdim 2030344779Sdim bool IsLocLists = getDwarfVersion() >= 5; 2031344779Sdim MCSymbol *TableEnd = nullptr; 2032344779Sdim if (IsLocLists) { 2033344779Sdim Asm->OutStreamer->SwitchSection( 2034344779Sdim Asm->getObjFileLowering().getDwarfLoclistsSection()); 2035344779Sdim TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder 2036344779Sdim : InfoHolder); 2037344779Sdim } else { 2038344779Sdim Asm->OutStreamer->SwitchSection( 2039344779Sdim Asm->getObjFileLowering().getDwarfLocSection()); 2040344779Sdim } 2041344779Sdim 2042321369Sdim unsigned char Size = Asm->MAI->getCodePointerSize(); 2043288943Sdim for (const auto &List : DebugLocs.getLists()) { 2044288943Sdim Asm->OutStreamer->EmitLabel(List.Label); 2045344779Sdim 2046288943Sdim const DwarfCompileUnit *CU = List.CU; 2047344779Sdim const MCSymbol *Base = CU->getBaseAddress(); 2048288943Sdim for (const auto &Entry : DebugLocs.getEntries(List)) { 2049344779Sdim if (Base) { 2050344779Sdim // Set up the range. This range is relative to the entry point of the 2051344779Sdim // compile unit. This is a hard coded 0 for low_pc when we're emitting 2052344779Sdim // ranges, or the DW_AT_low_pc on the compile unit otherwise. 2053344779Sdim if (IsLocLists) { 2054344779Sdim Asm->OutStreamer->AddComment("DW_LLE_offset_pair"); 2055344779Sdim Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1); 2056344779Sdim Asm->OutStreamer->AddComment(" starting offset"); 2057344779Sdim Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base); 2058344779Sdim Asm->OutStreamer->AddComment(" ending offset"); 2059344779Sdim Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base); 2060344779Sdim } else { 2061344779Sdim Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 2062344779Sdim Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 2063344779Sdim } 2064344779Sdim 2065344779Sdim emitDebugLocEntryLocation(Entry); 2066344779Sdim continue; 2067344779Sdim } 2068344779Sdim 2069344779Sdim // We have no base address. 2070344779Sdim if (IsLocLists) { 2071344779Sdim // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or 2072344779Sdim // DW_LLE_startx_length in case if there is only a single range. 2073344779Sdim // That should reduce the size of the debug data emited. 2074344779Sdim // For now just use the DW_LLE_startx_length for all cases. 2075344779Sdim Asm->OutStreamer->AddComment("DW_LLE_startx_length"); 2076344779Sdim Asm->emitInt8(dwarf::DW_LLE_startx_length); 2077344779Sdim Asm->OutStreamer->AddComment(" start idx"); 2078344779Sdim Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym)); 2079344779Sdim Asm->OutStreamer->AddComment(" length"); 2080344779Sdim Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym); 2081276479Sdim } else { 2082288943Sdim Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 2083288943Sdim Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 2084276479Sdim } 2085249423Sdim 2086276479Sdim emitDebugLocEntryLocation(Entry); 2087208599Srdivacky } 2088344779Sdim 2089344779Sdim if (IsLocLists) { 2090344779Sdim // .debug_loclists section ends with DW_LLE_end_of_list. 2091344779Sdim Asm->OutStreamer->AddComment("DW_LLE_end_of_list"); 2092344779Sdim Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1); 2093344779Sdim } else { 2094344779Sdim // Terminate the .debug_loc list with two 0 values. 2095344779Sdim Asm->OutStreamer->EmitIntValue(0, Size); 2096344779Sdim Asm->OutStreamer->EmitIntValue(0, Size); 2097344779Sdim } 2098208599Srdivacky } 2099344779Sdim 2100344779Sdim if (TableEnd) 2101344779Sdim Asm->OutStreamer->EmitLabel(TableEnd); 2102193323Sed} 2103193323Sed 2104276479Sdimvoid DwarfDebug::emitDebugLocDWO() { 2105288943Sdim Asm->OutStreamer->SwitchSection( 2106276479Sdim Asm->getObjFileLowering().getDwarfLocDWOSection()); 2107288943Sdim for (const auto &List : DebugLocs.getLists()) { 2108288943Sdim Asm->OutStreamer->EmitLabel(List.Label); 2109288943Sdim for (const auto &Entry : DebugLocs.getEntries(List)) { 2110344779Sdim // GDB only supports startx_length in pre-standard split-DWARF. 2111344779Sdim // (in v5 standard loclists, it currently* /only/ supports base_address + 2112344779Sdim // offset_pair, so the implementations can't really share much since they 2113344779Sdim // need to use different representations) 2114344779Sdim // * as of October 2018, at least 2115344779Sdim // Ideally/in v5, this could use SectionLabels to reuse existing addresses 2116344779Sdim // in the address pool to minimize object size/relocations. 2117341825Sdim Asm->emitInt8(dwarf::DW_LLE_startx_length); 2118288943Sdim unsigned idx = AddrPool.getIndex(Entry.BeginSym); 2119276479Sdim Asm->EmitULEB128(idx); 2120288943Sdim Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 2121261991Sdim 2122276479Sdim emitDebugLocEntryLocation(Entry); 2123276479Sdim } 2124341825Sdim Asm->emitInt8(dwarf::DW_LLE_end_of_list); 2125261991Sdim } 2126261991Sdim} 2127261991Sdim 2128261991Sdimstruct ArangeSpan { 2129261991Sdim const MCSymbol *Start, *End; 2130261991Sdim}; 2131261991Sdim 2132261991Sdim// Emit a debug aranges section, containing a CU lookup for any 2133261991Sdim// address we can tie back to a CU. 2134249423Sdimvoid DwarfDebug::emitDebugARanges() { 2135288943Sdim // Provides a unique id per text section. 2136288943Sdim MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 2137261991Sdim 2138288943Sdim // Filter labels by section. 2139288943Sdim for (const SymbolCU &SCU : ArangeLabels) { 2140288943Sdim if (SCU.Sym->isInSection()) { 2141288943Sdim // Make a note of this symbol and it's section. 2142288943Sdim MCSection *Section = &SCU.Sym->getSection(); 2143288943Sdim if (!Section->getKind().isMetadata()) 2144288943Sdim SectionMap[Section].push_back(SCU); 2145288943Sdim } else { 2146288943Sdim // Some symbols (e.g. common/bss on mach-o) can have no section but still 2147288943Sdim // appear in the output. This sucks as we rely on sections to build 2148288943Sdim // arange spans. We can do it without, but it's icky. 2149288943Sdim SectionMap[nullptr].push_back(SCU); 2150288943Sdim } 2151288943Sdim } 2152261991Sdim 2153288943Sdim DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 2154261991Sdim 2155288943Sdim for (auto &I : SectionMap) { 2156309124Sdim MCSection *Section = I.first; 2157288943Sdim SmallVector<SymbolCU, 8> &List = I.second; 2158309124Sdim if (List.size() < 1) 2159261991Sdim continue; 2160261991Sdim 2161288943Sdim // If we have no section (e.g. common), just write out 2162288943Sdim // individual spans for each symbol. 2163288943Sdim if (!Section) { 2164288943Sdim for (const SymbolCU &Cur : List) { 2165288943Sdim ArangeSpan Span; 2166288943Sdim Span.Start = Cur.Sym; 2167288943Sdim Span.End = nullptr; 2168309124Sdim assert(Cur.CU); 2169309124Sdim Spans[Cur.CU].push_back(Span); 2170288943Sdim } 2171288943Sdim continue; 2172288943Sdim } 2173288943Sdim 2174261991Sdim // Sort the symbols by offset within the section. 2175341825Sdim std::stable_sort( 2176309124Sdim List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) { 2177309124Sdim unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 2178309124Sdim unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 2179261991Sdim 2180309124Sdim // Symbols with no order assigned should be placed at the end. 2181309124Sdim // (e.g. section end labels) 2182309124Sdim if (IA == 0) 2183309124Sdim return false; 2184309124Sdim if (IB == 0) 2185309124Sdim return true; 2186309124Sdim return IA < IB; 2187309124Sdim }); 2188276479Sdim 2189309124Sdim // Insert a final terminator. 2190309124Sdim List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section))); 2191309124Sdim 2192288943Sdim // Build spans between each label. 2193288943Sdim const MCSymbol *StartSym = List[0].Sym; 2194288943Sdim for (size_t n = 1, e = List.size(); n < e; n++) { 2195288943Sdim const SymbolCU &Prev = List[n - 1]; 2196288943Sdim const SymbolCU &Cur = List[n]; 2197288943Sdim 2198288943Sdim // Try and build the longest span we can within the same CU. 2199288943Sdim if (Cur.CU != Prev.CU) { 2200261991Sdim ArangeSpan Span; 2201288943Sdim Span.Start = StartSym; 2202288943Sdim Span.End = Cur.Sym; 2203309124Sdim assert(Prev.CU); 2204288943Sdim Spans[Prev.CU].push_back(Span); 2205288943Sdim StartSym = Cur.Sym; 2206261991Sdim } 2207261991Sdim } 2208261991Sdim } 2209261991Sdim 2210288943Sdim // Start the dwarf aranges section. 2211288943Sdim Asm->OutStreamer->SwitchSection( 2212288943Sdim Asm->getObjFileLowering().getDwarfARangesSection()); 2213288943Sdim 2214321369Sdim unsigned PtrSize = Asm->MAI->getCodePointerSize(); 2215261991Sdim 2216261991Sdim // Build a list of CUs used. 2217276479Sdim std::vector<DwarfCompileUnit *> CUs; 2218276479Sdim for (const auto &it : Spans) { 2219276479Sdim DwarfCompileUnit *CU = it.first; 2220261991Sdim CUs.push_back(CU); 2221261991Sdim } 2222261991Sdim 2223261991Sdim // Sort the CU list (again, to ensure consistent output order). 2224344779Sdim llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 2225344779Sdim return A->getUniqueID() < B->getUniqueID(); 2226344779Sdim }); 2227261991Sdim 2228261991Sdim // Emit an arange table for each CU we used. 2229276479Sdim for (DwarfCompileUnit *CU : CUs) { 2230261991Sdim std::vector<ArangeSpan> &List = Spans[CU]; 2231261991Sdim 2232280031Sdim // Describe the skeleton CU's offset and length, not the dwo file's. 2233280031Sdim if (auto *Skel = CU->getSkeleton()) 2234280031Sdim CU = Skel; 2235280031Sdim 2236261991Sdim // Emit size of content not including length itself. 2237276479Sdim unsigned ContentSize = 2238276479Sdim sizeof(int16_t) + // DWARF ARange version number 2239276479Sdim sizeof(int32_t) + // Offset of CU in the .debug_info section 2240276479Sdim sizeof(int8_t) + // Pointer Size (in bytes) 2241276479Sdim sizeof(int8_t); // Segment Size (in bytes) 2242261991Sdim 2243261991Sdim unsigned TupleSize = PtrSize * 2; 2244261991Sdim 2245261991Sdim // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 2246276479Sdim unsigned Padding = 2247276479Sdim OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 2248261991Sdim 2249261991Sdim ContentSize += Padding; 2250261991Sdim ContentSize += (List.size() + 1) * TupleSize; 2251261991Sdim 2252261991Sdim // For each compile unit, write the list of spans it covers. 2253288943Sdim Asm->OutStreamer->AddComment("Length of ARange Set"); 2254341825Sdim Asm->emitInt32(ContentSize); 2255288943Sdim Asm->OutStreamer->AddComment("DWARF Arange version number"); 2256341825Sdim Asm->emitInt16(dwarf::DW_ARANGES_VERSION); 2257288943Sdim Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 2258341825Sdim emitSectionReference(*CU); 2259288943Sdim Asm->OutStreamer->AddComment("Address Size (in bytes)"); 2260341825Sdim Asm->emitInt8(PtrSize); 2261288943Sdim Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 2262341825Sdim Asm->emitInt8(0); 2263261991Sdim 2264309124Sdim Asm->OutStreamer->emitFill(Padding, 0xff); 2265261991Sdim 2266276479Sdim for (const ArangeSpan &Span : List) { 2267261991Sdim Asm->EmitLabelReference(Span.Start, PtrSize); 2268261991Sdim 2269261991Sdim // Calculate the size as being from the span start to it's end. 2270261991Sdim if (Span.End) { 2271261991Sdim Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 2272261991Sdim } else { 2273261991Sdim // For symbols without an end marker (e.g. common), we 2274261991Sdim // write a single arange entry containing just that one symbol. 2275261991Sdim uint64_t Size = SymSize[Span.Start]; 2276261991Sdim if (Size == 0) 2277261991Sdim Size = 1; 2278261991Sdim 2279288943Sdim Asm->OutStreamer->EmitIntValue(Size, PtrSize); 2280261991Sdim } 2281261991Sdim } 2282261991Sdim 2283288943Sdim Asm->OutStreamer->AddComment("ARange terminator"); 2284288943Sdim Asm->OutStreamer->EmitIntValue(0, PtrSize); 2285288943Sdim Asm->OutStreamer->EmitIntValue(0, PtrSize); 2286261991Sdim } 2287193323Sed} 2288193323Sed 2289341825Sdim/// Emit a single range list. We handle both DWARF v5 and earlier. 2290344779Sdimstatic void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, 2291341825Sdim const RangeSpanList &List) { 2292341825Sdim 2293344779Sdim auto DwarfVersion = DD.getDwarfVersion(); 2294341825Sdim // Emit our symbol so we can find the beginning of the range. 2295341825Sdim Asm->OutStreamer->EmitLabel(List.getSym()); 2296341825Sdim // Gather all the ranges that apply to the same section so they can share 2297341825Sdim // a base address entry. 2298341825Sdim MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges; 2299341825Sdim // Size for our labels. 2300341825Sdim auto Size = Asm->MAI->getCodePointerSize(); 2301341825Sdim 2302341825Sdim for (const RangeSpan &Range : List.getRanges()) 2303341825Sdim SectionRanges[&Range.getStart()->getSection()].push_back(&Range); 2304341825Sdim 2305344779Sdim const DwarfCompileUnit &CU = List.getCU(); 2306344779Sdim const MCSymbol *CUBase = CU.getBaseAddress(); 2307341825Sdim bool BaseIsSet = false; 2308341825Sdim for (const auto &P : SectionRanges) { 2309341825Sdim // Don't bother with a base address entry if there's only one range in 2310341825Sdim // this section in this range list - for example ranges for a CU will 2311341825Sdim // usually consist of single regions from each of many sections 2312341825Sdim // (-ffunction-sections, or just C++ inline functions) except under LTO 2313341825Sdim // or optnone where there may be holes in a single CU's section 2314341825Sdim // contributions. 2315341825Sdim auto *Base = CUBase; 2316344779Sdim if (!Base && (P.second.size() > 1 || DwarfVersion < 5) && 2317344779Sdim (CU.getCUNode()->getRangesBaseAddress() || DwarfVersion >= 5)) { 2318341825Sdim BaseIsSet = true; 2319341825Sdim // FIXME/use care: This may not be a useful base address if it's not 2320341825Sdim // the lowest address/range in this object. 2321341825Sdim Base = P.second.front()->getStart(); 2322341825Sdim if (DwarfVersion >= 5) { 2323344779Sdim Base = DD.getSectionLabel(&Base->getSection()); 2324344779Sdim Asm->OutStreamer->AddComment("DW_RLE_base_addressx"); 2325344779Sdim Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1); 2326344779Sdim Asm->OutStreamer->AddComment(" base address index"); 2327344779Sdim Asm->EmitULEB128(DD.getAddressPool().getIndex(Base)); 2328344779Sdim } else { 2329341825Sdim Asm->OutStreamer->EmitIntValue(-1, Size); 2330344779Sdim Asm->OutStreamer->AddComment(" base address"); 2331344779Sdim Asm->OutStreamer->EmitSymbolValue(Base, Size); 2332344779Sdim } 2333341825Sdim } else if (BaseIsSet && DwarfVersion < 5) { 2334341825Sdim BaseIsSet = false; 2335341825Sdim assert(!Base); 2336341825Sdim Asm->OutStreamer->EmitIntValue(-1, Size); 2337341825Sdim Asm->OutStreamer->EmitIntValue(0, Size); 2338341825Sdim } 2339341825Sdim 2340341825Sdim for (const auto *RS : P.second) { 2341341825Sdim const MCSymbol *Begin = RS->getStart(); 2342341825Sdim const MCSymbol *End = RS->getEnd(); 2343341825Sdim assert(Begin && "Range without a begin symbol?"); 2344341825Sdim assert(End && "Range without an end symbol?"); 2345341825Sdim if (Base) { 2346341825Sdim if (DwarfVersion >= 5) { 2347341825Sdim // Emit DW_RLE_offset_pair when we have a base. 2348341825Sdim Asm->OutStreamer->AddComment("DW_RLE_offset_pair"); 2349341825Sdim Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1); 2350341825Sdim Asm->OutStreamer->AddComment(" starting offset"); 2351341825Sdim Asm->EmitLabelDifferenceAsULEB128(Begin, Base); 2352341825Sdim Asm->OutStreamer->AddComment(" ending offset"); 2353341825Sdim Asm->EmitLabelDifferenceAsULEB128(End, Base); 2354341825Sdim } else { 2355341825Sdim Asm->EmitLabelDifference(Begin, Base, Size); 2356341825Sdim Asm->EmitLabelDifference(End, Base, Size); 2357341825Sdim } 2358341825Sdim } else if (DwarfVersion >= 5) { 2359344779Sdim Asm->OutStreamer->AddComment("DW_RLE_startx_length"); 2360344779Sdim Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1); 2361344779Sdim Asm->OutStreamer->AddComment(" start index"); 2362344779Sdim Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin)); 2363341825Sdim Asm->OutStreamer->AddComment(" length"); 2364341825Sdim Asm->EmitLabelDifferenceAsULEB128(End, Begin); 2365341825Sdim } else { 2366341825Sdim Asm->OutStreamer->EmitSymbolValue(Begin, Size); 2367341825Sdim Asm->OutStreamer->EmitSymbolValue(End, Size); 2368341825Sdim } 2369341825Sdim } 2370341825Sdim } 2371341825Sdim if (DwarfVersion >= 5) { 2372341825Sdim Asm->OutStreamer->AddComment("DW_RLE_end_of_list"); 2373341825Sdim Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1); 2374341825Sdim } else { 2375341825Sdim // Terminate the list with two 0 values. 2376341825Sdim Asm->OutStreamer->EmitIntValue(0, Size); 2377341825Sdim Asm->OutStreamer->EmitIntValue(0, Size); 2378341825Sdim } 2379341825Sdim} 2380341825Sdim 2381344779Sdimstatic void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm, 2382344779Sdim const DwarfFile &Holder, MCSymbol *TableEnd) { 2383344779Sdim for (const RangeSpanList &List : Holder.getRangeLists()) 2384344779Sdim emitRangeList(DD, Asm, List); 2385341825Sdim 2386344779Sdim if (TableEnd) 2387344779Sdim Asm->OutStreamer->EmitLabel(TableEnd); 2388341825Sdim} 2389341825Sdim 2390341825Sdim/// Emit address ranges into the .debug_ranges section or into the DWARF v5 2391341825Sdim/// .debug_rnglists section. 2392199989Srdivackyvoid DwarfDebug::emitDebugRanges() { 2393321369Sdim if (CUMap.empty()) 2394321369Sdim return; 2395321369Sdim 2396344779Sdim const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2397341825Sdim 2398344779Sdim if (Holder.getRangeLists().empty()) 2399341825Sdim return; 2400341825Sdim 2401344779Sdim assert(useRangesSection()); 2402344779Sdim assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2403344779Sdim return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2404344779Sdim })); 2405341825Sdim 2406193323Sed // Start the dwarf ranges section. 2407341825Sdim MCSymbol *TableEnd = nullptr; 2408341825Sdim if (getDwarfVersion() >= 5) { 2409341825Sdim Asm->OutStreamer->SwitchSection( 2410341825Sdim Asm->getObjFileLowering().getDwarfRnglistsSection()); 2411344779Sdim TableEnd = emitRnglistsTableHeader(Asm, Holder); 2412341825Sdim } else 2413341825Sdim Asm->OutStreamer->SwitchSection( 2414341825Sdim Asm->getObjFileLowering().getDwarfRangesSection()); 2415276479Sdim 2416344779Sdim emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2417344779Sdim} 2418276479Sdim 2419344779Sdimvoid DwarfDebug::emitDebugRangesDWO() { 2420344779Sdim assert(useSplitDwarf()); 2421280031Sdim 2422344779Sdim if (CUMap.empty()) 2423344779Sdim return; 2424276479Sdim 2425344779Sdim const auto &Holder = InfoHolder; 2426344779Sdim 2427344779Sdim if (Holder.getRangeLists().empty()) 2428344779Sdim return; 2429344779Sdim 2430344779Sdim assert(getDwarfVersion() >= 5); 2431344779Sdim assert(useRangesSection()); 2432344779Sdim assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2433344779Sdim return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2434344779Sdim })); 2435344779Sdim 2436344779Sdim // Start the dwarf ranges section. 2437344779Sdim Asm->OutStreamer->SwitchSection( 2438344779Sdim Asm->getObjFileLowering().getDwarfRnglistsDWOSection()); 2439344779Sdim MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder); 2440344779Sdim 2441344779Sdim emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2442193323Sed} 2443193323Sed 2444309124Sdimvoid DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 2445296417Sdim for (auto *MN : Nodes) { 2446296417Sdim if (auto *M = dyn_cast<DIMacro>(MN)) 2447309124Sdim emitMacro(*M); 2448296417Sdim else if (auto *F = dyn_cast<DIMacroFile>(MN)) 2449309124Sdim emitMacroFile(*F, U); 2450296417Sdim else 2451296417Sdim llvm_unreachable("Unexpected DI type!"); 2452296417Sdim } 2453296417Sdim} 2454296417Sdim 2455309124Sdimvoid DwarfDebug::emitMacro(DIMacro &M) { 2456309124Sdim Asm->EmitULEB128(M.getMacinfoType()); 2457309124Sdim Asm->EmitULEB128(M.getLine()); 2458296417Sdim StringRef Name = M.getName(); 2459296417Sdim StringRef Value = M.getValue(); 2460309124Sdim Asm->OutStreamer->EmitBytes(Name); 2461296417Sdim if (!Value.empty()) { 2462296417Sdim // There should be one space between macro name and macro value. 2463341825Sdim Asm->emitInt8(' '); 2464309124Sdim Asm->OutStreamer->EmitBytes(Value); 2465296417Sdim } 2466341825Sdim Asm->emitInt8('\0'); 2467296417Sdim} 2468296417Sdim 2469309124Sdimvoid DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 2470296417Sdim assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 2471309124Sdim Asm->EmitULEB128(dwarf::DW_MACINFO_start_file); 2472309124Sdim Asm->EmitULEB128(F.getLine()); 2473341825Sdim Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile())); 2474309124Sdim handleMacroNodes(F.getElements(), U); 2475309124Sdim Asm->EmitULEB128(dwarf::DW_MACINFO_end_file); 2476296417Sdim} 2477296417Sdim 2478309124Sdim/// Emit macros into a debug macinfo section. 2479296417Sdimvoid DwarfDebug::emitDebugMacinfo() { 2480321369Sdim if (CUMap.empty()) 2481321369Sdim return; 2482321369Sdim 2483344779Sdim if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2484344779Sdim return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2485344779Sdim })) 2486344779Sdim return; 2487344779Sdim 2488309124Sdim // Start the dwarf macinfo section. 2489309124Sdim Asm->OutStreamer->SwitchSection( 2490309124Sdim Asm->getObjFileLowering().getDwarfMacinfoSection()); 2491309124Sdim 2492296417Sdim for (const auto &P : CUMap) { 2493296417Sdim auto &TheCU = *P.second; 2494344779Sdim if (TheCU.getCUNode()->isDebugDirectivesOnly()) 2495344779Sdim continue; 2496296417Sdim auto *SkCU = TheCU.getSkeleton(); 2497296417Sdim DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 2498296417Sdim auto *CUNode = cast<DICompileUnit>(P.first); 2499341825Sdim DIMacroNodeArray Macros = CUNode->getMacros(); 2500341825Sdim if (!Macros.empty()) { 2501341825Sdim Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin()); 2502341825Sdim handleMacroNodes(Macros, U); 2503341825Sdim } 2504296417Sdim } 2505296417Sdim Asm->OutStreamer->AddComment("End Of Macro List Mark"); 2506341825Sdim Asm->emitInt8(0); 2507296417Sdim} 2508296417Sdim 2509249423Sdim// DWARF5 Experimental Separate Dwarf emitters. 2510249423Sdim 2511276479Sdimvoid DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 2512309124Sdim std::unique_ptr<DwarfCompileUnit> NewU) { 2513249423Sdim 2514276479Sdim if (!CompilationDir.empty()) 2515280031Sdim NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2516249423Sdim 2517276479Sdim addGnuPubAttributes(*NewU, Die); 2518249423Sdim 2519276479Sdim SkeletonHolder.addUnit(std::move(NewU)); 2520276479Sdim} 2521249423Sdim 2522276479SdimDwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 2523249423Sdim 2524327952Sdim auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 2525276479Sdim CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 2526276479Sdim DwarfCompileUnit &NewCU = *OwnedUnit; 2527314564Sdim NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 2528249423Sdim 2529288943Sdim NewCU.initStmtList(); 2530249423Sdim 2531341825Sdim if (useSegmentedStringOffsetsTable()) 2532341825Sdim NewCU.addStringOffsetsStart(); 2533341825Sdim 2534276479Sdim initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 2535261991Sdim 2536276479Sdim return NewCU; 2537276479Sdim} 2538261991Sdim 2539249423Sdim// Emit the .debug_info.dwo section for separated dwarf. This contains the 2540249423Sdim// compile units that would normally be in debug_info. 2541249423Sdimvoid DwarfDebug::emitDebugInfoDWO() { 2542249423Sdim assert(useSplitDwarf() && "No split dwarf debug info?"); 2543288943Sdim // Don't emit relocations into the dwo file. 2544288943Sdim InfoHolder.emitUnits(/* UseOffsets */ true); 2545249423Sdim} 2546249423Sdim 2547249423Sdim// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2548249423Sdim// abbreviations for the .debug_info.dwo section. 2549249423Sdimvoid DwarfDebug::emitDebugAbbrevDWO() { 2550249423Sdim assert(useSplitDwarf() && "No split dwarf?"); 2551276479Sdim InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2552249423Sdim} 2553249423Sdim 2554276479Sdimvoid DwarfDebug::emitDebugLineDWO() { 2555276479Sdim assert(useSplitDwarf() && "No split dwarf?"); 2556341825Sdim SplitTypeUnitFileTable.Emit( 2557341825Sdim *Asm->OutStreamer, MCDwarfLineTableParams(), 2558276479Sdim Asm->getObjFileLowering().getDwarfLineDWOSection()); 2559276479Sdim} 2560276479Sdim 2561341825Sdimvoid DwarfDebug::emitStringOffsetsTableHeaderDWO() { 2562341825Sdim assert(useSplitDwarf() && "No split dwarf?"); 2563341825Sdim InfoHolder.getStringPool().emitStringOffsetsTableHeader( 2564341825Sdim *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(), 2565341825Sdim InfoHolder.getStringOffsetsStartSym()); 2566341825Sdim} 2567341825Sdim 2568249423Sdim// Emit the .debug_str.dwo section for separated dwarf. This contains the 2569249423Sdim// string section and is identical in format to traditional .debug_str 2570249423Sdim// sections. 2571249423Sdimvoid DwarfDebug::emitDebugStrDWO() { 2572341825Sdim if (useSegmentedStringOffsetsTable()) 2573341825Sdim emitStringOffsetsTableHeaderDWO(); 2574249423Sdim assert(useSplitDwarf() && "No split dwarf?"); 2575288943Sdim MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2576249423Sdim InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2577341825Sdim OffSec, /* UseRelativeOffsets = */ false); 2578249423Sdim} 2579276479Sdim 2580344779Sdim// Emit address pool. 2581341825Sdimvoid DwarfDebug::emitDebugAddr() { 2582341825Sdim AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 2583341825Sdim} 2584341825Sdim 2585276479SdimMCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2586276479Sdim if (!useSplitDwarf()) 2587276479Sdim return nullptr; 2588341825Sdim const DICompileUnit *DIUnit = CU.getCUNode(); 2589341825Sdim SplitTypeUnitFileTable.maybeSetRootFile( 2590341825Sdim DIUnit->getDirectory(), DIUnit->getFilename(), 2591341825Sdim CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource()); 2592276479Sdim return &SplitTypeUnitFileTable; 2593276479Sdim} 2594276479Sdim 2595296417Sdimuint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 2596276479Sdim MD5 Hash; 2597276479Sdim Hash.update(Identifier); 2598276479Sdim // ... take the least significant 8 bytes and return those. Our MD5 2599321369Sdim // implementation always returns its results in little endian, so we actually 2600321369Sdim // need the "high" word. 2601276479Sdim MD5::MD5Result Result; 2602276479Sdim Hash.final(Result); 2603321369Sdim return Result.high(); 2604276479Sdim} 2605276479Sdim 2606276479Sdimvoid DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2607276479Sdim StringRef Identifier, DIE &RefDie, 2608288943Sdim const DICompositeType *CTy) { 2609276479Sdim // Fast path if we're building some type units and one has already used the 2610276479Sdim // address pool we know we're going to throw away all this work anyway, so 2611276479Sdim // don't bother building dependent types. 2612276479Sdim if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 2613276479Sdim return; 2614276479Sdim 2615309124Sdim auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 2616309124Sdim if (!Ins.second) { 2617309124Sdim CU.addDIETypeSignature(RefDie, Ins.first->second); 2618276479Sdim return; 2619276479Sdim } 2620276479Sdim 2621276479Sdim bool TopLevelType = TypeUnitsUnderConstruction.empty(); 2622276479Sdim AddrPool.resetUsedFlag(); 2623276479Sdim 2624327952Sdim auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 2625327952Sdim getDwoLineTable(CU)); 2626276479Sdim DwarfTypeUnit &NewTU = *OwnedUnit; 2627276479Sdim DIE &UnitDie = NewTU.getUnitDie(); 2628314564Sdim TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy); 2629276479Sdim 2630276479Sdim NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2631276479Sdim CU.getLanguage()); 2632276479Sdim 2633276479Sdim uint64_t Signature = makeTypeSignature(Identifier); 2634276479Sdim NewTU.setTypeSignature(Signature); 2635309124Sdim Ins.first->second = Signature; 2636276479Sdim 2637344779Sdim if (useSplitDwarf()) { 2638344779Sdim MCSection *Section = 2639344779Sdim getDwarfVersion() <= 4 2640344779Sdim ? Asm->getObjFileLowering().getDwarfTypesDWOSection() 2641344779Sdim : Asm->getObjFileLowering().getDwarfInfoDWOSection(); 2642344779Sdim NewTU.setSection(Section); 2643344779Sdim } else { 2644344779Sdim MCSection *Section = 2645344779Sdim getDwarfVersion() <= 4 2646344779Sdim ? Asm->getObjFileLowering().getDwarfTypesSection(Signature) 2647344779Sdim : Asm->getObjFileLowering().getDwarfInfoSection(Signature); 2648344779Sdim NewTU.setSection(Section); 2649341825Sdim // Non-split type units reuse the compile unit's line table. 2650276479Sdim CU.applyStmtList(UnitDie); 2651280031Sdim } 2652276479Sdim 2653341825Sdim // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 2654341825Sdim // units. 2655341825Sdim if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 2656341825Sdim NewTU.addStringOffsetsStart(); 2657341825Sdim 2658276479Sdim NewTU.setType(NewTU.createTypeDIE(CTy)); 2659276479Sdim 2660276479Sdim if (TopLevelType) { 2661276479Sdim auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 2662276479Sdim TypeUnitsUnderConstruction.clear(); 2663276479Sdim 2664276479Sdim // Types referencing entries in the address table cannot be placed in type 2665276479Sdim // units. 2666276479Sdim if (AddrPool.hasBeenUsed()) { 2667276479Sdim 2668276479Sdim // Remove all the types built while building this type. 2669276479Sdim // This is pessimistic as some of these types might not be dependent on 2670276479Sdim // the type that used an address. 2671276479Sdim for (const auto &TU : TypeUnitsToAdd) 2672309124Sdim TypeSignatures.erase(TU.second); 2673276479Sdim 2674276479Sdim // Construct this type in the CU directly. 2675276479Sdim // This is inefficient because all the dependent types will be rebuilt 2676276479Sdim // from scratch, including building them in type units, discovering that 2677276479Sdim // they depend on addresses, throwing them out and rebuilding them. 2678288943Sdim CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 2679276479Sdim return; 2680276479Sdim } 2681276479Sdim 2682276479Sdim // If the type wasn't dependent on fission addresses, finish adding the type 2683276479Sdim // and all its dependent types. 2684309124Sdim for (auto &TU : TypeUnitsToAdd) { 2685309124Sdim InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 2686309124Sdim InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 2687309124Sdim } 2688276479Sdim } 2689309124Sdim CU.addDIETypeSignature(RefDie, Signature); 2690276479Sdim} 2691276479Sdim 2692341825Sdim// Add the Name along with its companion DIE to the appropriate accelerator 2693341825Sdim// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for 2694341825Sdim// AccelTableKind::Apple, we use the table we got as an argument). If 2695341825Sdim// accelerator tables are disabled, this function does nothing. 2696341825Sdimtemplate <typename DataT> 2697344779Sdimvoid DwarfDebug::addAccelNameImpl(const DICompileUnit &CU, 2698344779Sdim AccelTable<DataT> &AppleAccel, StringRef Name, 2699341825Sdim const DIE &Die) { 2700341825Sdim if (getAccelTableKind() == AccelTableKind::None) 2701276479Sdim return; 2702341825Sdim 2703344779Sdim if (getAccelTableKind() != AccelTableKind::Apple && 2704344779Sdim CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 2705344779Sdim return; 2706344779Sdim 2707341825Sdim DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2708344779Sdim DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name); 2709341825Sdim 2710341825Sdim switch (getAccelTableKind()) { 2711341825Sdim case AccelTableKind::Apple: 2712341825Sdim AppleAccel.addName(Ref, Die); 2713341825Sdim break; 2714341825Sdim case AccelTableKind::Dwarf: 2715341825Sdim AccelDebugNames.addName(Ref, Die); 2716341825Sdim break; 2717341825Sdim case AccelTableKind::Default: 2718341825Sdim llvm_unreachable("Default should have already been resolved."); 2719341825Sdim case AccelTableKind::None: 2720341825Sdim llvm_unreachable("None handled above"); 2721341825Sdim } 2722276479Sdim} 2723276479Sdim 2724344779Sdimvoid DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name, 2725344779Sdim const DIE &Die) { 2726344779Sdim addAccelNameImpl(CU, AccelNames, Name, Die); 2727341825Sdim} 2728341825Sdim 2729344779Sdimvoid DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name, 2730344779Sdim const DIE &Die) { 2731341825Sdim // ObjC names go only into the Apple accelerator tables. 2732341825Sdim if (getAccelTableKind() == AccelTableKind::Apple) 2733344779Sdim addAccelNameImpl(CU, AccelObjC, Name, Die); 2734276479Sdim} 2735276479Sdim 2736344779Sdimvoid DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name, 2737344779Sdim const DIE &Die) { 2738344779Sdim addAccelNameImpl(CU, AccelNamespace, Name, Die); 2739276479Sdim} 2740276479Sdim 2741344779Sdimvoid DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name, 2742344779Sdim const DIE &Die, char Flags) { 2743344779Sdim addAccelNameImpl(CU, AccelTypes, Name, Die); 2744276479Sdim} 2745314564Sdim 2746314564Sdimuint16_t DwarfDebug::getDwarfVersion() const { 2747314564Sdim return Asm->OutStreamer->getContext().getDwarfVersion(); 2748314564Sdim} 2749344779Sdim 2750344779Sdimvoid DwarfDebug::addSectionLabel(const MCSymbol *Sym) { 2751344779Sdim SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym)); 2752344779Sdim} 2753344779Sdim 2754344779Sdimconst MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) { 2755344779Sdim return SectionLabels.find(S)->second; 2756344779Sdim} 2757