1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains support for writing dwarf debug info into asm files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "DwarfDebug.h" 14 #include "ByteStreamer.h" 15 #include "DIEHash.h" 16 #include "DebugLocEntry.h" 17 #include "DebugLocStream.h" 18 #include "DwarfCompileUnit.h" 19 #include "DwarfExpression.h" 20 #include "DwarfFile.h" 21 #include "DwarfUnit.h" 22 #include "llvm/ADT/APInt.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/DenseSet.h" 25 #include "llvm/ADT/MapVector.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/Triple.h" 30 #include "llvm/ADT/Twine.h" 31 #include "llvm/BinaryFormat/Dwarf.h" 32 #include "llvm/CodeGen/AccelTable.h" 33 #include "llvm/CodeGen/AsmPrinter.h" 34 #include "llvm/CodeGen/DIE.h" 35 #include "llvm/CodeGen/LexicalScopes.h" 36 #include "llvm/CodeGen/MachineBasicBlock.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineInstr.h" 39 #include "llvm/CodeGen/MachineModuleInfo.h" 40 #include "llvm/CodeGen/MachineOperand.h" 41 #include "llvm/CodeGen/TargetInstrInfo.h" 42 #include "llvm/CodeGen/TargetRegisterInfo.h" 43 #include "llvm/CodeGen/TargetSubtargetInfo.h" 44 #include "llvm/DebugInfo/DWARF/DWARFExpression.h" 45 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h" 46 #include "llvm/IR/Constants.h" 47 #include "llvm/IR/DebugInfoMetadata.h" 48 #include "llvm/IR/DebugLoc.h" 49 #include "llvm/IR/Function.h" 50 #include "llvm/IR/GlobalVariable.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/MC/MCAsmInfo.h" 53 #include "llvm/MC/MCContext.h" 54 #include "llvm/MC/MCDwarf.h" 55 #include "llvm/MC/MCSection.h" 56 #include "llvm/MC/MCStreamer.h" 57 #include "llvm/MC/MCSymbol.h" 58 #include "llvm/MC/MCTargetOptions.h" 59 #include "llvm/MC/MachineLocation.h" 60 #include "llvm/MC/SectionKind.h" 61 #include "llvm/Pass.h" 62 #include "llvm/Support/Casting.h" 63 #include "llvm/Support/CommandLine.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/MD5.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/Timer.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include "llvm/Target/TargetLoweringObjectFile.h" 71 #include "llvm/Target/TargetMachine.h" 72 #include "llvm/Target/TargetOptions.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstddef> 76 #include <cstdint> 77 #include <iterator> 78 #include <string> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 #define DEBUG_TYPE "dwarfdebug" 85 86 static cl::opt<bool> 87 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, 88 cl::desc("Disable debug info printing")); 89 90 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier( 91 "use-dwarf-ranges-base-address-specifier", cl::Hidden, 92 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false)); 93 94 static cl::opt<bool> GenerateARangeSection("generate-arange-section", 95 cl::Hidden, 96 cl::desc("Generate dwarf aranges"), 97 cl::init(false)); 98 99 static cl::opt<bool> 100 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, 101 cl::desc("Generate DWARF4 type units."), 102 cl::init(false)); 103 104 static cl::opt<bool> SplitDwarfCrossCuReferences( 105 "split-dwarf-cross-cu-references", cl::Hidden, 106 cl::desc("Enable cross-cu references in DWO files"), cl::init(false)); 107 108 enum DefaultOnOff { Default, Enable, Disable }; 109 110 static cl::opt<DefaultOnOff> UnknownLocations( 111 "use-unknown-locations", cl::Hidden, 112 cl::desc("Make an absence of debug location information explicit."), 113 cl::values(clEnumVal(Default, "At top of block or after label"), 114 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")), 115 cl::init(Default)); 116 117 static cl::opt<AccelTableKind> AccelTables( 118 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), 119 cl::values(clEnumValN(AccelTableKind::Default, "Default", 120 "Default for platform"), 121 clEnumValN(AccelTableKind::None, "Disable", "Disabled."), 122 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), 123 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), 124 cl::init(AccelTableKind::Default)); 125 126 static cl::opt<DefaultOnOff> 127 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden, 128 cl::desc("Use inlined strings rather than string section."), 129 cl::values(clEnumVal(Default, "Default for platform"), 130 clEnumVal(Enable, "Enabled"), 131 clEnumVal(Disable, "Disabled")), 132 cl::init(Default)); 133 134 static cl::opt<bool> 135 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, 136 cl::desc("Disable emission .debug_ranges section."), 137 cl::init(false)); 138 139 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences( 140 "dwarf-sections-as-references", cl::Hidden, 141 cl::desc("Use sections+offset as references rather than labels."), 142 cl::values(clEnumVal(Default, "Default for platform"), 143 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), 144 cl::init(Default)); 145 146 enum LinkageNameOption { 147 DefaultLinkageNames, 148 AllLinkageNames, 149 AbstractLinkageNames 150 }; 151 152 static cl::opt<LinkageNameOption> 153 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden, 154 cl::desc("Which DWARF linkage-name attributes to emit."), 155 cl::values(clEnumValN(DefaultLinkageNames, "Default", 156 "Default for platform"), 157 clEnumValN(AllLinkageNames, "All", "All"), 158 clEnumValN(AbstractLinkageNames, "Abstract", 159 "Abstract subprograms")), 160 cl::init(DefaultLinkageNames)); 161 162 static const char *const DWARFGroupName = "dwarf"; 163 static const char *const DWARFGroupDescription = "DWARF Emission"; 164 static const char *const DbgTimerName = "writer"; 165 static const char *const DbgTimerDescription = "DWARF Debug Writer"; 166 static constexpr unsigned ULEB128PadSize = 4; 167 168 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) { 169 BS.EmitInt8( 170 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op) 171 : dwarf::OperationEncodingString(Op)); 172 } 173 174 void DebugLocDwarfExpression::emitSigned(int64_t Value) { 175 BS.EmitSLEB128(Value, Twine(Value)); 176 } 177 178 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) { 179 BS.EmitULEB128(Value, Twine(Value)); 180 } 181 182 void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) { 183 assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit"); 184 BS.EmitULEB128(Idx, Twine(Idx), ULEB128PadSize); 185 } 186 187 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI, 188 unsigned MachineReg) { 189 // This information is not available while emitting .debug_loc entries. 190 return false; 191 } 192 193 bool DbgVariable::isBlockByrefVariable() const { 194 assert(getVariable() && "Invalid complex DbgVariable!"); 195 return getVariable()->getType().resolve()->isBlockByrefStruct(); 196 } 197 198 const DIType *DbgVariable::getType() const { 199 DIType *Ty = getVariable()->getType().resolve(); 200 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 201 // addresses instead. 202 if (Ty->isBlockByrefStruct()) { 203 /* Byref variables, in Blocks, are declared by the programmer as 204 "SomeType VarName;", but the compiler creates a 205 __Block_byref_x_VarName struct, and gives the variable VarName 206 either the struct, or a pointer to the struct, as its type. This 207 is necessary for various behind-the-scenes things the compiler 208 needs to do with by-reference variables in blocks. 209 210 However, as far as the original *programmer* is concerned, the 211 variable should still have type 'SomeType', as originally declared. 212 213 The following function dives into the __Block_byref_x_VarName 214 struct to find the original type of the variable. This will be 215 passed back to the code generating the type for the Debug 216 Information Entry for the variable 'VarName'. 'VarName' will then 217 have the original type 'SomeType' in its debug information. 218 219 The original type 'SomeType' will be the type of the field named 220 'VarName' inside the __Block_byref_x_VarName struct. 221 222 NOTE: In order for this to not completely fail on the debugger 223 side, the Debug Information Entry for the variable VarName needs to 224 have a DW_AT_location that tells the debugger how to unwind through 225 the pointers and __Block_byref_x_VarName struct to find the actual 226 value of the variable. The function addBlockByrefType does this. */ 227 DIType *subType = Ty; 228 uint16_t tag = Ty->getTag(); 229 230 if (tag == dwarf::DW_TAG_pointer_type) 231 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType()); 232 233 auto Elements = cast<DICompositeType>(subType)->getElements(); 234 for (unsigned i = 0, N = Elements.size(); i < N; ++i) { 235 auto *DT = cast<DIDerivedType>(Elements[i]); 236 if (getName() == DT->getName()) 237 return resolve(DT->getBaseType()); 238 } 239 } 240 return Ty; 241 } 242 243 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const { 244 if (FrameIndexExprs.size() == 1) 245 return FrameIndexExprs; 246 247 assert(llvm::all_of(FrameIndexExprs, 248 [](const FrameIndexExpr &A) { 249 return A.Expr->isFragment(); 250 }) && 251 "multiple FI expressions without DW_OP_LLVM_fragment"); 252 llvm::sort(FrameIndexExprs, 253 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool { 254 return A.Expr->getFragmentInfo()->OffsetInBits < 255 B.Expr->getFragmentInfo()->OffsetInBits; 256 }); 257 258 return FrameIndexExprs; 259 } 260 261 void DbgVariable::addMMIEntry(const DbgVariable &V) { 262 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry"); 263 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry"); 264 assert(V.getVariable() == getVariable() && "conflicting variable"); 265 assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location"); 266 267 assert(!FrameIndexExprs.empty() && "Expected an MMI entry"); 268 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry"); 269 270 // FIXME: This logic should not be necessary anymore, as we now have proper 271 // deduplication. However, without it, we currently run into the assertion 272 // below, which means that we are likely dealing with broken input, i.e. two 273 // non-fragment entries for the same variable at different frame indices. 274 if (FrameIndexExprs.size()) { 275 auto *Expr = FrameIndexExprs.back().Expr; 276 if (!Expr || !Expr->isFragment()) 277 return; 278 } 279 280 for (const auto &FIE : V.FrameIndexExprs) 281 // Ignore duplicate entries. 282 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) { 283 return FIE.FI == Other.FI && FIE.Expr == Other.Expr; 284 })) 285 FrameIndexExprs.push_back(FIE); 286 287 assert((FrameIndexExprs.size() == 1 || 288 llvm::all_of(FrameIndexExprs, 289 [](FrameIndexExpr &FIE) { 290 return FIE.Expr && FIE.Expr->isFragment(); 291 })) && 292 "conflicting locations for variable"); 293 } 294 295 static AccelTableKind computeAccelTableKind(unsigned DwarfVersion, 296 bool GenerateTypeUnits, 297 DebuggerKind Tuning, 298 const Triple &TT) { 299 // Honor an explicit request. 300 if (AccelTables != AccelTableKind::Default) 301 return AccelTables; 302 303 // Accelerator tables with type units are currently not supported. 304 if (GenerateTypeUnits) 305 return AccelTableKind::None; 306 307 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5 308 // always implies debug_names. For lower standard versions we use apple 309 // accelerator tables on apple platforms and debug_names elsewhere. 310 if (DwarfVersion >= 5) 311 return AccelTableKind::Dwarf; 312 if (Tuning == DebuggerKind::LLDB) 313 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple 314 : AccelTableKind::Dwarf; 315 return AccelTableKind::None; 316 } 317 318 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 319 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()), 320 InfoHolder(A, "info_string", DIEValueAllocator), 321 SkeletonHolder(A, "skel_string", DIEValueAllocator), 322 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) { 323 const Triple &TT = Asm->TM.getTargetTriple(); 324 325 // Make sure we know our "debugger tuning". The target option takes 326 // precedence; fall back to triple-based defaults. 327 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default) 328 DebuggerTuning = Asm->TM.Options.DebuggerTuning; 329 else if (IsDarwin) 330 DebuggerTuning = DebuggerKind::LLDB; 331 else if (TT.isPS4CPU()) 332 DebuggerTuning = DebuggerKind::SCE; 333 else 334 DebuggerTuning = DebuggerKind::GDB; 335 336 if (DwarfInlinedStrings == Default) 337 UseInlineStrings = TT.isNVPTX(); 338 else 339 UseInlineStrings = DwarfInlinedStrings == Enable; 340 341 UseLocSection = !TT.isNVPTX(); 342 343 HasAppleExtensionAttributes = tuneForLLDB(); 344 345 // Handle split DWARF. 346 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty(); 347 348 // SCE defaults to linkage names only for abstract subprograms. 349 if (DwarfLinkageNames == DefaultLinkageNames) 350 UseAllLinkageNames = !tuneForSCE(); 351 else 352 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames; 353 354 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion; 355 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber 356 : MMI->getModule()->getDwarfVersion(); 357 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2. 358 DwarfVersion = 359 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION); 360 361 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX(); 362 363 // Use sections as references. Force for NVPTX. 364 if (DwarfSectionsAsReferences == Default) 365 UseSectionsAsReferences = TT.isNVPTX(); 366 else 367 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable; 368 369 // Don't generate type units for unsupported object file formats. 370 GenerateTypeUnits = 371 A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits; 372 373 TheAccelTableKind = computeAccelTableKind( 374 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple()); 375 376 // Work around a GDB bug. GDB doesn't support the standard opcode; 377 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which 378 // is defined as of DWARF 3. 379 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented 380 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616 381 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3; 382 383 // GDB does not fully support the DWARF 4 representation for bitfields. 384 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB(); 385 386 // The DWARF v5 string offsets table has - possibly shared - contributions 387 // from each compile and type unit each preceded by a header. The string 388 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses 389 // a monolithic string offsets table without any header. 390 UseSegmentedStringOffsetsTable = DwarfVersion >= 5; 391 392 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion); 393 } 394 395 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h. 396 DwarfDebug::~DwarfDebug() = default; 397 398 static bool isObjCClass(StringRef Name) { 399 return Name.startswith("+") || Name.startswith("-"); 400 } 401 402 static bool hasObjCCategory(StringRef Name) { 403 if (!isObjCClass(Name)) 404 return false; 405 406 return Name.find(") ") != StringRef::npos; 407 } 408 409 static void getObjCClassCategory(StringRef In, StringRef &Class, 410 StringRef &Category) { 411 if (!hasObjCCategory(In)) { 412 Class = In.slice(In.find('[') + 1, In.find(' ')); 413 Category = ""; 414 return; 415 } 416 417 Class = In.slice(In.find('[') + 1, In.find('(')); 418 Category = In.slice(In.find('[') + 1, In.find(' ')); 419 } 420 421 static StringRef getObjCMethodName(StringRef In) { 422 return In.slice(In.find(' ') + 1, In.find(']')); 423 } 424 425 // Add the various names to the Dwarf accelerator table names. 426 void DwarfDebug::addSubprogramNames(const DICompileUnit &CU, 427 const DISubprogram *SP, DIE &Die) { 428 if (getAccelTableKind() != AccelTableKind::Apple && 429 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 430 return; 431 432 if (!SP->isDefinition()) 433 return; 434 435 if (SP->getName() != "") 436 addAccelName(CU, SP->getName(), Die); 437 438 // If the linkage name is different than the name, go ahead and output that as 439 // well into the name table. Only do that if we are going to actually emit 440 // that name. 441 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() && 442 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP))) 443 addAccelName(CU, SP->getLinkageName(), Die); 444 445 // If this is an Objective-C selector name add it to the ObjC accelerator 446 // too. 447 if (isObjCClass(SP->getName())) { 448 StringRef Class, Category; 449 getObjCClassCategory(SP->getName(), Class, Category); 450 addAccelObjC(CU, Class, Die); 451 if (Category != "") 452 addAccelObjC(CU, Category, Die); 453 // Also add the base method name to the name table. 454 addAccelName(CU, getObjCMethodName(SP->getName()), Die); 455 } 456 } 457 458 /// Check whether we should create a DIE for the given Scope, return true 459 /// if we don't create a DIE (the corresponding DIE is null). 460 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) { 461 if (Scope->isAbstractScope()) 462 return false; 463 464 // We don't create a DIE if there is no Range. 465 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges(); 466 if (Ranges.empty()) 467 return true; 468 469 if (Ranges.size() > 1) 470 return false; 471 472 // We don't create a DIE if we have a single Range and the end label 473 // is null. 474 return !getLabelAfterInsn(Ranges.front().second); 475 } 476 477 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) { 478 F(CU); 479 if (auto *SkelCU = CU.getSkeleton()) 480 if (CU.getCUNode()->getSplitDebugInlining()) 481 F(*SkelCU); 482 } 483 484 bool DwarfDebug::shareAcrossDWOCUs() const { 485 return SplitDwarfCrossCuReferences; 486 } 487 488 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, 489 LexicalScope *Scope) { 490 assert(Scope && Scope->getScopeNode()); 491 assert(Scope->isAbstractScope()); 492 assert(!Scope->getInlinedAt()); 493 494 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 495 496 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 497 // was inlined from another compile unit. 498 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining()) 499 // Avoid building the original CU if it won't be used 500 SrcCU.constructAbstractSubprogramScopeDIE(Scope); 501 else { 502 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 503 if (auto *SkelCU = CU.getSkeleton()) { 504 (shareAcrossDWOCUs() ? CU : SrcCU) 505 .constructAbstractSubprogramScopeDIE(Scope); 506 if (CU.getCUNode()->getSplitDebugInlining()) 507 SkelCU->constructAbstractSubprogramScopeDIE(Scope); 508 } else 509 CU.constructAbstractSubprogramScopeDIE(Scope); 510 } 511 } 512 513 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP, 514 DwarfCompileUnit &CU, DIE &ScopeDIE, 515 const MachineFunction &MF) { 516 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if 517 // the subprogram is required to have one. 518 if (!SP.areAllCallsDescribed() || !SP.isDefinition()) 519 return; 520 521 // Use DW_AT_call_all_calls to express that call site entries are present 522 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls 523 // because one of its requirements is not met: call site entries for 524 // optimized-out calls are elided. 525 CU.addFlag(ScopeDIE, dwarf::DW_AT_call_all_calls); 526 527 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 528 assert(TII && "TargetInstrInfo not found: cannot label tail calls"); 529 530 // Emit call site entries for each call or tail call in the function. 531 for (const MachineBasicBlock &MBB : MF) { 532 for (const MachineInstr &MI : MBB.instrs()) { 533 // Skip instructions which aren't calls. Both calls and tail-calling jump 534 // instructions (e.g TAILJMPd64) are classified correctly here. 535 if (!MI.isCall()) 536 continue; 537 538 // TODO: Add support for targets with delay slots (see: beginInstruction). 539 if (MI.hasDelaySlot()) 540 return; 541 542 // If this is a direct call, find the callee's subprogram. 543 const MachineOperand &CalleeOp = MI.getOperand(0); 544 if (!CalleeOp.isGlobal()) 545 continue; 546 const Function *CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal()); 547 if (!CalleeDecl || !CalleeDecl->getSubprogram()) 548 continue; 549 550 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc). 551 // TODO: Add support for indirect calls. 552 553 bool IsTail = TII->isTailCall(MI); 554 555 // For tail calls, no return PC information is needed. For regular calls, 556 // the return PC is needed to disambiguate paths in the call graph which 557 // could lead to some target function. 558 const MCExpr *PCOffset = 559 IsTail ? nullptr : getFunctionLocalOffsetAfterInsn(&MI); 560 561 assert((IsTail || PCOffset) && "Call without return PC information"); 562 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> " 563 << CalleeDecl->getName() << (IsTail ? " [tail]" : "") 564 << "\n"); 565 CU.constructCallSiteEntryDIE(ScopeDIE, *CalleeDecl->getSubprogram(), 566 IsTail, PCOffset); 567 } 568 } 569 } 570 571 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const { 572 if (!U.hasDwarfPubSections()) 573 return; 574 575 U.addFlag(D, dwarf::DW_AT_GNU_pubnames); 576 } 577 578 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit, 579 DwarfCompileUnit &NewCU) { 580 DIE &Die = NewCU.getUnitDie(); 581 StringRef FN = DIUnit->getFilename(); 582 583 StringRef Producer = DIUnit->getProducer(); 584 StringRef Flags = DIUnit->getFlags(); 585 if (!Flags.empty() && !useAppleExtensionAttributes()) { 586 std::string ProducerWithFlags = Producer.str() + " " + Flags.str(); 587 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags); 588 } else 589 NewCU.addString(Die, dwarf::DW_AT_producer, Producer); 590 591 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 592 DIUnit->getSourceLanguage()); 593 NewCU.addString(Die, dwarf::DW_AT_name, FN); 594 595 // Add DW_str_offsets_base to the unit DIE, except for split units. 596 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 597 NewCU.addStringOffsetsStart(); 598 599 if (!useSplitDwarf()) { 600 NewCU.initStmtList(); 601 602 // If we're using split dwarf the compilation dir is going to be in the 603 // skeleton CU and so we don't need to duplicate it here. 604 if (!CompilationDir.empty()) 605 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 606 607 addGnuPubAttributes(NewCU, Die); 608 } 609 610 if (useAppleExtensionAttributes()) { 611 if (DIUnit->isOptimized()) 612 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized); 613 614 StringRef Flags = DIUnit->getFlags(); 615 if (!Flags.empty()) 616 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 617 618 if (unsigned RVer = DIUnit->getRuntimeVersion()) 619 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 620 dwarf::DW_FORM_data1, RVer); 621 } 622 623 if (DIUnit->getDWOId()) { 624 // This CU is either a clang module DWO or a skeleton CU. 625 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 626 DIUnit->getDWOId()); 627 if (!DIUnit->getSplitDebugFilename().empty()) 628 // This is a prefabricated skeleton CU. 629 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name, 630 DIUnit->getSplitDebugFilename()); 631 } 632 } 633 // Create new DwarfCompileUnit for the given metadata node with tag 634 // DW_TAG_compile_unit. 635 DwarfCompileUnit & 636 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) { 637 if (auto *CU = CUMap.lookup(DIUnit)) 638 return *CU; 639 640 CompilationDir = DIUnit->getDirectory(); 641 642 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 643 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder); 644 DwarfCompileUnit &NewCU = *OwnedUnit; 645 InfoHolder.addUnit(std::move(OwnedUnit)); 646 647 for (auto *IE : DIUnit->getImportedEntities()) 648 NewCU.addImportedEntity(IE); 649 650 // LTO with assembly output shares a single line table amongst multiple CUs. 651 // To avoid the compilation directory being ambiguous, let the line table 652 // explicitly describe the directory of all files, never relying on the 653 // compilation directory. 654 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU) 655 Asm->OutStreamer->emitDwarfFile0Directive( 656 CompilationDir, DIUnit->getFilename(), 657 NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(), 658 NewCU.getUniqueID()); 659 660 if (useSplitDwarf()) { 661 NewCU.setSkeleton(constructSkeletonCU(NewCU)); 662 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection()); 663 } else { 664 finishUnitAttributes(DIUnit, NewCU); 665 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 666 } 667 668 CUMap.insert({DIUnit, &NewCU}); 669 CUDieMap.insert({&NewCU.getUnitDie(), &NewCU}); 670 return NewCU; 671 } 672 673 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU, 674 const DIImportedEntity *N) { 675 if (isa<DILocalScope>(N->getScope())) 676 return; 677 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope())) 678 D->addChild(TheCU.constructImportedEntityDIE(N)); 679 } 680 681 /// Sort and unique GVEs by comparing their fragment offset. 682 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> & 683 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) { 684 llvm::sort( 685 GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) { 686 // Sort order: first null exprs, then exprs without fragment 687 // info, then sort by fragment offset in bits. 688 // FIXME: Come up with a more comprehensive comparator so 689 // the sorting isn't non-deterministic, and so the following 690 // std::unique call works correctly. 691 if (!A.Expr || !B.Expr) 692 return !!B.Expr; 693 auto FragmentA = A.Expr->getFragmentInfo(); 694 auto FragmentB = B.Expr->getFragmentInfo(); 695 if (!FragmentA || !FragmentB) 696 return !!FragmentB; 697 return FragmentA->OffsetInBits < FragmentB->OffsetInBits; 698 }); 699 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(), 700 [](DwarfCompileUnit::GlobalExpr A, 701 DwarfCompileUnit::GlobalExpr B) { 702 return A.Expr == B.Expr; 703 }), 704 GVEs.end()); 705 return GVEs; 706 } 707 708 // Emit all Dwarf sections that should come prior to the content. Create 709 // global DIEs and emit initial debug info sections. This is invoked by 710 // the target AsmPrinter. 711 void DwarfDebug::beginModule() { 712 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName, 713 DWARFGroupDescription, TimePassesIsEnabled); 714 if (DisableDebugInfoPrinting) { 715 MMI->setDebugInfoAvailability(false); 716 return; 717 } 718 719 const Module *M = MMI->getModule(); 720 721 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(), 722 M->debug_compile_units_end()); 723 // Tell MMI whether we have debug info. 724 assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) && 725 "DebugInfoAvailabilty initialized unexpectedly"); 726 SingleCU = NumDebugCUs == 1; 727 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>> 728 GVMap; 729 for (const GlobalVariable &Global : M->globals()) { 730 SmallVector<DIGlobalVariableExpression *, 1> GVs; 731 Global.getDebugInfo(GVs); 732 for (auto *GVE : GVs) 733 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()}); 734 } 735 736 // Create the symbol that designates the start of the unit's contribution 737 // to the string offsets table. In a split DWARF scenario, only the skeleton 738 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol). 739 if (useSegmentedStringOffsetsTable()) 740 (useSplitDwarf() ? SkeletonHolder : InfoHolder) 741 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base")); 742 743 744 // Create the symbols that designates the start of the DWARF v5 range list 745 // and locations list tables. They are located past the table headers. 746 if (getDwarfVersion() >= 5) { 747 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 748 Holder.setRnglistsTableBaseSym( 749 Asm->createTempSymbol("rnglists_table_base")); 750 Holder.setLoclistsTableBaseSym( 751 Asm->createTempSymbol("loclists_table_base")); 752 753 if (useSplitDwarf()) 754 InfoHolder.setRnglistsTableBaseSym( 755 Asm->createTempSymbol("rnglists_dwo_table_base")); 756 } 757 758 // Create the symbol that points to the first entry following the debug 759 // address table (.debug_addr) header. 760 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base")); 761 762 for (DICompileUnit *CUNode : M->debug_compile_units()) { 763 // FIXME: Move local imported entities into a list attached to the 764 // subprogram, then this search won't be needed and a 765 // getImportedEntities().empty() test should go below with the rest. 766 bool HasNonLocalImportedEntities = llvm::any_of( 767 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) { 768 return !isa<DILocalScope>(IE->getScope()); 769 }); 770 771 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() && 772 CUNode->getRetainedTypes().empty() && 773 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty()) 774 continue; 775 776 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode); 777 778 // Global Variables. 779 for (auto *GVE : CUNode->getGlobalVariables()) { 780 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we 781 // already know about the variable and it isn't adding a constant 782 // expression. 783 auto &GVMapEntry = GVMap[GVE->getVariable()]; 784 auto *Expr = GVE->getExpression(); 785 if (!GVMapEntry.size() || (Expr && Expr->isConstant())) 786 GVMapEntry.push_back({nullptr, Expr}); 787 } 788 DenseSet<DIGlobalVariable *> Processed; 789 for (auto *GVE : CUNode->getGlobalVariables()) { 790 DIGlobalVariable *GV = GVE->getVariable(); 791 if (Processed.insert(GV).second) 792 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV])); 793 } 794 795 for (auto *Ty : CUNode->getEnumTypes()) { 796 // The enum types array by design contains pointers to 797 // MDNodes rather than DIRefs. Unique them here. 798 CU.getOrCreateTypeDIE(cast<DIType>(Ty)); 799 } 800 for (auto *Ty : CUNode->getRetainedTypes()) { 801 // The retained types array by design contains pointers to 802 // MDNodes rather than DIRefs. Unique them here. 803 if (DIType *RT = dyn_cast<DIType>(Ty)) 804 // There is no point in force-emitting a forward declaration. 805 CU.getOrCreateTypeDIE(RT); 806 } 807 // Emit imported_modules last so that the relevant context is already 808 // available. 809 for (auto *IE : CUNode->getImportedEntities()) 810 constructAndAddImportedEntityDIE(CU, IE); 811 } 812 } 813 814 void DwarfDebug::finishEntityDefinitions() { 815 for (const auto &Entity : ConcreteEntities) { 816 DIE *Die = Entity->getDIE(); 817 assert(Die); 818 // FIXME: Consider the time-space tradeoff of just storing the unit pointer 819 // in the ConcreteEntities list, rather than looking it up again here. 820 // DIE::getUnit isn't simple - it walks parent pointers, etc. 821 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie()); 822 assert(Unit); 823 Unit->finishEntityDefinition(Entity.get()); 824 } 825 } 826 827 void DwarfDebug::finishSubprogramDefinitions() { 828 for (const DISubprogram *SP : ProcessedSPNodes) { 829 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug); 830 forBothCUs( 831 getOrCreateDwarfCompileUnit(SP->getUnit()), 832 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); }); 833 } 834 } 835 836 void DwarfDebug::finalizeModuleInfo() { 837 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 838 839 finishSubprogramDefinitions(); 840 841 finishEntityDefinitions(); 842 843 // Include the DWO file name in the hash if there's more than one CU. 844 // This handles ThinLTO's situation where imported CUs may very easily be 845 // duplicate with the same CU partially imported into another ThinLTO unit. 846 StringRef DWOName; 847 if (CUMap.size() > 1) 848 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile; 849 850 // Handle anything that needs to be done on a per-unit basis after 851 // all other generation. 852 for (const auto &P : CUMap) { 853 auto &TheCU = *P.second; 854 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 855 continue; 856 // Emit DW_AT_containing_type attribute to connect types with their 857 // vtable holding type. 858 TheCU.constructContainingTypeDIEs(); 859 860 // Add CU specific attributes if we need to add any. 861 // If we're splitting the dwarf out now that we've got the entire 862 // CU then add the dwo id to it. 863 auto *SkCU = TheCU.getSkeleton(); 864 if (useSplitDwarf() && !empty(TheCU.getUnitDie().children())) { 865 finishUnitAttributes(TheCU.getCUNode(), TheCU); 866 TheCU.addString(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_name, 867 Asm->TM.Options.MCOptions.SplitDwarfFile); 868 SkCU->addString(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_name, 869 Asm->TM.Options.MCOptions.SplitDwarfFile); 870 // Emit a unique identifier for this CU. 871 uint64_t ID = 872 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie()); 873 if (getDwarfVersion() >= 5) { 874 TheCU.setDWOId(ID); 875 SkCU->setDWOId(ID); 876 } else { 877 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 878 dwarf::DW_FORM_data8, ID); 879 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 880 dwarf::DW_FORM_data8, ID); 881 } 882 883 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) { 884 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol(); 885 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base, 886 Sym, Sym); 887 } 888 } else if (SkCU) { 889 finishUnitAttributes(SkCU->getCUNode(), *SkCU); 890 } 891 892 // If we have code split among multiple sections or non-contiguous 893 // ranges of code then emit a DW_AT_ranges attribute on the unit that will 894 // remain in the .o file, otherwise add a DW_AT_low_pc. 895 // FIXME: We should use ranges allow reordering of code ala 896 // .subsections_via_symbols in mach-o. This would mean turning on 897 // ranges for all subprogram DIEs for mach-o. 898 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 899 900 // We don't keep track of which addresses are used in which CU so this 901 // is a bit pessimistic under LTO. 902 if (!AddrPool.isEmpty() && 903 (getDwarfVersion() >= 5 || 904 (SkCU && !empty(TheCU.getUnitDie().children())))) 905 U.addAddrTableBase(); 906 907 if (unsigned NumRanges = TheCU.getRanges().size()) { 908 if (NumRanges > 1 && useRangesSection()) 909 // A DW_AT_low_pc attribute may also be specified in combination with 910 // DW_AT_ranges to specify the default base address for use in 911 // location lists (see Section 2.6.2) and range lists (see Section 912 // 2.17.3). 913 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0); 914 else 915 U.setBaseAddress(TheCU.getRanges().front().getStart()); 916 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges()); 917 } 918 919 if (getDwarfVersion() >= 5) { 920 if (U.hasRangeLists()) 921 U.addRnglistsBase(); 922 923 if (!DebugLocs.getLists().empty() && !useSplitDwarf()) 924 U.addLoclistsBase(); 925 } 926 927 auto *CUNode = cast<DICompileUnit>(P.first); 928 // If compile Unit has macros, emit "DW_AT_macro_info" attribute. 929 if (CUNode->getMacros()) 930 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info, 931 U.getMacroLabelBegin(), 932 TLOF.getDwarfMacinfoSection()->getBeginSymbol()); 933 } 934 935 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules. 936 for (auto *CUNode : MMI->getModule()->debug_compile_units()) 937 if (CUNode->getDWOId()) 938 getOrCreateDwarfCompileUnit(CUNode); 939 940 // Compute DIE offsets and sizes. 941 InfoHolder.computeSizeAndOffsets(); 942 if (useSplitDwarf()) 943 SkeletonHolder.computeSizeAndOffsets(); 944 } 945 946 // Emit all Dwarf sections that should come after the content. 947 void DwarfDebug::endModule() { 948 assert(CurFn == nullptr); 949 assert(CurMI == nullptr); 950 951 for (const auto &P : CUMap) { 952 auto &CU = *P.second; 953 CU.createBaseTypeDIEs(); 954 } 955 956 // If we aren't actually generating debug info (check beginModule - 957 // conditionalized on !DisableDebugInfoPrinting and the presence of the 958 // llvm.dbg.cu metadata node) 959 if (!MMI->hasDebugInfo()) 960 return; 961 962 // Finalize the debug info for the module. 963 finalizeModuleInfo(); 964 965 emitDebugStr(); 966 967 if (useSplitDwarf()) 968 emitDebugLocDWO(); 969 else 970 // Emit info into a debug loc section. 971 emitDebugLoc(); 972 973 // Corresponding abbreviations into a abbrev section. 974 emitAbbreviations(); 975 976 // Emit all the DIEs into a debug info section. 977 emitDebugInfo(); 978 979 // Emit info into a debug aranges section. 980 if (GenerateARangeSection) 981 emitDebugARanges(); 982 983 // Emit info into a debug ranges section. 984 emitDebugRanges(); 985 986 // Emit info into a debug macinfo section. 987 emitDebugMacinfo(); 988 989 if (useSplitDwarf()) { 990 emitDebugStrDWO(); 991 emitDebugInfoDWO(); 992 emitDebugAbbrevDWO(); 993 emitDebugLineDWO(); 994 emitDebugRangesDWO(); 995 } 996 997 emitDebugAddr(); 998 999 // Emit info into the dwarf accelerator table sections. 1000 switch (getAccelTableKind()) { 1001 case AccelTableKind::Apple: 1002 emitAccelNames(); 1003 emitAccelObjC(); 1004 emitAccelNamespaces(); 1005 emitAccelTypes(); 1006 break; 1007 case AccelTableKind::Dwarf: 1008 emitAccelDebugNames(); 1009 break; 1010 case AccelTableKind::None: 1011 break; 1012 case AccelTableKind::Default: 1013 llvm_unreachable("Default should have already been resolved."); 1014 } 1015 1016 // Emit the pubnames and pubtypes sections if requested. 1017 emitDebugPubSections(); 1018 1019 // clean up. 1020 // FIXME: AbstractVariables.clear(); 1021 } 1022 1023 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU, 1024 const DINode *Node, 1025 const MDNode *ScopeNode) { 1026 if (CU.getExistingAbstractEntity(Node)) 1027 return; 1028 1029 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope( 1030 cast<DILocalScope>(ScopeNode))); 1031 } 1032 1033 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU, 1034 const DINode *Node, const MDNode *ScopeNode) { 1035 if (CU.getExistingAbstractEntity(Node)) 1036 return; 1037 1038 if (LexicalScope *Scope = 1039 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode))) 1040 CU.createAbstractEntity(Node, Scope); 1041 } 1042 1043 // Collect variable information from side table maintained by MF. 1044 void DwarfDebug::collectVariableInfoFromMFTable( 1045 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) { 1046 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars; 1047 for (const auto &VI : Asm->MF->getVariableDbgInfo()) { 1048 if (!VI.Var) 1049 continue; 1050 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 1051 "Expected inlined-at fields to agree"); 1052 1053 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt()); 1054 Processed.insert(Var); 1055 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 1056 1057 // If variable scope is not found then skip this variable. 1058 if (!Scope) 1059 continue; 1060 1061 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode()); 1062 auto RegVar = llvm::make_unique<DbgVariable>( 1063 cast<DILocalVariable>(Var.first), Var.second); 1064 RegVar->initializeMMI(VI.Expr, VI.Slot); 1065 if (DbgVariable *DbgVar = MFVars.lookup(Var)) 1066 DbgVar->addMMIEntry(*RegVar); 1067 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) { 1068 MFVars.insert({Var, RegVar.get()}); 1069 ConcreteEntities.push_back(std::move(RegVar)); 1070 } 1071 } 1072 } 1073 1074 // Get .debug_loc entry for the instruction range starting at MI. 1075 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) { 1076 const DIExpression *Expr = MI->getDebugExpression(); 1077 assert(MI->getNumOperands() == 4); 1078 if (MI->getOperand(0).isReg()) { 1079 auto RegOp = MI->getOperand(0); 1080 auto Op1 = MI->getOperand(1); 1081 // If the second operand is an immediate, this is a 1082 // register-indirect address. 1083 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"); 1084 MachineLocation MLoc(RegOp.getReg(), Op1.isImm()); 1085 return DebugLocEntry::Value(Expr, MLoc); 1086 } 1087 if (MI->getOperand(0).isImm()) 1088 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm()); 1089 if (MI->getOperand(0).isFPImm()) 1090 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm()); 1091 if (MI->getOperand(0).isCImm()) 1092 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm()); 1093 1094 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!"); 1095 } 1096 1097 /// If this and Next are describing different fragments of the same 1098 /// variable, merge them by appending Next's values to the current 1099 /// list of values. 1100 /// Return true if the merge was successful. 1101 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) { 1102 if (Begin == Next.Begin) { 1103 auto *FirstExpr = cast<DIExpression>(Values[0].Expression); 1104 auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression); 1105 if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment()) 1106 return false; 1107 1108 // We can only merge entries if none of the fragments overlap any others. 1109 // In doing so, we can take advantage of the fact that both lists are 1110 // sorted. 1111 for (unsigned i = 0, j = 0; i < Values.size(); ++i) { 1112 for (; j < Next.Values.size(); ++j) { 1113 int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp( 1114 cast<DIExpression>(Next.Values[j].Expression)); 1115 if (res == 0) // The two expressions overlap, we can't merge. 1116 return false; 1117 // Values[i] is entirely before Next.Values[j], 1118 // so go back to the next entry of Values. 1119 else if (res == -1) 1120 break; 1121 // Next.Values[j] is entirely before Values[i], so go on to the 1122 // next entry of Next.Values. 1123 } 1124 } 1125 1126 addValues(Next.Values); 1127 End = Next.End; 1128 return true; 1129 } 1130 return false; 1131 } 1132 1133 /// Build the location list for all DBG_VALUEs in the function that 1134 /// describe the same variable. If the ranges of several independent 1135 /// fragments of the same variable overlap partially, split them up and 1136 /// combine the ranges. The resulting DebugLocEntries are will have 1137 /// strict monotonically increasing begin addresses and will never 1138 /// overlap. 1139 // 1140 // Input: 1141 // 1142 // Ranges History [var, loc, fragment ofs size] 1143 // 0 | [x, (reg0, fragment 0, 32)] 1144 // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry 1145 // 2 | | ... 1146 // 3 | [clobber reg0] 1147 // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of 1148 // x. 1149 // 1150 // Output: 1151 // 1152 // [0-1] [x, (reg0, fragment 0, 32)] 1153 // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)] 1154 // [3-4] [x, (reg1, fragment 32, 32)] 1155 // [4- ] [x, (mem, fragment 0, 64)] 1156 void 1157 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 1158 const DbgValueHistoryMap::InstrRanges &Ranges) { 1159 SmallVector<DebugLocEntry::Value, 4> OpenRanges; 1160 1161 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 1162 const MachineInstr *Begin = I->first; 1163 const MachineInstr *End = I->second; 1164 assert(Begin->isDebugValue() && "Invalid History entry"); 1165 1166 // Check if a variable is inaccessible in this range. 1167 if (Begin->getNumOperands() > 1 && 1168 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) { 1169 OpenRanges.clear(); 1170 continue; 1171 } 1172 1173 // If this fragment overlaps with any open ranges, truncate them. 1174 const DIExpression *DIExpr = Begin->getDebugExpression(); 1175 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) { 1176 return DIExpr->fragmentsOverlap(R.getExpression()); 1177 }); 1178 OpenRanges.erase(Last, OpenRanges.end()); 1179 1180 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin); 1181 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!"); 1182 1183 const MCSymbol *EndLabel; 1184 if (End != nullptr) 1185 EndLabel = getLabelAfterInsn(End); 1186 else if (std::next(I) == Ranges.end()) 1187 EndLabel = Asm->getFunctionEnd(); 1188 else 1189 EndLabel = getLabelBeforeInsn(std::next(I)->first); 1190 assert(EndLabel && "Forgot label after instruction ending a range!"); 1191 1192 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n"); 1193 1194 auto Value = getDebugLocValue(Begin); 1195 1196 // Omit entries with empty ranges as they do not have any effect in DWARF. 1197 if (StartLabel == EndLabel) { 1198 // If this is a fragment, we must still add the value to the list of 1199 // open ranges, since it may describe non-overlapping parts of the 1200 // variable. 1201 if (DIExpr->isFragment()) 1202 OpenRanges.push_back(Value); 1203 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n"); 1204 continue; 1205 } 1206 1207 DebugLocEntry Loc(StartLabel, EndLabel, Value); 1208 bool couldMerge = false; 1209 1210 // If this is a fragment, it may belong to the current DebugLocEntry. 1211 if (DIExpr->isFragment()) { 1212 // Add this value to the list of open ranges. 1213 OpenRanges.push_back(Value); 1214 1215 // Attempt to add the fragment to the last entry. 1216 if (!DebugLoc.empty()) 1217 if (DebugLoc.back().MergeValues(Loc)) 1218 couldMerge = true; 1219 } 1220 1221 if (!couldMerge) { 1222 // Need to add a new DebugLocEntry. Add all values from still 1223 // valid non-overlapping fragments. 1224 if (OpenRanges.size()) 1225 Loc.addValues(OpenRanges); 1226 1227 DebugLoc.push_back(std::move(Loc)); 1228 } 1229 1230 // Attempt to coalesce the ranges of two otherwise identical 1231 // DebugLocEntries. 1232 auto CurEntry = DebugLoc.rbegin(); 1233 LLVM_DEBUG({ 1234 dbgs() << CurEntry->getValues().size() << " Values:\n"; 1235 for (auto &Value : CurEntry->getValues()) 1236 Value.dump(); 1237 dbgs() << "-----\n"; 1238 }); 1239 1240 auto PrevEntry = std::next(CurEntry); 1241 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 1242 DebugLoc.pop_back(); 1243 } 1244 } 1245 1246 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU, 1247 LexicalScope &Scope, 1248 const DINode *Node, 1249 const DILocation *Location, 1250 const MCSymbol *Sym) { 1251 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode()); 1252 if (isa<const DILocalVariable>(Node)) { 1253 ConcreteEntities.push_back( 1254 llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node), 1255 Location)); 1256 InfoHolder.addScopeVariable(&Scope, 1257 cast<DbgVariable>(ConcreteEntities.back().get())); 1258 } else if (isa<const DILabel>(Node)) { 1259 ConcreteEntities.push_back( 1260 llvm::make_unique<DbgLabel>(cast<const DILabel>(Node), 1261 Location, Sym)); 1262 InfoHolder.addScopeLabel(&Scope, 1263 cast<DbgLabel>(ConcreteEntities.back().get())); 1264 } 1265 return ConcreteEntities.back().get(); 1266 } 1267 1268 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its 1269 /// enclosing lexical scope. The check ensures there are no other instructions 1270 /// in the same lexical scope preceding the DBG_VALUE and that its range is 1271 /// either open or otherwise rolls off the end of the scope. 1272 static bool validThroughout(LexicalScopes &LScopes, 1273 const MachineInstr *DbgValue, 1274 const MachineInstr *RangeEnd) { 1275 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location"); 1276 auto MBB = DbgValue->getParent(); 1277 auto DL = DbgValue->getDebugLoc(); 1278 auto *LScope = LScopes.findLexicalScope(DL); 1279 // Scope doesn't exist; this is a dead DBG_VALUE. 1280 if (!LScope) 1281 return false; 1282 auto &LSRange = LScope->getRanges(); 1283 if (LSRange.size() == 0) 1284 return false; 1285 1286 // Determine if the DBG_VALUE is valid at the beginning of its lexical block. 1287 const MachineInstr *LScopeBegin = LSRange.front().first; 1288 // Early exit if the lexical scope begins outside of the current block. 1289 if (LScopeBegin->getParent() != MBB) 1290 return false; 1291 MachineBasicBlock::const_reverse_iterator Pred(DbgValue); 1292 for (++Pred; Pred != MBB->rend(); ++Pred) { 1293 if (Pred->getFlag(MachineInstr::FrameSetup)) 1294 break; 1295 auto PredDL = Pred->getDebugLoc(); 1296 if (!PredDL || Pred->isMetaInstruction()) 1297 continue; 1298 // Check whether the instruction preceding the DBG_VALUE is in the same 1299 // (sub)scope as the DBG_VALUE. 1300 if (DL->getScope() == PredDL->getScope()) 1301 return false; 1302 auto *PredScope = LScopes.findLexicalScope(PredDL); 1303 if (!PredScope || LScope->dominates(PredScope)) 1304 return false; 1305 } 1306 1307 // If the range of the DBG_VALUE is open-ended, report success. 1308 if (!RangeEnd) 1309 return true; 1310 1311 // Fail if there are instructions belonging to our scope in another block. 1312 const MachineInstr *LScopeEnd = LSRange.back().second; 1313 if (LScopeEnd->getParent() != MBB) 1314 return false; 1315 1316 // Single, constant DBG_VALUEs in the prologue are promoted to be live 1317 // throughout the function. This is a hack, presumably for DWARF v2 and not 1318 // necessarily correct. It would be much better to use a dbg.declare instead 1319 // if we know the constant is live throughout the scope. 1320 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty()) 1321 return true; 1322 1323 return false; 1324 } 1325 1326 // Find variables for each lexical scope. 1327 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU, 1328 const DISubprogram *SP, 1329 DenseSet<InlinedEntity> &Processed) { 1330 // Grab the variable info that was squirreled away in the MMI side-table. 1331 collectVariableInfoFromMFTable(TheCU, Processed); 1332 1333 for (const auto &I : DbgValues) { 1334 InlinedEntity IV = I.first; 1335 if (Processed.count(IV)) 1336 continue; 1337 1338 // Instruction ranges, specifying where IV is accessible. 1339 const auto &Ranges = I.second; 1340 if (Ranges.empty()) 1341 continue; 1342 1343 LexicalScope *Scope = nullptr; 1344 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first); 1345 if (const DILocation *IA = IV.second) 1346 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA); 1347 else 1348 Scope = LScopes.findLexicalScope(LocalVar->getScope()); 1349 // If variable scope is not found then skip this variable. 1350 if (!Scope) 1351 continue; 1352 1353 Processed.insert(IV); 1354 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU, 1355 *Scope, LocalVar, IV.second)); 1356 1357 const MachineInstr *MInsn = Ranges.front().first; 1358 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1359 1360 // Check if there is a single DBG_VALUE, valid throughout the var's scope. 1361 if (Ranges.size() == 1 && 1362 validThroughout(LScopes, MInsn, Ranges.front().second)) { 1363 RegVar->initializeDbgValue(MInsn); 1364 continue; 1365 } 1366 // Do not emit location lists if .debug_loc secton is disabled. 1367 if (!useLocSection()) 1368 continue; 1369 1370 // Handle multiple DBG_VALUE instructions describing one variable. 1371 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 1372 1373 // Build the location list for this variable. 1374 SmallVector<DebugLocEntry, 8> Entries; 1375 buildLocationList(Entries, Ranges); 1376 1377 // If the variable has a DIBasicType, extract it. Basic types cannot have 1378 // unique identifiers, so don't bother resolving the type with the 1379 // identifier map. 1380 const DIBasicType *BT = dyn_cast<DIBasicType>( 1381 static_cast<const Metadata *>(LocalVar->getType())); 1382 1383 // Finalize the entry by lowering it into a DWARF bytestream. 1384 for (auto &Entry : Entries) 1385 Entry.finalize(*Asm, List, BT, TheCU); 1386 } 1387 1388 // For each InlinedEntity collected from DBG_LABEL instructions, convert to 1389 // DWARF-related DbgLabel. 1390 for (const auto &I : DbgLabels) { 1391 InlinedEntity IL = I.first; 1392 const MachineInstr *MI = I.second; 1393 if (MI == nullptr) 1394 continue; 1395 1396 LexicalScope *Scope = nullptr; 1397 const DILabel *Label = cast<DILabel>(IL.first); 1398 // Get inlined DILocation if it is inlined label. 1399 if (const DILocation *IA = IL.second) 1400 Scope = LScopes.findInlinedScope(Label->getScope(), IA); 1401 else 1402 Scope = LScopes.findLexicalScope(Label->getScope()); 1403 // If label scope is not found then skip this label. 1404 if (!Scope) 1405 continue; 1406 1407 Processed.insert(IL); 1408 /// At this point, the temporary label is created. 1409 /// Save the temporary label to DbgLabel entity to get the 1410 /// actually address when generating Dwarf DIE. 1411 MCSymbol *Sym = getLabelBeforeInsn(MI); 1412 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym); 1413 } 1414 1415 // Collect info for variables/labels that were optimized out. 1416 for (const DINode *DN : SP->getRetainedNodes()) { 1417 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1418 continue; 1419 LexicalScope *Scope = nullptr; 1420 if (auto *DV = dyn_cast<DILocalVariable>(DN)) { 1421 Scope = LScopes.findLexicalScope(DV->getScope()); 1422 } else if (auto *DL = dyn_cast<DILabel>(DN)) { 1423 Scope = LScopes.findLexicalScope(DL->getScope()); 1424 } 1425 1426 if (Scope) 1427 createConcreteEntity(TheCU, *Scope, DN, nullptr); 1428 } 1429 } 1430 1431 // Process beginning of an instruction. 1432 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1433 DebugHandlerBase::beginInstruction(MI); 1434 assert(CurMI); 1435 1436 const auto *SP = MI->getMF()->getFunction().getSubprogram(); 1437 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1438 return; 1439 1440 // Check if source location changes, but ignore DBG_VALUE and CFI locations. 1441 // If the instruction is part of the function frame setup code, do not emit 1442 // any line record, as there is no correspondence with any user code. 1443 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup)) 1444 return; 1445 const DebugLoc &DL = MI->getDebugLoc(); 1446 // When we emit a line-0 record, we don't update PrevInstLoc; so look at 1447 // the last line number actually emitted, to see if it was line 0. 1448 unsigned LastAsmLine = 1449 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine(); 1450 1451 // Request a label after the call in order to emit AT_return_pc information 1452 // in call site entries. TODO: Add support for targets with delay slots. 1453 if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot()) 1454 requestLabelAfterInsn(MI); 1455 1456 if (DL == PrevInstLoc) { 1457 // If we have an ongoing unspecified location, nothing to do here. 1458 if (!DL) 1459 return; 1460 // We have an explicit location, same as the previous location. 1461 // But we might be coming back to it after a line 0 record. 1462 if (LastAsmLine == 0 && DL.getLine() != 0) { 1463 // Reinstate the source location but not marked as a statement. 1464 const MDNode *Scope = DL.getScope(); 1465 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0); 1466 } 1467 return; 1468 } 1469 1470 if (!DL) { 1471 // We have an unspecified location, which might want to be line 0. 1472 // If we have already emitted a line-0 record, don't repeat it. 1473 if (LastAsmLine == 0) 1474 return; 1475 // If user said Don't Do That, don't do that. 1476 if (UnknownLocations == Disable) 1477 return; 1478 // See if we have a reason to emit a line-0 record now. 1479 // Reasons to emit a line-0 record include: 1480 // - User asked for it (UnknownLocations). 1481 // - Instruction has a label, so it's referenced from somewhere else, 1482 // possibly debug information; we want it to have a source location. 1483 // - Instruction is at the top of a block; we don't want to inherit the 1484 // location from the physically previous (maybe unrelated) block. 1485 if (UnknownLocations == Enable || PrevLabel || 1486 (PrevInstBB && PrevInstBB != MI->getParent())) { 1487 // Preserve the file and column numbers, if we can, to save space in 1488 // the encoded line table. 1489 // Do not update PrevInstLoc, it remembers the last non-0 line. 1490 const MDNode *Scope = nullptr; 1491 unsigned Column = 0; 1492 if (PrevInstLoc) { 1493 Scope = PrevInstLoc.getScope(); 1494 Column = PrevInstLoc.getCol(); 1495 } 1496 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0); 1497 } 1498 return; 1499 } 1500 1501 // We have an explicit location, different from the previous location. 1502 // Don't repeat a line-0 record, but otherwise emit the new location. 1503 // (The new location might be an explicit line 0, which we do emit.) 1504 if (DL.getLine() == 0 && LastAsmLine == 0) 1505 return; 1506 unsigned Flags = 0; 1507 if (DL == PrologEndLoc) { 1508 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT; 1509 PrologEndLoc = DebugLoc(); 1510 } 1511 // If the line changed, we call that a new statement; unless we went to 1512 // line 0 and came back, in which case it is not a new statement. 1513 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine; 1514 if (DL.getLine() && DL.getLine() != OldLine) 1515 Flags |= DWARF2_FLAG_IS_STMT; 1516 1517 const MDNode *Scope = DL.getScope(); 1518 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1519 1520 // If we're not at line 0, remember this location. 1521 if (DL.getLine()) 1522 PrevInstLoc = DL; 1523 } 1524 1525 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1526 // First known non-DBG_VALUE and non-frame setup location marks 1527 // the beginning of the function body. 1528 for (const auto &MBB : *MF) 1529 for (const auto &MI : MBB) 1530 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1531 MI.getDebugLoc()) 1532 return MI.getDebugLoc(); 1533 return DebugLoc(); 1534 } 1535 1536 /// Register a source line with debug info. Returns the unique label that was 1537 /// emitted and which provides correspondence to the source line list. 1538 static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col, 1539 const MDNode *S, unsigned Flags, unsigned CUID, 1540 uint16_t DwarfVersion, 1541 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) { 1542 StringRef Fn; 1543 unsigned FileNo = 1; 1544 unsigned Discriminator = 0; 1545 if (auto *Scope = cast_or_null<DIScope>(S)) { 1546 Fn = Scope->getFilename(); 1547 if (Line != 0 && DwarfVersion >= 4) 1548 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 1549 Discriminator = LBF->getDiscriminator(); 1550 1551 FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID]) 1552 .getOrCreateSourceID(Scope->getFile()); 1553 } 1554 Asm.OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0, 1555 Discriminator, Fn); 1556 } 1557 1558 DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF, 1559 unsigned CUID) { 1560 // Get beginning of function. 1561 if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) { 1562 // Ensure the compile unit is created if the function is called before 1563 // beginFunction(). 1564 (void)getOrCreateDwarfCompileUnit( 1565 MF.getFunction().getSubprogram()->getUnit()); 1566 // We'd like to list the prologue as "not statements" but GDB behaves 1567 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1568 const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram(); 1569 ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT, 1570 CUID, getDwarfVersion(), getUnits()); 1571 return PrologEndLoc; 1572 } 1573 return DebugLoc(); 1574 } 1575 1576 // Gather pre-function debug information. Assumes being called immediately 1577 // after the function entry point has been emitted. 1578 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) { 1579 CurFn = MF; 1580 1581 auto *SP = MF->getFunction().getSubprogram(); 1582 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode()); 1583 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1584 return; 1585 1586 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 1587 1588 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1589 // belongs to so that we add to the correct per-cu line table in the 1590 // non-asm case. 1591 if (Asm->OutStreamer->hasRawTextSupport()) 1592 // Use a single line table if we are generating assembly. 1593 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1594 else 1595 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID()); 1596 1597 // Record beginning of function. 1598 PrologEndLoc = emitInitialLocDirective( 1599 *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID()); 1600 } 1601 1602 void DwarfDebug::skippedNonDebugFunction() { 1603 // If we don't have a subprogram for this function then there will be a hole 1604 // in the range information. Keep note of this by setting the previously used 1605 // section to nullptr. 1606 PrevCU = nullptr; 1607 CurFn = nullptr; 1608 } 1609 1610 // Gather and emit post-function debug information. 1611 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) { 1612 const DISubprogram *SP = MF->getFunction().getSubprogram(); 1613 1614 assert(CurFn == MF && 1615 "endFunction should be called with the same function as beginFunction"); 1616 1617 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1618 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1619 1620 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1621 assert(!FnScope || SP == FnScope->getScopeNode()); 1622 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit()); 1623 if (TheCU.getCUNode()->isDebugDirectivesOnly()) { 1624 PrevLabel = nullptr; 1625 CurFn = nullptr; 1626 return; 1627 } 1628 1629 DenseSet<InlinedEntity> Processed; 1630 collectEntityInfo(TheCU, SP, Processed); 1631 1632 // Add the range of this function to the list of ranges for the CU. 1633 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd())); 1634 1635 // Under -gmlt, skip building the subprogram if there are no inlined 1636 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram 1637 // is still needed as we need its source location. 1638 if (!TheCU.getCUNode()->getDebugInfoForProfiling() && 1639 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly && 1640 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1641 assert(InfoHolder.getScopeVariables().empty()); 1642 PrevLabel = nullptr; 1643 CurFn = nullptr; 1644 return; 1645 } 1646 1647 #ifndef NDEBUG 1648 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1649 #endif 1650 // Construct abstract scopes. 1651 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1652 auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 1653 for (const DINode *DN : SP->getRetainedNodes()) { 1654 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1655 continue; 1656 1657 const MDNode *Scope = nullptr; 1658 if (auto *DV = dyn_cast<DILocalVariable>(DN)) 1659 Scope = DV->getScope(); 1660 else if (auto *DL = dyn_cast<DILabel>(DN)) 1661 Scope = DL->getScope(); 1662 else 1663 llvm_unreachable("Unexpected DI type!"); 1664 1665 // Collect info for variables/labels that were optimized out. 1666 ensureAbstractEntityIsCreated(TheCU, DN, Scope); 1667 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1668 && "ensureAbstractEntityIsCreated inserted abstract scopes"); 1669 } 1670 constructAbstractSubprogramScopeDIE(TheCU, AScope); 1671 } 1672 1673 ProcessedSPNodes.insert(SP); 1674 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope); 1675 if (auto *SkelCU = TheCU.getSkeleton()) 1676 if (!LScopes.getAbstractScopesList().empty() && 1677 TheCU.getCUNode()->getSplitDebugInlining()) 1678 SkelCU->constructSubprogramScopeDIE(SP, FnScope); 1679 1680 // Construct call site entries. 1681 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF); 1682 1683 // Clear debug info 1684 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1685 // DbgVariables except those that are also in AbstractVariables (since they 1686 // can be used cross-function) 1687 InfoHolder.getScopeVariables().clear(); 1688 InfoHolder.getScopeLabels().clear(); 1689 PrevLabel = nullptr; 1690 CurFn = nullptr; 1691 } 1692 1693 // Register a source line with debug info. Returns the unique label that was 1694 // emitted and which provides correspondence to the source line list. 1695 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1696 unsigned Flags) { 1697 ::recordSourceLine(*Asm, Line, Col, S, Flags, 1698 Asm->OutStreamer->getContext().getDwarfCompileUnitID(), 1699 getDwarfVersion(), getUnits()); 1700 } 1701 1702 //===----------------------------------------------------------------------===// 1703 // Emit Methods 1704 //===----------------------------------------------------------------------===// 1705 1706 // Emit the debug info section. 1707 void DwarfDebug::emitDebugInfo() { 1708 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1709 Holder.emitUnits(/* UseOffsets */ false); 1710 } 1711 1712 // Emit the abbreviation section. 1713 void DwarfDebug::emitAbbreviations() { 1714 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1715 1716 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1717 } 1718 1719 void DwarfDebug::emitStringOffsetsTableHeader() { 1720 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1721 Holder.getStringPool().emitStringOffsetsTableHeader( 1722 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(), 1723 Holder.getStringOffsetsStartSym()); 1724 } 1725 1726 template <typename AccelTableT> 1727 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section, 1728 StringRef TableName) { 1729 Asm->OutStreamer->SwitchSection(Section); 1730 1731 // Emit the full data. 1732 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol()); 1733 } 1734 1735 void DwarfDebug::emitAccelDebugNames() { 1736 // Don't emit anything if we have no compilation units to index. 1737 if (getUnits().empty()) 1738 return; 1739 1740 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits()); 1741 } 1742 1743 // Emit visible names into a hashed accelerator table section. 1744 void DwarfDebug::emitAccelNames() { 1745 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1746 "Names"); 1747 } 1748 1749 // Emit objective C classes and categories into a hashed accelerator table 1750 // section. 1751 void DwarfDebug::emitAccelObjC() { 1752 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1753 "ObjC"); 1754 } 1755 1756 // Emit namespace dies into a hashed accelerator table. 1757 void DwarfDebug::emitAccelNamespaces() { 1758 emitAccel(AccelNamespace, 1759 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1760 "namespac"); 1761 } 1762 1763 // Emit type dies into a hashed accelerator table. 1764 void DwarfDebug::emitAccelTypes() { 1765 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1766 "types"); 1767 } 1768 1769 // Public name handling. 1770 // The format for the various pubnames: 1771 // 1772 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1773 // for the DIE that is named. 1774 // 1775 // gnu pubnames - offset/index value/name tuples where the offset is the offset 1776 // into the CU and the index value is computed according to the type of value 1777 // for the DIE that is named. 1778 // 1779 // For type units the offset is the offset of the skeleton DIE. For split dwarf 1780 // it's the offset within the debug_info/debug_types dwo section, however, the 1781 // reference in the pubname header doesn't change. 1782 1783 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 1784 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1785 const DIE *Die) { 1786 // Entities that ended up only in a Type Unit reference the CU instead (since 1787 // the pub entry has offsets within the CU there's no real offset that can be 1788 // provided anyway). As it happens all such entities (namespaces and types, 1789 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out 1790 // not to be true it would be necessary to persist this information from the 1791 // point at which the entry is added to the index data structure - since by 1792 // the time the index is built from that, the original type/namespace DIE in a 1793 // type unit has already been destroyed so it can't be queried for properties 1794 // like tag, etc. 1795 if (Die->getTag() == dwarf::DW_TAG_compile_unit) 1796 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, 1797 dwarf::GIEL_EXTERNAL); 1798 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1799 1800 // We could have a specification DIE that has our most of our knowledge, 1801 // look for that now. 1802 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 1803 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 1804 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1805 Linkage = dwarf::GIEL_EXTERNAL; 1806 } else if (Die->findAttribute(dwarf::DW_AT_external)) 1807 Linkage = dwarf::GIEL_EXTERNAL; 1808 1809 switch (Die->getTag()) { 1810 case dwarf::DW_TAG_class_type: 1811 case dwarf::DW_TAG_structure_type: 1812 case dwarf::DW_TAG_union_type: 1813 case dwarf::DW_TAG_enumeration_type: 1814 return dwarf::PubIndexEntryDescriptor( 1815 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1816 ? dwarf::GIEL_STATIC 1817 : dwarf::GIEL_EXTERNAL); 1818 case dwarf::DW_TAG_typedef: 1819 case dwarf::DW_TAG_base_type: 1820 case dwarf::DW_TAG_subrange_type: 1821 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1822 case dwarf::DW_TAG_namespace: 1823 return dwarf::GIEK_TYPE; 1824 case dwarf::DW_TAG_subprogram: 1825 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1826 case dwarf::DW_TAG_variable: 1827 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1828 case dwarf::DW_TAG_enumerator: 1829 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1830 dwarf::GIEL_STATIC); 1831 default: 1832 return dwarf::GIEK_NONE; 1833 } 1834 } 1835 1836 /// emitDebugPubSections - Emit visible names and types into debug pubnames and 1837 /// pubtypes sections. 1838 void DwarfDebug::emitDebugPubSections() { 1839 for (const auto &NU : CUMap) { 1840 DwarfCompileUnit *TheU = NU.second; 1841 if (!TheU->hasDwarfPubSections()) 1842 continue; 1843 1844 bool GnuStyle = TheU->getCUNode()->getNameTableKind() == 1845 DICompileUnit::DebugNameTableKind::GNU; 1846 1847 Asm->OutStreamer->SwitchSection( 1848 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1849 : Asm->getObjFileLowering().getDwarfPubNamesSection()); 1850 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames()); 1851 1852 Asm->OutStreamer->SwitchSection( 1853 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1854 : Asm->getObjFileLowering().getDwarfPubTypesSection()); 1855 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes()); 1856 } 1857 } 1858 1859 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) { 1860 if (useSectionsAsReferences()) 1861 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(), 1862 CU.getDebugSectionOffset()); 1863 else 1864 Asm->emitDwarfSymbolReference(CU.getLabelBegin()); 1865 } 1866 1867 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name, 1868 DwarfCompileUnit *TheU, 1869 const StringMap<const DIE *> &Globals) { 1870 if (auto *Skeleton = TheU->getSkeleton()) 1871 TheU = Skeleton; 1872 1873 // Emit the header. 1874 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info"); 1875 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 1876 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 1877 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1878 1879 Asm->OutStreamer->EmitLabel(BeginLabel); 1880 1881 Asm->OutStreamer->AddComment("DWARF Version"); 1882 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); 1883 1884 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 1885 emitSectionReference(*TheU); 1886 1887 Asm->OutStreamer->AddComment("Compilation Unit Length"); 1888 Asm->emitInt32(TheU->getLength()); 1889 1890 // Emit the pubnames for this compilation unit. 1891 for (const auto &GI : Globals) { 1892 const char *Name = GI.getKeyData(); 1893 const DIE *Entity = GI.second; 1894 1895 Asm->OutStreamer->AddComment("DIE offset"); 1896 Asm->emitInt32(Entity->getOffset()); 1897 1898 if (GnuStyle) { 1899 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1900 Asm->OutStreamer->AddComment( 1901 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + 1902 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1903 Asm->emitInt8(Desc.toBits()); 1904 } 1905 1906 Asm->OutStreamer->AddComment("External Name"); 1907 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1908 } 1909 1910 Asm->OutStreamer->AddComment("End Mark"); 1911 Asm->emitInt32(0); 1912 Asm->OutStreamer->EmitLabel(EndLabel); 1913 } 1914 1915 /// Emit null-terminated strings into a debug str section. 1916 void DwarfDebug::emitDebugStr() { 1917 MCSection *StringOffsetsSection = nullptr; 1918 if (useSegmentedStringOffsetsTable()) { 1919 emitStringOffsetsTableHeader(); 1920 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection(); 1921 } 1922 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1923 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(), 1924 StringOffsetsSection, /* UseRelativeOffsets = */ true); 1925 } 1926 1927 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, const 1928 DebugLocStream::Entry &Entry, 1929 const DwarfCompileUnit *CU) { 1930 auto &&Comments = DebugLocs.getComments(Entry); 1931 auto Comment = Comments.begin(); 1932 auto End = Comments.end(); 1933 1934 // The expressions are inserted into a byte stream rather early (see 1935 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that 1936 // need to reference a base_type DIE the offset of that DIE is not yet known. 1937 // To deal with this we instead insert a placeholder early and then extract 1938 // it here and replace it with the real reference. 1939 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 1940 DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(), 1941 DebugLocs.getBytes(Entry).size()), 1942 Asm->getDataLayout().isLittleEndian(), PtrSize); 1943 DWARFExpression Expr(Data, getDwarfVersion(), PtrSize); 1944 1945 using Encoding = DWARFExpression::Operation::Encoding; 1946 uint32_t Offset = 0; 1947 for (auto &Op : Expr) { 1948 assert(Op.getCode() != dwarf::DW_OP_const_type && 1949 "3 operand ops not yet supported"); 1950 Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : ""); 1951 Offset++; 1952 for (unsigned I = 0; I < 2; ++I) { 1953 if (Op.getDescription().Op[I] == Encoding::SizeNA) 1954 continue; 1955 if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) { 1956 if (CU) { 1957 uint64_t Offset = CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset(); 1958 assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit"); 1959 Asm->EmitULEB128(Offset, nullptr, ULEB128PadSize); 1960 } else { 1961 // Emit a reference to the 'generic type'. 1962 Asm->EmitULEB128(0, nullptr, ULEB128PadSize); 1963 } 1964 // Make sure comments stay aligned. 1965 for (unsigned J = 0; J < ULEB128PadSize; ++J) 1966 if (Comment != End) 1967 Comment++; 1968 } else { 1969 for (uint32_t J = Offset; J < Op.getOperandEndOffset(I); ++J) 1970 Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : ""); 1971 } 1972 Offset = Op.getOperandEndOffset(I); 1973 } 1974 assert(Offset == Op.getEndOffset()); 1975 } 1976 } 1977 1978 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 1979 const DebugLocEntry::Value &Value, 1980 DwarfExpression &DwarfExpr) { 1981 auto *DIExpr = Value.getExpression(); 1982 DIExpressionCursor ExprCursor(DIExpr); 1983 DwarfExpr.addFragmentOffset(DIExpr); 1984 // Regular entry. 1985 if (Value.isInt()) { 1986 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 1987 BT->getEncoding() == dwarf::DW_ATE_signed_char)) 1988 DwarfExpr.addSignedConstant(Value.getInt()); 1989 else 1990 DwarfExpr.addUnsignedConstant(Value.getInt()); 1991 } else if (Value.isLocation()) { 1992 MachineLocation Location = Value.getLoc(); 1993 if (Location.isIndirect()) 1994 DwarfExpr.setMemoryLocationKind(); 1995 DIExpressionCursor Cursor(DIExpr); 1996 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo(); 1997 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1998 return; 1999 return DwarfExpr.addExpression(std::move(Cursor)); 2000 } else if (Value.isConstantFP()) { 2001 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt(); 2002 DwarfExpr.addUnsignedConstant(RawBytes); 2003 } 2004 DwarfExpr.addExpression(std::move(ExprCursor)); 2005 } 2006 2007 void DebugLocEntry::finalize(const AsmPrinter &AP, 2008 DebugLocStream::ListBuilder &List, 2009 const DIBasicType *BT, 2010 DwarfCompileUnit &TheCU) { 2011 assert(Begin != End && "unexpected location list entry with empty range"); 2012 DebugLocStream::EntryBuilder Entry(List, Begin, End); 2013 BufferByteStreamer Streamer = Entry.getStreamer(); 2014 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU); 2015 const DebugLocEntry::Value &Value = Values[0]; 2016 if (Value.isFragment()) { 2017 // Emit all fragments that belong to the same variable and range. 2018 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) { 2019 return P.isFragment(); 2020 }) && "all values are expected to be fragments"); 2021 assert(std::is_sorted(Values.begin(), Values.end()) && 2022 "fragments are expected to be sorted"); 2023 2024 for (auto Fragment : Values) 2025 emitDebugLocValue(AP, BT, Fragment, DwarfExpr); 2026 2027 } else { 2028 assert(Values.size() == 1 && "only fragments may have >1 value"); 2029 emitDebugLocValue(AP, BT, Value, DwarfExpr); 2030 } 2031 DwarfExpr.finalize(); 2032 } 2033 2034 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry, 2035 const DwarfCompileUnit *CU) { 2036 // Emit the size. 2037 Asm->OutStreamer->AddComment("Loc expr size"); 2038 if (getDwarfVersion() >= 5) 2039 Asm->EmitULEB128(DebugLocs.getBytes(Entry).size()); 2040 else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max()) 2041 Asm->emitInt16(DebugLocs.getBytes(Entry).size()); 2042 else { 2043 // The entry is too big to fit into 16 bit, drop it as there is nothing we 2044 // can do. 2045 Asm->emitInt16(0); 2046 return; 2047 } 2048 // Emit the entry. 2049 APByteStreamer Streamer(*Asm); 2050 emitDebugLocEntry(Streamer, Entry, CU); 2051 } 2052 2053 // Emit the common part of the DWARF 5 range/locations list tables header. 2054 static void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder, 2055 MCSymbol *TableStart, 2056 MCSymbol *TableEnd) { 2057 // Build the table header, which starts with the length field. 2058 Asm->OutStreamer->AddComment("Length"); 2059 Asm->EmitLabelDifference(TableEnd, TableStart, 4); 2060 Asm->OutStreamer->EmitLabel(TableStart); 2061 // Version number (DWARF v5 and later). 2062 Asm->OutStreamer->AddComment("Version"); 2063 Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion()); 2064 // Address size. 2065 Asm->OutStreamer->AddComment("Address size"); 2066 Asm->emitInt8(Asm->MAI->getCodePointerSize()); 2067 // Segment selector size. 2068 Asm->OutStreamer->AddComment("Segment selector size"); 2069 Asm->emitInt8(0); 2070 } 2071 2072 // Emit the header of a DWARF 5 range list table list table. Returns the symbol 2073 // that designates the end of the table for the caller to emit when the table is 2074 // complete. 2075 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm, 2076 const DwarfFile &Holder) { 2077 MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start"); 2078 MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end"); 2079 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 2080 2081 Asm->OutStreamer->AddComment("Offset entry count"); 2082 Asm->emitInt32(Holder.getRangeLists().size()); 2083 Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym()); 2084 2085 for (const RangeSpanList &List : Holder.getRangeLists()) 2086 Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(), 2087 4); 2088 2089 return TableEnd; 2090 } 2091 2092 // Emit the header of a DWARF 5 locations list table. Returns the symbol that 2093 // designates the end of the table for the caller to emit when the table is 2094 // complete. 2095 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm, 2096 const DwarfFile &Holder) { 2097 MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start"); 2098 MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end"); 2099 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 2100 2101 // FIXME: Generate the offsets table and use DW_FORM_loclistx with the 2102 // DW_AT_loclists_base attribute. Until then set the number of offsets to 0. 2103 Asm->OutStreamer->AddComment("Offset entry count"); 2104 Asm->emitInt32(0); 2105 Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym()); 2106 2107 return TableEnd; 2108 } 2109 2110 // Emit locations into the .debug_loc/.debug_rnglists section. 2111 void DwarfDebug::emitDebugLoc() { 2112 if (DebugLocs.getLists().empty()) 2113 return; 2114 2115 bool IsLocLists = getDwarfVersion() >= 5; 2116 MCSymbol *TableEnd = nullptr; 2117 if (IsLocLists) { 2118 Asm->OutStreamer->SwitchSection( 2119 Asm->getObjFileLowering().getDwarfLoclistsSection()); 2120 TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder 2121 : InfoHolder); 2122 } else { 2123 Asm->OutStreamer->SwitchSection( 2124 Asm->getObjFileLowering().getDwarfLocSection()); 2125 } 2126 2127 unsigned char Size = Asm->MAI->getCodePointerSize(); 2128 for (const auto &List : DebugLocs.getLists()) { 2129 Asm->OutStreamer->EmitLabel(List.Label); 2130 2131 const DwarfCompileUnit *CU = List.CU; 2132 const MCSymbol *Base = CU->getBaseAddress(); 2133 for (const auto &Entry : DebugLocs.getEntries(List)) { 2134 if (Base) { 2135 // Set up the range. This range is relative to the entry point of the 2136 // compile unit. This is a hard coded 0 for low_pc when we're emitting 2137 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 2138 if (IsLocLists) { 2139 Asm->OutStreamer->AddComment("DW_LLE_offset_pair"); 2140 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1); 2141 Asm->OutStreamer->AddComment(" starting offset"); 2142 Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base); 2143 Asm->OutStreamer->AddComment(" ending offset"); 2144 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base); 2145 } else { 2146 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 2147 Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 2148 } 2149 2150 emitDebugLocEntryLocation(Entry, CU); 2151 continue; 2152 } 2153 2154 // We have no base address. 2155 if (IsLocLists) { 2156 // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or 2157 // DW_LLE_startx_length in case if there is only a single range. 2158 // That should reduce the size of the debug data emited. 2159 // For now just use the DW_LLE_startx_length for all cases. 2160 Asm->OutStreamer->AddComment("DW_LLE_startx_length"); 2161 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2162 Asm->OutStreamer->AddComment(" start idx"); 2163 Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym)); 2164 Asm->OutStreamer->AddComment(" length"); 2165 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym); 2166 } else { 2167 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 2168 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 2169 } 2170 2171 emitDebugLocEntryLocation(Entry, CU); 2172 } 2173 2174 if (IsLocLists) { 2175 // .debug_loclists section ends with DW_LLE_end_of_list. 2176 Asm->OutStreamer->AddComment("DW_LLE_end_of_list"); 2177 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1); 2178 } else { 2179 // Terminate the .debug_loc list with two 0 values. 2180 Asm->OutStreamer->EmitIntValue(0, Size); 2181 Asm->OutStreamer->EmitIntValue(0, Size); 2182 } 2183 } 2184 2185 if (TableEnd) 2186 Asm->OutStreamer->EmitLabel(TableEnd); 2187 } 2188 2189 void DwarfDebug::emitDebugLocDWO() { 2190 for (const auto &List : DebugLocs.getLists()) { 2191 Asm->OutStreamer->SwitchSection( 2192 Asm->getObjFileLowering().getDwarfLocDWOSection()); 2193 Asm->OutStreamer->EmitLabel(List.Label); 2194 for (const auto &Entry : DebugLocs.getEntries(List)) { 2195 // GDB only supports startx_length in pre-standard split-DWARF. 2196 // (in v5 standard loclists, it currently* /only/ supports base_address + 2197 // offset_pair, so the implementations can't really share much since they 2198 // need to use different representations) 2199 // * as of October 2018, at least 2200 // Ideally/in v5, this could use SectionLabels to reuse existing addresses 2201 // in the address pool to minimize object size/relocations. 2202 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2203 unsigned idx = AddrPool.getIndex(Entry.BeginSym); 2204 Asm->EmitULEB128(idx); 2205 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 2206 2207 emitDebugLocEntryLocation(Entry, List.CU); 2208 } 2209 Asm->emitInt8(dwarf::DW_LLE_end_of_list); 2210 } 2211 } 2212 2213 struct ArangeSpan { 2214 const MCSymbol *Start, *End; 2215 }; 2216 2217 // Emit a debug aranges section, containing a CU lookup for any 2218 // address we can tie back to a CU. 2219 void DwarfDebug::emitDebugARanges() { 2220 // Provides a unique id per text section. 2221 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 2222 2223 // Filter labels by section. 2224 for (const SymbolCU &SCU : ArangeLabels) { 2225 if (SCU.Sym->isInSection()) { 2226 // Make a note of this symbol and it's section. 2227 MCSection *Section = &SCU.Sym->getSection(); 2228 if (!Section->getKind().isMetadata()) 2229 SectionMap[Section].push_back(SCU); 2230 } else { 2231 // Some symbols (e.g. common/bss on mach-o) can have no section but still 2232 // appear in the output. This sucks as we rely on sections to build 2233 // arange spans. We can do it without, but it's icky. 2234 SectionMap[nullptr].push_back(SCU); 2235 } 2236 } 2237 2238 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 2239 2240 for (auto &I : SectionMap) { 2241 MCSection *Section = I.first; 2242 SmallVector<SymbolCU, 8> &List = I.second; 2243 if (List.size() < 1) 2244 continue; 2245 2246 // If we have no section (e.g. common), just write out 2247 // individual spans for each symbol. 2248 if (!Section) { 2249 for (const SymbolCU &Cur : List) { 2250 ArangeSpan Span; 2251 Span.Start = Cur.Sym; 2252 Span.End = nullptr; 2253 assert(Cur.CU); 2254 Spans[Cur.CU].push_back(Span); 2255 } 2256 continue; 2257 } 2258 2259 // Sort the symbols by offset within the section. 2260 std::stable_sort( 2261 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) { 2262 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 2263 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 2264 2265 // Symbols with no order assigned should be placed at the end. 2266 // (e.g. section end labels) 2267 if (IA == 0) 2268 return false; 2269 if (IB == 0) 2270 return true; 2271 return IA < IB; 2272 }); 2273 2274 // Insert a final terminator. 2275 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section))); 2276 2277 // Build spans between each label. 2278 const MCSymbol *StartSym = List[0].Sym; 2279 for (size_t n = 1, e = List.size(); n < e; n++) { 2280 const SymbolCU &Prev = List[n - 1]; 2281 const SymbolCU &Cur = List[n]; 2282 2283 // Try and build the longest span we can within the same CU. 2284 if (Cur.CU != Prev.CU) { 2285 ArangeSpan Span; 2286 Span.Start = StartSym; 2287 Span.End = Cur.Sym; 2288 assert(Prev.CU); 2289 Spans[Prev.CU].push_back(Span); 2290 StartSym = Cur.Sym; 2291 } 2292 } 2293 } 2294 2295 // Start the dwarf aranges section. 2296 Asm->OutStreamer->SwitchSection( 2297 Asm->getObjFileLowering().getDwarfARangesSection()); 2298 2299 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 2300 2301 // Build a list of CUs used. 2302 std::vector<DwarfCompileUnit *> CUs; 2303 for (const auto &it : Spans) { 2304 DwarfCompileUnit *CU = it.first; 2305 CUs.push_back(CU); 2306 } 2307 2308 // Sort the CU list (again, to ensure consistent output order). 2309 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 2310 return A->getUniqueID() < B->getUniqueID(); 2311 }); 2312 2313 // Emit an arange table for each CU we used. 2314 for (DwarfCompileUnit *CU : CUs) { 2315 std::vector<ArangeSpan> &List = Spans[CU]; 2316 2317 // Describe the skeleton CU's offset and length, not the dwo file's. 2318 if (auto *Skel = CU->getSkeleton()) 2319 CU = Skel; 2320 2321 // Emit size of content not including length itself. 2322 unsigned ContentSize = 2323 sizeof(int16_t) + // DWARF ARange version number 2324 sizeof(int32_t) + // Offset of CU in the .debug_info section 2325 sizeof(int8_t) + // Pointer Size (in bytes) 2326 sizeof(int8_t); // Segment Size (in bytes) 2327 2328 unsigned TupleSize = PtrSize * 2; 2329 2330 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 2331 unsigned Padding = 2332 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 2333 2334 ContentSize += Padding; 2335 ContentSize += (List.size() + 1) * TupleSize; 2336 2337 // For each compile unit, write the list of spans it covers. 2338 Asm->OutStreamer->AddComment("Length of ARange Set"); 2339 Asm->emitInt32(ContentSize); 2340 Asm->OutStreamer->AddComment("DWARF Arange version number"); 2341 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); 2342 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 2343 emitSectionReference(*CU); 2344 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 2345 Asm->emitInt8(PtrSize); 2346 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 2347 Asm->emitInt8(0); 2348 2349 Asm->OutStreamer->emitFill(Padding, 0xff); 2350 2351 for (const ArangeSpan &Span : List) { 2352 Asm->EmitLabelReference(Span.Start, PtrSize); 2353 2354 // Calculate the size as being from the span start to it's end. 2355 if (Span.End) { 2356 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 2357 } else { 2358 // For symbols without an end marker (e.g. common), we 2359 // write a single arange entry containing just that one symbol. 2360 uint64_t Size = SymSize[Span.Start]; 2361 if (Size == 0) 2362 Size = 1; 2363 2364 Asm->OutStreamer->EmitIntValue(Size, PtrSize); 2365 } 2366 } 2367 2368 Asm->OutStreamer->AddComment("ARange terminator"); 2369 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2370 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2371 } 2372 } 2373 2374 /// Emit a single range list. We handle both DWARF v5 and earlier. 2375 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, 2376 const RangeSpanList &List) { 2377 2378 auto DwarfVersion = DD.getDwarfVersion(); 2379 // Emit our symbol so we can find the beginning of the range. 2380 Asm->OutStreamer->EmitLabel(List.getSym()); 2381 // Gather all the ranges that apply to the same section so they can share 2382 // a base address entry. 2383 MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges; 2384 // Size for our labels. 2385 auto Size = Asm->MAI->getCodePointerSize(); 2386 2387 for (const RangeSpan &Range : List.getRanges()) 2388 SectionRanges[&Range.getStart()->getSection()].push_back(&Range); 2389 2390 const DwarfCompileUnit &CU = List.getCU(); 2391 const MCSymbol *CUBase = CU.getBaseAddress(); 2392 bool BaseIsSet = false; 2393 for (const auto &P : SectionRanges) { 2394 // Don't bother with a base address entry if there's only one range in 2395 // this section in this range list - for example ranges for a CU will 2396 // usually consist of single regions from each of many sections 2397 // (-ffunction-sections, or just C++ inline functions) except under LTO 2398 // or optnone where there may be holes in a single CU's section 2399 // contributions. 2400 auto *Base = CUBase; 2401 if (!Base && (P.second.size() > 1 || DwarfVersion < 5) && 2402 (CU.getCUNode()->getRangesBaseAddress() || DwarfVersion >= 5)) { 2403 BaseIsSet = true; 2404 // FIXME/use care: This may not be a useful base address if it's not 2405 // the lowest address/range in this object. 2406 Base = P.second.front()->getStart(); 2407 if (DwarfVersion >= 5) { 2408 Base = DD.getSectionLabel(&Base->getSection()); 2409 Asm->OutStreamer->AddComment("DW_RLE_base_addressx"); 2410 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1); 2411 Asm->OutStreamer->AddComment(" base address index"); 2412 Asm->EmitULEB128(DD.getAddressPool().getIndex(Base)); 2413 } else { 2414 Asm->OutStreamer->EmitIntValue(-1, Size); 2415 Asm->OutStreamer->AddComment(" base address"); 2416 Asm->OutStreamer->EmitSymbolValue(Base, Size); 2417 } 2418 } else if (BaseIsSet && DwarfVersion < 5) { 2419 BaseIsSet = false; 2420 assert(!Base); 2421 Asm->OutStreamer->EmitIntValue(-1, Size); 2422 Asm->OutStreamer->EmitIntValue(0, Size); 2423 } 2424 2425 for (const auto *RS : P.second) { 2426 const MCSymbol *Begin = RS->getStart(); 2427 const MCSymbol *End = RS->getEnd(); 2428 assert(Begin && "Range without a begin symbol?"); 2429 assert(End && "Range without an end symbol?"); 2430 if (Base) { 2431 if (DwarfVersion >= 5) { 2432 // Emit DW_RLE_offset_pair when we have a base. 2433 Asm->OutStreamer->AddComment("DW_RLE_offset_pair"); 2434 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1); 2435 Asm->OutStreamer->AddComment(" starting offset"); 2436 Asm->EmitLabelDifferenceAsULEB128(Begin, Base); 2437 Asm->OutStreamer->AddComment(" ending offset"); 2438 Asm->EmitLabelDifferenceAsULEB128(End, Base); 2439 } else { 2440 Asm->EmitLabelDifference(Begin, Base, Size); 2441 Asm->EmitLabelDifference(End, Base, Size); 2442 } 2443 } else if (DwarfVersion >= 5) { 2444 Asm->OutStreamer->AddComment("DW_RLE_startx_length"); 2445 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1); 2446 Asm->OutStreamer->AddComment(" start index"); 2447 Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin)); 2448 Asm->OutStreamer->AddComment(" length"); 2449 Asm->EmitLabelDifferenceAsULEB128(End, Begin); 2450 } else { 2451 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 2452 Asm->OutStreamer->EmitSymbolValue(End, Size); 2453 } 2454 } 2455 } 2456 if (DwarfVersion >= 5) { 2457 Asm->OutStreamer->AddComment("DW_RLE_end_of_list"); 2458 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1); 2459 } else { 2460 // Terminate the list with two 0 values. 2461 Asm->OutStreamer->EmitIntValue(0, Size); 2462 Asm->OutStreamer->EmitIntValue(0, Size); 2463 } 2464 } 2465 2466 static void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm, 2467 const DwarfFile &Holder, MCSymbol *TableEnd) { 2468 for (const RangeSpanList &List : Holder.getRangeLists()) 2469 emitRangeList(DD, Asm, List); 2470 2471 if (TableEnd) 2472 Asm->OutStreamer->EmitLabel(TableEnd); 2473 } 2474 2475 /// Emit address ranges into the .debug_ranges section or into the DWARF v5 2476 /// .debug_rnglists section. 2477 void DwarfDebug::emitDebugRanges() { 2478 if (CUMap.empty()) 2479 return; 2480 2481 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2482 2483 if (Holder.getRangeLists().empty()) 2484 return; 2485 2486 assert(useRangesSection()); 2487 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2488 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2489 })); 2490 2491 // Start the dwarf ranges section. 2492 MCSymbol *TableEnd = nullptr; 2493 if (getDwarfVersion() >= 5) { 2494 Asm->OutStreamer->SwitchSection( 2495 Asm->getObjFileLowering().getDwarfRnglistsSection()); 2496 TableEnd = emitRnglistsTableHeader(Asm, Holder); 2497 } else 2498 Asm->OutStreamer->SwitchSection( 2499 Asm->getObjFileLowering().getDwarfRangesSection()); 2500 2501 emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2502 } 2503 2504 void DwarfDebug::emitDebugRangesDWO() { 2505 assert(useSplitDwarf()); 2506 2507 if (CUMap.empty()) 2508 return; 2509 2510 const auto &Holder = InfoHolder; 2511 2512 if (Holder.getRangeLists().empty()) 2513 return; 2514 2515 assert(getDwarfVersion() >= 5); 2516 assert(useRangesSection()); 2517 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2518 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2519 })); 2520 2521 // Start the dwarf ranges section. 2522 Asm->OutStreamer->SwitchSection( 2523 Asm->getObjFileLowering().getDwarfRnglistsDWOSection()); 2524 MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder); 2525 2526 emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2527 } 2528 2529 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 2530 for (auto *MN : Nodes) { 2531 if (auto *M = dyn_cast<DIMacro>(MN)) 2532 emitMacro(*M); 2533 else if (auto *F = dyn_cast<DIMacroFile>(MN)) 2534 emitMacroFile(*F, U); 2535 else 2536 llvm_unreachable("Unexpected DI type!"); 2537 } 2538 } 2539 2540 void DwarfDebug::emitMacro(DIMacro &M) { 2541 Asm->EmitULEB128(M.getMacinfoType()); 2542 Asm->EmitULEB128(M.getLine()); 2543 StringRef Name = M.getName(); 2544 StringRef Value = M.getValue(); 2545 Asm->OutStreamer->EmitBytes(Name); 2546 if (!Value.empty()) { 2547 // There should be one space between macro name and macro value. 2548 Asm->emitInt8(' '); 2549 Asm->OutStreamer->EmitBytes(Value); 2550 } 2551 Asm->emitInt8('\0'); 2552 } 2553 2554 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 2555 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 2556 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file); 2557 Asm->EmitULEB128(F.getLine()); 2558 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile())); 2559 handleMacroNodes(F.getElements(), U); 2560 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file); 2561 } 2562 2563 /// Emit macros into a debug macinfo section. 2564 void DwarfDebug::emitDebugMacinfo() { 2565 if (CUMap.empty()) 2566 return; 2567 2568 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2569 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2570 })) 2571 return; 2572 2573 // Start the dwarf macinfo section. 2574 Asm->OutStreamer->SwitchSection( 2575 Asm->getObjFileLowering().getDwarfMacinfoSection()); 2576 2577 for (const auto &P : CUMap) { 2578 auto &TheCU = *P.second; 2579 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 2580 continue; 2581 auto *SkCU = TheCU.getSkeleton(); 2582 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 2583 auto *CUNode = cast<DICompileUnit>(P.first); 2584 DIMacroNodeArray Macros = CUNode->getMacros(); 2585 if (!Macros.empty()) { 2586 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin()); 2587 handleMacroNodes(Macros, U); 2588 } 2589 } 2590 Asm->OutStreamer->AddComment("End Of Macro List Mark"); 2591 Asm->emitInt8(0); 2592 } 2593 2594 // DWARF5 Experimental Separate Dwarf emitters. 2595 2596 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 2597 std::unique_ptr<DwarfCompileUnit> NewU) { 2598 2599 if (!CompilationDir.empty()) 2600 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2601 2602 addGnuPubAttributes(*NewU, Die); 2603 2604 SkeletonHolder.addUnit(std::move(NewU)); 2605 } 2606 2607 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 2608 2609 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 2610 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 2611 DwarfCompileUnit &NewCU = *OwnedUnit; 2612 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 2613 2614 NewCU.initStmtList(); 2615 2616 if (useSegmentedStringOffsetsTable()) 2617 NewCU.addStringOffsetsStart(); 2618 2619 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 2620 2621 return NewCU; 2622 } 2623 2624 // Emit the .debug_info.dwo section for separated dwarf. This contains the 2625 // compile units that would normally be in debug_info. 2626 void DwarfDebug::emitDebugInfoDWO() { 2627 assert(useSplitDwarf() && "No split dwarf debug info?"); 2628 // Don't emit relocations into the dwo file. 2629 InfoHolder.emitUnits(/* UseOffsets */ true); 2630 } 2631 2632 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2633 // abbreviations for the .debug_info.dwo section. 2634 void DwarfDebug::emitDebugAbbrevDWO() { 2635 assert(useSplitDwarf() && "No split dwarf?"); 2636 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2637 } 2638 2639 void DwarfDebug::emitDebugLineDWO() { 2640 assert(useSplitDwarf() && "No split dwarf?"); 2641 SplitTypeUnitFileTable.Emit( 2642 *Asm->OutStreamer, MCDwarfLineTableParams(), 2643 Asm->getObjFileLowering().getDwarfLineDWOSection()); 2644 } 2645 2646 void DwarfDebug::emitStringOffsetsTableHeaderDWO() { 2647 assert(useSplitDwarf() && "No split dwarf?"); 2648 InfoHolder.getStringPool().emitStringOffsetsTableHeader( 2649 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(), 2650 InfoHolder.getStringOffsetsStartSym()); 2651 } 2652 2653 // Emit the .debug_str.dwo section for separated dwarf. This contains the 2654 // string section and is identical in format to traditional .debug_str 2655 // sections. 2656 void DwarfDebug::emitDebugStrDWO() { 2657 if (useSegmentedStringOffsetsTable()) 2658 emitStringOffsetsTableHeaderDWO(); 2659 assert(useSplitDwarf() && "No split dwarf?"); 2660 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2661 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2662 OffSec, /* UseRelativeOffsets = */ false); 2663 } 2664 2665 // Emit address pool. 2666 void DwarfDebug::emitDebugAddr() { 2667 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 2668 } 2669 2670 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2671 if (!useSplitDwarf()) 2672 return nullptr; 2673 const DICompileUnit *DIUnit = CU.getCUNode(); 2674 SplitTypeUnitFileTable.maybeSetRootFile( 2675 DIUnit->getDirectory(), DIUnit->getFilename(), 2676 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource()); 2677 return &SplitTypeUnitFileTable; 2678 } 2679 2680 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 2681 MD5 Hash; 2682 Hash.update(Identifier); 2683 // ... take the least significant 8 bytes and return those. Our MD5 2684 // implementation always returns its results in little endian, so we actually 2685 // need the "high" word. 2686 MD5::MD5Result Result; 2687 Hash.final(Result); 2688 return Result.high(); 2689 } 2690 2691 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2692 StringRef Identifier, DIE &RefDie, 2693 const DICompositeType *CTy) { 2694 // Fast path if we're building some type units and one has already used the 2695 // address pool we know we're going to throw away all this work anyway, so 2696 // don't bother building dependent types. 2697 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 2698 return; 2699 2700 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 2701 if (!Ins.second) { 2702 CU.addDIETypeSignature(RefDie, Ins.first->second); 2703 return; 2704 } 2705 2706 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 2707 AddrPool.resetUsedFlag(); 2708 2709 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 2710 getDwoLineTable(CU)); 2711 DwarfTypeUnit &NewTU = *OwnedUnit; 2712 DIE &UnitDie = NewTU.getUnitDie(); 2713 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy); 2714 2715 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2716 CU.getLanguage()); 2717 2718 uint64_t Signature = makeTypeSignature(Identifier); 2719 NewTU.setTypeSignature(Signature); 2720 Ins.first->second = Signature; 2721 2722 if (useSplitDwarf()) { 2723 MCSection *Section = 2724 getDwarfVersion() <= 4 2725 ? Asm->getObjFileLowering().getDwarfTypesDWOSection() 2726 : Asm->getObjFileLowering().getDwarfInfoDWOSection(); 2727 NewTU.setSection(Section); 2728 } else { 2729 MCSection *Section = 2730 getDwarfVersion() <= 4 2731 ? Asm->getObjFileLowering().getDwarfTypesSection(Signature) 2732 : Asm->getObjFileLowering().getDwarfInfoSection(Signature); 2733 NewTU.setSection(Section); 2734 // Non-split type units reuse the compile unit's line table. 2735 CU.applyStmtList(UnitDie); 2736 } 2737 2738 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 2739 // units. 2740 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 2741 NewTU.addStringOffsetsStart(); 2742 2743 NewTU.setType(NewTU.createTypeDIE(CTy)); 2744 2745 if (TopLevelType) { 2746 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 2747 TypeUnitsUnderConstruction.clear(); 2748 2749 // Types referencing entries in the address table cannot be placed in type 2750 // units. 2751 if (AddrPool.hasBeenUsed()) { 2752 2753 // Remove all the types built while building this type. 2754 // This is pessimistic as some of these types might not be dependent on 2755 // the type that used an address. 2756 for (const auto &TU : TypeUnitsToAdd) 2757 TypeSignatures.erase(TU.second); 2758 2759 // Construct this type in the CU directly. 2760 // This is inefficient because all the dependent types will be rebuilt 2761 // from scratch, including building them in type units, discovering that 2762 // they depend on addresses, throwing them out and rebuilding them. 2763 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 2764 return; 2765 } 2766 2767 // If the type wasn't dependent on fission addresses, finish adding the type 2768 // and all its dependent types. 2769 for (auto &TU : TypeUnitsToAdd) { 2770 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 2771 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 2772 } 2773 } 2774 CU.addDIETypeSignature(RefDie, Signature); 2775 } 2776 2777 // Add the Name along with its companion DIE to the appropriate accelerator 2778 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for 2779 // AccelTableKind::Apple, we use the table we got as an argument). If 2780 // accelerator tables are disabled, this function does nothing. 2781 template <typename DataT> 2782 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU, 2783 AccelTable<DataT> &AppleAccel, StringRef Name, 2784 const DIE &Die) { 2785 if (getAccelTableKind() == AccelTableKind::None) 2786 return; 2787 2788 if (getAccelTableKind() != AccelTableKind::Apple && 2789 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 2790 return; 2791 2792 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2793 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name); 2794 2795 switch (getAccelTableKind()) { 2796 case AccelTableKind::Apple: 2797 AppleAccel.addName(Ref, Die); 2798 break; 2799 case AccelTableKind::Dwarf: 2800 AccelDebugNames.addName(Ref, Die); 2801 break; 2802 case AccelTableKind::Default: 2803 llvm_unreachable("Default should have already been resolved."); 2804 case AccelTableKind::None: 2805 llvm_unreachable("None handled above"); 2806 } 2807 } 2808 2809 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name, 2810 const DIE &Die) { 2811 addAccelNameImpl(CU, AccelNames, Name, Die); 2812 } 2813 2814 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name, 2815 const DIE &Die) { 2816 // ObjC names go only into the Apple accelerator tables. 2817 if (getAccelTableKind() == AccelTableKind::Apple) 2818 addAccelNameImpl(CU, AccelObjC, Name, Die); 2819 } 2820 2821 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name, 2822 const DIE &Die) { 2823 addAccelNameImpl(CU, AccelNamespace, Name, Die); 2824 } 2825 2826 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name, 2827 const DIE &Die, char Flags) { 2828 addAccelNameImpl(CU, AccelTypes, Name, Die); 2829 } 2830 2831 uint16_t DwarfDebug::getDwarfVersion() const { 2832 return Asm->OutStreamer->getContext().getDwarfVersion(); 2833 } 2834 2835 void DwarfDebug::addSectionLabel(const MCSymbol *Sym) { 2836 SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym)); 2837 } 2838 2839 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) { 2840 return SectionLabels.find(S)->second; 2841 } 2842