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 2041 Asm->emitInt16(DebugLocs.getBytes(Entry).size()); 2042 // Emit the entry. 2043 APByteStreamer Streamer(*Asm); 2044 emitDebugLocEntry(Streamer, Entry, CU); 2045 } 2046 2047 // Emit the common part of the DWARF 5 range/locations list tables header. 2048 static void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder, 2049 MCSymbol *TableStart, 2050 MCSymbol *TableEnd) { 2051 // Build the table header, which starts with the length field. 2052 Asm->OutStreamer->AddComment("Length"); 2053 Asm->EmitLabelDifference(TableEnd, TableStart, 4); 2054 Asm->OutStreamer->EmitLabel(TableStart); 2055 // Version number (DWARF v5 and later). 2056 Asm->OutStreamer->AddComment("Version"); 2057 Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion()); 2058 // Address size. 2059 Asm->OutStreamer->AddComment("Address size"); 2060 Asm->emitInt8(Asm->MAI->getCodePointerSize()); 2061 // Segment selector size. 2062 Asm->OutStreamer->AddComment("Segment selector size"); 2063 Asm->emitInt8(0); 2064 } 2065 2066 // Emit the header of a DWARF 5 range list table list table. Returns the symbol 2067 // that designates the end of the table for the caller to emit when the table is 2068 // complete. 2069 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm, 2070 const DwarfFile &Holder) { 2071 MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start"); 2072 MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end"); 2073 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 2074 2075 Asm->OutStreamer->AddComment("Offset entry count"); 2076 Asm->emitInt32(Holder.getRangeLists().size()); 2077 Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym()); 2078 2079 for (const RangeSpanList &List : Holder.getRangeLists()) 2080 Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(), 2081 4); 2082 2083 return TableEnd; 2084 } 2085 2086 // Emit the header of a DWARF 5 locations list table. Returns the symbol that 2087 // designates the end of the table for the caller to emit when the table is 2088 // complete. 2089 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm, 2090 const DwarfFile &Holder) { 2091 MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start"); 2092 MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end"); 2093 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 2094 2095 // FIXME: Generate the offsets table and use DW_FORM_loclistx with the 2096 // DW_AT_loclists_base attribute. Until then set the number of offsets to 0. 2097 Asm->OutStreamer->AddComment("Offset entry count"); 2098 Asm->emitInt32(0); 2099 Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym()); 2100 2101 return TableEnd; 2102 } 2103 2104 // Emit locations into the .debug_loc/.debug_rnglists section. 2105 void DwarfDebug::emitDebugLoc() { 2106 if (DebugLocs.getLists().empty()) 2107 return; 2108 2109 bool IsLocLists = getDwarfVersion() >= 5; 2110 MCSymbol *TableEnd = nullptr; 2111 if (IsLocLists) { 2112 Asm->OutStreamer->SwitchSection( 2113 Asm->getObjFileLowering().getDwarfLoclistsSection()); 2114 TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder 2115 : InfoHolder); 2116 } else { 2117 Asm->OutStreamer->SwitchSection( 2118 Asm->getObjFileLowering().getDwarfLocSection()); 2119 } 2120 2121 unsigned char Size = Asm->MAI->getCodePointerSize(); 2122 for (const auto &List : DebugLocs.getLists()) { 2123 Asm->OutStreamer->EmitLabel(List.Label); 2124 2125 const DwarfCompileUnit *CU = List.CU; 2126 const MCSymbol *Base = CU->getBaseAddress(); 2127 for (const auto &Entry : DebugLocs.getEntries(List)) { 2128 if (Base) { 2129 // Set up the range. This range is relative to the entry point of the 2130 // compile unit. This is a hard coded 0 for low_pc when we're emitting 2131 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 2132 if (IsLocLists) { 2133 Asm->OutStreamer->AddComment("DW_LLE_offset_pair"); 2134 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1); 2135 Asm->OutStreamer->AddComment(" starting offset"); 2136 Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base); 2137 Asm->OutStreamer->AddComment(" ending offset"); 2138 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base); 2139 } else { 2140 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 2141 Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 2142 } 2143 2144 emitDebugLocEntryLocation(Entry, CU); 2145 continue; 2146 } 2147 2148 // We have no base address. 2149 if (IsLocLists) { 2150 // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or 2151 // DW_LLE_startx_length in case if there is only a single range. 2152 // That should reduce the size of the debug data emited. 2153 // For now just use the DW_LLE_startx_length for all cases. 2154 Asm->OutStreamer->AddComment("DW_LLE_startx_length"); 2155 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2156 Asm->OutStreamer->AddComment(" start idx"); 2157 Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym)); 2158 Asm->OutStreamer->AddComment(" length"); 2159 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym); 2160 } else { 2161 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 2162 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 2163 } 2164 2165 emitDebugLocEntryLocation(Entry, CU); 2166 } 2167 2168 if (IsLocLists) { 2169 // .debug_loclists section ends with DW_LLE_end_of_list. 2170 Asm->OutStreamer->AddComment("DW_LLE_end_of_list"); 2171 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1); 2172 } else { 2173 // Terminate the .debug_loc list with two 0 values. 2174 Asm->OutStreamer->EmitIntValue(0, Size); 2175 Asm->OutStreamer->EmitIntValue(0, Size); 2176 } 2177 } 2178 2179 if (TableEnd) 2180 Asm->OutStreamer->EmitLabel(TableEnd); 2181 } 2182 2183 void DwarfDebug::emitDebugLocDWO() { 2184 for (const auto &List : DebugLocs.getLists()) { 2185 Asm->OutStreamer->SwitchSection( 2186 Asm->getObjFileLowering().getDwarfLocDWOSection()); 2187 Asm->OutStreamer->EmitLabel(List.Label); 2188 for (const auto &Entry : DebugLocs.getEntries(List)) { 2189 // GDB only supports startx_length in pre-standard split-DWARF. 2190 // (in v5 standard loclists, it currently* /only/ supports base_address + 2191 // offset_pair, so the implementations can't really share much since they 2192 // need to use different representations) 2193 // * as of October 2018, at least 2194 // Ideally/in v5, this could use SectionLabels to reuse existing addresses 2195 // in the address pool to minimize object size/relocations. 2196 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2197 unsigned idx = AddrPool.getIndex(Entry.BeginSym); 2198 Asm->EmitULEB128(idx); 2199 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 2200 2201 emitDebugLocEntryLocation(Entry, List.CU); 2202 } 2203 Asm->emitInt8(dwarf::DW_LLE_end_of_list); 2204 } 2205 } 2206 2207 struct ArangeSpan { 2208 const MCSymbol *Start, *End; 2209 }; 2210 2211 // Emit a debug aranges section, containing a CU lookup for any 2212 // address we can tie back to a CU. 2213 void DwarfDebug::emitDebugARanges() { 2214 // Provides a unique id per text section. 2215 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 2216 2217 // Filter labels by section. 2218 for (const SymbolCU &SCU : ArangeLabels) { 2219 if (SCU.Sym->isInSection()) { 2220 // Make a note of this symbol and it's section. 2221 MCSection *Section = &SCU.Sym->getSection(); 2222 if (!Section->getKind().isMetadata()) 2223 SectionMap[Section].push_back(SCU); 2224 } else { 2225 // Some symbols (e.g. common/bss on mach-o) can have no section but still 2226 // appear in the output. This sucks as we rely on sections to build 2227 // arange spans. We can do it without, but it's icky. 2228 SectionMap[nullptr].push_back(SCU); 2229 } 2230 } 2231 2232 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 2233 2234 for (auto &I : SectionMap) { 2235 MCSection *Section = I.first; 2236 SmallVector<SymbolCU, 8> &List = I.second; 2237 if (List.size() < 1) 2238 continue; 2239 2240 // If we have no section (e.g. common), just write out 2241 // individual spans for each symbol. 2242 if (!Section) { 2243 for (const SymbolCU &Cur : List) { 2244 ArangeSpan Span; 2245 Span.Start = Cur.Sym; 2246 Span.End = nullptr; 2247 assert(Cur.CU); 2248 Spans[Cur.CU].push_back(Span); 2249 } 2250 continue; 2251 } 2252 2253 // Sort the symbols by offset within the section. 2254 std::stable_sort( 2255 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) { 2256 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 2257 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 2258 2259 // Symbols with no order assigned should be placed at the end. 2260 // (e.g. section end labels) 2261 if (IA == 0) 2262 return false; 2263 if (IB == 0) 2264 return true; 2265 return IA < IB; 2266 }); 2267 2268 // Insert a final terminator. 2269 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section))); 2270 2271 // Build spans between each label. 2272 const MCSymbol *StartSym = List[0].Sym; 2273 for (size_t n = 1, e = List.size(); n < e; n++) { 2274 const SymbolCU &Prev = List[n - 1]; 2275 const SymbolCU &Cur = List[n]; 2276 2277 // Try and build the longest span we can within the same CU. 2278 if (Cur.CU != Prev.CU) { 2279 ArangeSpan Span; 2280 Span.Start = StartSym; 2281 Span.End = Cur.Sym; 2282 assert(Prev.CU); 2283 Spans[Prev.CU].push_back(Span); 2284 StartSym = Cur.Sym; 2285 } 2286 } 2287 } 2288 2289 // Start the dwarf aranges section. 2290 Asm->OutStreamer->SwitchSection( 2291 Asm->getObjFileLowering().getDwarfARangesSection()); 2292 2293 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 2294 2295 // Build a list of CUs used. 2296 std::vector<DwarfCompileUnit *> CUs; 2297 for (const auto &it : Spans) { 2298 DwarfCompileUnit *CU = it.first; 2299 CUs.push_back(CU); 2300 } 2301 2302 // Sort the CU list (again, to ensure consistent output order). 2303 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 2304 return A->getUniqueID() < B->getUniqueID(); 2305 }); 2306 2307 // Emit an arange table for each CU we used. 2308 for (DwarfCompileUnit *CU : CUs) { 2309 std::vector<ArangeSpan> &List = Spans[CU]; 2310 2311 // Describe the skeleton CU's offset and length, not the dwo file's. 2312 if (auto *Skel = CU->getSkeleton()) 2313 CU = Skel; 2314 2315 // Emit size of content not including length itself. 2316 unsigned ContentSize = 2317 sizeof(int16_t) + // DWARF ARange version number 2318 sizeof(int32_t) + // Offset of CU in the .debug_info section 2319 sizeof(int8_t) + // Pointer Size (in bytes) 2320 sizeof(int8_t); // Segment Size (in bytes) 2321 2322 unsigned TupleSize = PtrSize * 2; 2323 2324 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 2325 unsigned Padding = 2326 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 2327 2328 ContentSize += Padding; 2329 ContentSize += (List.size() + 1) * TupleSize; 2330 2331 // For each compile unit, write the list of spans it covers. 2332 Asm->OutStreamer->AddComment("Length of ARange Set"); 2333 Asm->emitInt32(ContentSize); 2334 Asm->OutStreamer->AddComment("DWARF Arange version number"); 2335 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); 2336 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 2337 emitSectionReference(*CU); 2338 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 2339 Asm->emitInt8(PtrSize); 2340 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 2341 Asm->emitInt8(0); 2342 2343 Asm->OutStreamer->emitFill(Padding, 0xff); 2344 2345 for (const ArangeSpan &Span : List) { 2346 Asm->EmitLabelReference(Span.Start, PtrSize); 2347 2348 // Calculate the size as being from the span start to it's end. 2349 if (Span.End) { 2350 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 2351 } else { 2352 // For symbols without an end marker (e.g. common), we 2353 // write a single arange entry containing just that one symbol. 2354 uint64_t Size = SymSize[Span.Start]; 2355 if (Size == 0) 2356 Size = 1; 2357 2358 Asm->OutStreamer->EmitIntValue(Size, PtrSize); 2359 } 2360 } 2361 2362 Asm->OutStreamer->AddComment("ARange terminator"); 2363 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2364 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2365 } 2366 } 2367 2368 /// Emit a single range list. We handle both DWARF v5 and earlier. 2369 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, 2370 const RangeSpanList &List) { 2371 2372 auto DwarfVersion = DD.getDwarfVersion(); 2373 // Emit our symbol so we can find the beginning of the range. 2374 Asm->OutStreamer->EmitLabel(List.getSym()); 2375 // Gather all the ranges that apply to the same section so they can share 2376 // a base address entry. 2377 MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges; 2378 // Size for our labels. 2379 auto Size = Asm->MAI->getCodePointerSize(); 2380 2381 for (const RangeSpan &Range : List.getRanges()) 2382 SectionRanges[&Range.getStart()->getSection()].push_back(&Range); 2383 2384 const DwarfCompileUnit &CU = List.getCU(); 2385 const MCSymbol *CUBase = CU.getBaseAddress(); 2386 bool BaseIsSet = false; 2387 for (const auto &P : SectionRanges) { 2388 // Don't bother with a base address entry if there's only one range in 2389 // this section in this range list - for example ranges for a CU will 2390 // usually consist of single regions from each of many sections 2391 // (-ffunction-sections, or just C++ inline functions) except under LTO 2392 // or optnone where there may be holes in a single CU's section 2393 // contributions. 2394 auto *Base = CUBase; 2395 if (!Base && (P.second.size() > 1 || DwarfVersion < 5) && 2396 (CU.getCUNode()->getRangesBaseAddress() || DwarfVersion >= 5)) { 2397 BaseIsSet = true; 2398 // FIXME/use care: This may not be a useful base address if it's not 2399 // the lowest address/range in this object. 2400 Base = P.second.front()->getStart(); 2401 if (DwarfVersion >= 5) { 2402 Base = DD.getSectionLabel(&Base->getSection()); 2403 Asm->OutStreamer->AddComment("DW_RLE_base_addressx"); 2404 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1); 2405 Asm->OutStreamer->AddComment(" base address index"); 2406 Asm->EmitULEB128(DD.getAddressPool().getIndex(Base)); 2407 } else { 2408 Asm->OutStreamer->EmitIntValue(-1, Size); 2409 Asm->OutStreamer->AddComment(" base address"); 2410 Asm->OutStreamer->EmitSymbolValue(Base, Size); 2411 } 2412 } else if (BaseIsSet && DwarfVersion < 5) { 2413 BaseIsSet = false; 2414 assert(!Base); 2415 Asm->OutStreamer->EmitIntValue(-1, Size); 2416 Asm->OutStreamer->EmitIntValue(0, Size); 2417 } 2418 2419 for (const auto *RS : P.second) { 2420 const MCSymbol *Begin = RS->getStart(); 2421 const MCSymbol *End = RS->getEnd(); 2422 assert(Begin && "Range without a begin symbol?"); 2423 assert(End && "Range without an end symbol?"); 2424 if (Base) { 2425 if (DwarfVersion >= 5) { 2426 // Emit DW_RLE_offset_pair when we have a base. 2427 Asm->OutStreamer->AddComment("DW_RLE_offset_pair"); 2428 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1); 2429 Asm->OutStreamer->AddComment(" starting offset"); 2430 Asm->EmitLabelDifferenceAsULEB128(Begin, Base); 2431 Asm->OutStreamer->AddComment(" ending offset"); 2432 Asm->EmitLabelDifferenceAsULEB128(End, Base); 2433 } else { 2434 Asm->EmitLabelDifference(Begin, Base, Size); 2435 Asm->EmitLabelDifference(End, Base, Size); 2436 } 2437 } else if (DwarfVersion >= 5) { 2438 Asm->OutStreamer->AddComment("DW_RLE_startx_length"); 2439 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1); 2440 Asm->OutStreamer->AddComment(" start index"); 2441 Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin)); 2442 Asm->OutStreamer->AddComment(" length"); 2443 Asm->EmitLabelDifferenceAsULEB128(End, Begin); 2444 } else { 2445 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 2446 Asm->OutStreamer->EmitSymbolValue(End, Size); 2447 } 2448 } 2449 } 2450 if (DwarfVersion >= 5) { 2451 Asm->OutStreamer->AddComment("DW_RLE_end_of_list"); 2452 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1); 2453 } else { 2454 // Terminate the list with two 0 values. 2455 Asm->OutStreamer->EmitIntValue(0, Size); 2456 Asm->OutStreamer->EmitIntValue(0, Size); 2457 } 2458 } 2459 2460 static void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm, 2461 const DwarfFile &Holder, MCSymbol *TableEnd) { 2462 for (const RangeSpanList &List : Holder.getRangeLists()) 2463 emitRangeList(DD, Asm, List); 2464 2465 if (TableEnd) 2466 Asm->OutStreamer->EmitLabel(TableEnd); 2467 } 2468 2469 /// Emit address ranges into the .debug_ranges section or into the DWARF v5 2470 /// .debug_rnglists section. 2471 void DwarfDebug::emitDebugRanges() { 2472 if (CUMap.empty()) 2473 return; 2474 2475 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2476 2477 if (Holder.getRangeLists().empty()) 2478 return; 2479 2480 assert(useRangesSection()); 2481 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2482 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2483 })); 2484 2485 // Start the dwarf ranges section. 2486 MCSymbol *TableEnd = nullptr; 2487 if (getDwarfVersion() >= 5) { 2488 Asm->OutStreamer->SwitchSection( 2489 Asm->getObjFileLowering().getDwarfRnglistsSection()); 2490 TableEnd = emitRnglistsTableHeader(Asm, Holder); 2491 } else 2492 Asm->OutStreamer->SwitchSection( 2493 Asm->getObjFileLowering().getDwarfRangesSection()); 2494 2495 emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2496 } 2497 2498 void DwarfDebug::emitDebugRangesDWO() { 2499 assert(useSplitDwarf()); 2500 2501 if (CUMap.empty()) 2502 return; 2503 2504 const auto &Holder = InfoHolder; 2505 2506 if (Holder.getRangeLists().empty()) 2507 return; 2508 2509 assert(getDwarfVersion() >= 5); 2510 assert(useRangesSection()); 2511 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2512 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2513 })); 2514 2515 // Start the dwarf ranges section. 2516 Asm->OutStreamer->SwitchSection( 2517 Asm->getObjFileLowering().getDwarfRnglistsDWOSection()); 2518 MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder); 2519 2520 emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2521 } 2522 2523 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 2524 for (auto *MN : Nodes) { 2525 if (auto *M = dyn_cast<DIMacro>(MN)) 2526 emitMacro(*M); 2527 else if (auto *F = dyn_cast<DIMacroFile>(MN)) 2528 emitMacroFile(*F, U); 2529 else 2530 llvm_unreachable("Unexpected DI type!"); 2531 } 2532 } 2533 2534 void DwarfDebug::emitMacro(DIMacro &M) { 2535 Asm->EmitULEB128(M.getMacinfoType()); 2536 Asm->EmitULEB128(M.getLine()); 2537 StringRef Name = M.getName(); 2538 StringRef Value = M.getValue(); 2539 Asm->OutStreamer->EmitBytes(Name); 2540 if (!Value.empty()) { 2541 // There should be one space between macro name and macro value. 2542 Asm->emitInt8(' '); 2543 Asm->OutStreamer->EmitBytes(Value); 2544 } 2545 Asm->emitInt8('\0'); 2546 } 2547 2548 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 2549 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 2550 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file); 2551 Asm->EmitULEB128(F.getLine()); 2552 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile())); 2553 handleMacroNodes(F.getElements(), U); 2554 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file); 2555 } 2556 2557 /// Emit macros into a debug macinfo section. 2558 void DwarfDebug::emitDebugMacinfo() { 2559 if (CUMap.empty()) 2560 return; 2561 2562 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2563 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2564 })) 2565 return; 2566 2567 // Start the dwarf macinfo section. 2568 Asm->OutStreamer->SwitchSection( 2569 Asm->getObjFileLowering().getDwarfMacinfoSection()); 2570 2571 for (const auto &P : CUMap) { 2572 auto &TheCU = *P.second; 2573 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 2574 continue; 2575 auto *SkCU = TheCU.getSkeleton(); 2576 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 2577 auto *CUNode = cast<DICompileUnit>(P.first); 2578 DIMacroNodeArray Macros = CUNode->getMacros(); 2579 if (!Macros.empty()) { 2580 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin()); 2581 handleMacroNodes(Macros, U); 2582 } 2583 } 2584 Asm->OutStreamer->AddComment("End Of Macro List Mark"); 2585 Asm->emitInt8(0); 2586 } 2587 2588 // DWARF5 Experimental Separate Dwarf emitters. 2589 2590 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 2591 std::unique_ptr<DwarfCompileUnit> NewU) { 2592 2593 if (!CompilationDir.empty()) 2594 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2595 2596 addGnuPubAttributes(*NewU, Die); 2597 2598 SkeletonHolder.addUnit(std::move(NewU)); 2599 } 2600 2601 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 2602 2603 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 2604 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 2605 DwarfCompileUnit &NewCU = *OwnedUnit; 2606 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 2607 2608 NewCU.initStmtList(); 2609 2610 if (useSegmentedStringOffsetsTable()) 2611 NewCU.addStringOffsetsStart(); 2612 2613 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 2614 2615 return NewCU; 2616 } 2617 2618 // Emit the .debug_info.dwo section for separated dwarf. This contains the 2619 // compile units that would normally be in debug_info. 2620 void DwarfDebug::emitDebugInfoDWO() { 2621 assert(useSplitDwarf() && "No split dwarf debug info?"); 2622 // Don't emit relocations into the dwo file. 2623 InfoHolder.emitUnits(/* UseOffsets */ true); 2624 } 2625 2626 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2627 // abbreviations for the .debug_info.dwo section. 2628 void DwarfDebug::emitDebugAbbrevDWO() { 2629 assert(useSplitDwarf() && "No split dwarf?"); 2630 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2631 } 2632 2633 void DwarfDebug::emitDebugLineDWO() { 2634 assert(useSplitDwarf() && "No split dwarf?"); 2635 SplitTypeUnitFileTable.Emit( 2636 *Asm->OutStreamer, MCDwarfLineTableParams(), 2637 Asm->getObjFileLowering().getDwarfLineDWOSection()); 2638 } 2639 2640 void DwarfDebug::emitStringOffsetsTableHeaderDWO() { 2641 assert(useSplitDwarf() && "No split dwarf?"); 2642 InfoHolder.getStringPool().emitStringOffsetsTableHeader( 2643 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(), 2644 InfoHolder.getStringOffsetsStartSym()); 2645 } 2646 2647 // Emit the .debug_str.dwo section for separated dwarf. This contains the 2648 // string section and is identical in format to traditional .debug_str 2649 // sections. 2650 void DwarfDebug::emitDebugStrDWO() { 2651 if (useSegmentedStringOffsetsTable()) 2652 emitStringOffsetsTableHeaderDWO(); 2653 assert(useSplitDwarf() && "No split dwarf?"); 2654 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2655 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2656 OffSec, /* UseRelativeOffsets = */ false); 2657 } 2658 2659 // Emit address pool. 2660 void DwarfDebug::emitDebugAddr() { 2661 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 2662 } 2663 2664 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2665 if (!useSplitDwarf()) 2666 return nullptr; 2667 const DICompileUnit *DIUnit = CU.getCUNode(); 2668 SplitTypeUnitFileTable.maybeSetRootFile( 2669 DIUnit->getDirectory(), DIUnit->getFilename(), 2670 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource()); 2671 return &SplitTypeUnitFileTable; 2672 } 2673 2674 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 2675 MD5 Hash; 2676 Hash.update(Identifier); 2677 // ... take the least significant 8 bytes and return those. Our MD5 2678 // implementation always returns its results in little endian, so we actually 2679 // need the "high" word. 2680 MD5::MD5Result Result; 2681 Hash.final(Result); 2682 return Result.high(); 2683 } 2684 2685 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2686 StringRef Identifier, DIE &RefDie, 2687 const DICompositeType *CTy) { 2688 // Fast path if we're building some type units and one has already used the 2689 // address pool we know we're going to throw away all this work anyway, so 2690 // don't bother building dependent types. 2691 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 2692 return; 2693 2694 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 2695 if (!Ins.second) { 2696 CU.addDIETypeSignature(RefDie, Ins.first->second); 2697 return; 2698 } 2699 2700 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 2701 AddrPool.resetUsedFlag(); 2702 2703 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 2704 getDwoLineTable(CU)); 2705 DwarfTypeUnit &NewTU = *OwnedUnit; 2706 DIE &UnitDie = NewTU.getUnitDie(); 2707 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy); 2708 2709 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2710 CU.getLanguage()); 2711 2712 uint64_t Signature = makeTypeSignature(Identifier); 2713 NewTU.setTypeSignature(Signature); 2714 Ins.first->second = Signature; 2715 2716 if (useSplitDwarf()) { 2717 MCSection *Section = 2718 getDwarfVersion() <= 4 2719 ? Asm->getObjFileLowering().getDwarfTypesDWOSection() 2720 : Asm->getObjFileLowering().getDwarfInfoDWOSection(); 2721 NewTU.setSection(Section); 2722 } else { 2723 MCSection *Section = 2724 getDwarfVersion() <= 4 2725 ? Asm->getObjFileLowering().getDwarfTypesSection(Signature) 2726 : Asm->getObjFileLowering().getDwarfInfoSection(Signature); 2727 NewTU.setSection(Section); 2728 // Non-split type units reuse the compile unit's line table. 2729 CU.applyStmtList(UnitDie); 2730 } 2731 2732 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 2733 // units. 2734 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 2735 NewTU.addStringOffsetsStart(); 2736 2737 NewTU.setType(NewTU.createTypeDIE(CTy)); 2738 2739 if (TopLevelType) { 2740 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 2741 TypeUnitsUnderConstruction.clear(); 2742 2743 // Types referencing entries in the address table cannot be placed in type 2744 // units. 2745 if (AddrPool.hasBeenUsed()) { 2746 2747 // Remove all the types built while building this type. 2748 // This is pessimistic as some of these types might not be dependent on 2749 // the type that used an address. 2750 for (const auto &TU : TypeUnitsToAdd) 2751 TypeSignatures.erase(TU.second); 2752 2753 // Construct this type in the CU directly. 2754 // This is inefficient because all the dependent types will be rebuilt 2755 // from scratch, including building them in type units, discovering that 2756 // they depend on addresses, throwing them out and rebuilding them. 2757 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 2758 return; 2759 } 2760 2761 // If the type wasn't dependent on fission addresses, finish adding the type 2762 // and all its dependent types. 2763 for (auto &TU : TypeUnitsToAdd) { 2764 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 2765 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 2766 } 2767 } 2768 CU.addDIETypeSignature(RefDie, Signature); 2769 } 2770 2771 // Add the Name along with its companion DIE to the appropriate accelerator 2772 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for 2773 // AccelTableKind::Apple, we use the table we got as an argument). If 2774 // accelerator tables are disabled, this function does nothing. 2775 template <typename DataT> 2776 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU, 2777 AccelTable<DataT> &AppleAccel, StringRef Name, 2778 const DIE &Die) { 2779 if (getAccelTableKind() == AccelTableKind::None) 2780 return; 2781 2782 if (getAccelTableKind() != AccelTableKind::Apple && 2783 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 2784 return; 2785 2786 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2787 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name); 2788 2789 switch (getAccelTableKind()) { 2790 case AccelTableKind::Apple: 2791 AppleAccel.addName(Ref, Die); 2792 break; 2793 case AccelTableKind::Dwarf: 2794 AccelDebugNames.addName(Ref, Die); 2795 break; 2796 case AccelTableKind::Default: 2797 llvm_unreachable("Default should have already been resolved."); 2798 case AccelTableKind::None: 2799 llvm_unreachable("None handled above"); 2800 } 2801 } 2802 2803 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name, 2804 const DIE &Die) { 2805 addAccelNameImpl(CU, AccelNames, Name, Die); 2806 } 2807 2808 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name, 2809 const DIE &Die) { 2810 // ObjC names go only into the Apple accelerator tables. 2811 if (getAccelTableKind() == AccelTableKind::Apple) 2812 addAccelNameImpl(CU, AccelObjC, Name, Die); 2813 } 2814 2815 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name, 2816 const DIE &Die) { 2817 addAccelNameImpl(CU, AccelNamespace, Name, Die); 2818 } 2819 2820 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name, 2821 const DIE &Die, char Flags) { 2822 addAccelNameImpl(CU, AccelTypes, Name, Die); 2823 } 2824 2825 uint16_t DwarfDebug::getDwarfVersion() const { 2826 return Asm->OutStreamer->getContext().getDwarfVersion(); 2827 } 2828 2829 void DwarfDebug::addSectionLabel(const MCSymbol *Sym) { 2830 SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym)); 2831 } 2832 2833 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) { 2834 return SectionLabels.find(S)->second; 2835 } 2836