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