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 731 // Create the symbols that designates the start of the DWARF v5 range list 732 // and locations list tables. They are located past the table headers. 733 if (getDwarfVersion() >= 5) { 734 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 735 Holder.setRnglistsTableBaseSym( 736 Asm->createTempSymbol("rnglists_table_base")); 737 Holder.setLoclistsTableBaseSym( 738 Asm->createTempSymbol("loclists_table_base")); 739 740 if (useSplitDwarf()) 741 InfoHolder.setRnglistsTableBaseSym( 742 Asm->createTempSymbol("rnglists_dwo_table_base")); 743 } 744 745 // Create the symbol that points to the first entry following the debug 746 // address table (.debug_addr) header. 747 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base")); 748 749 for (DICompileUnit *CUNode : M->debug_compile_units()) { 750 // FIXME: Move local imported entities into a list attached to the 751 // subprogram, then this search won't be needed and a 752 // getImportedEntities().empty() test should go below with the rest. 753 bool HasNonLocalImportedEntities = llvm::any_of( 754 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) { 755 return !isa<DILocalScope>(IE->getScope()); 756 }); 757 758 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() && 759 CUNode->getRetainedTypes().empty() && 760 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty()) 761 continue; 762 763 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode); 764 765 // Global Variables. 766 for (auto *GVE : CUNode->getGlobalVariables()) { 767 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we 768 // already know about the variable and it isn't adding a constant 769 // expression. 770 auto &GVMapEntry = GVMap[GVE->getVariable()]; 771 auto *Expr = GVE->getExpression(); 772 if (!GVMapEntry.size() || (Expr && Expr->isConstant())) 773 GVMapEntry.push_back({nullptr, Expr}); 774 } 775 DenseSet<DIGlobalVariable *> Processed; 776 for (auto *GVE : CUNode->getGlobalVariables()) { 777 DIGlobalVariable *GV = GVE->getVariable(); 778 if (Processed.insert(GV).second) 779 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV])); 780 } 781 782 for (auto *Ty : CUNode->getEnumTypes()) { 783 // The enum types array by design contains pointers to 784 // MDNodes rather than DIRefs. Unique them here. 785 CU.getOrCreateTypeDIE(cast<DIType>(Ty)); 786 } 787 for (auto *Ty : CUNode->getRetainedTypes()) { 788 // The retained types array by design contains pointers to 789 // MDNodes rather than DIRefs. Unique them here. 790 if (DIType *RT = dyn_cast<DIType>(Ty)) 791 // There is no point in force-emitting a forward declaration. 792 CU.getOrCreateTypeDIE(RT); 793 } 794 // Emit imported_modules last so that the relevant context is already 795 // available. 796 for (auto *IE : CUNode->getImportedEntities()) 797 constructAndAddImportedEntityDIE(CU, IE); 798 } 799 } 800 801 void DwarfDebug::finishEntityDefinitions() { 802 for (const auto &Entity : ConcreteEntities) { 803 DIE *Die = Entity->getDIE(); 804 assert(Die); 805 // FIXME: Consider the time-space tradeoff of just storing the unit pointer 806 // in the ConcreteEntities list, rather than looking it up again here. 807 // DIE::getUnit isn't simple - it walks parent pointers, etc. 808 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie()); 809 assert(Unit); 810 Unit->finishEntityDefinition(Entity.get()); 811 } 812 } 813 814 void DwarfDebug::finishSubprogramDefinitions() { 815 for (const DISubprogram *SP : ProcessedSPNodes) { 816 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug); 817 forBothCUs( 818 getOrCreateDwarfCompileUnit(SP->getUnit()), 819 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); }); 820 } 821 } 822 823 void DwarfDebug::finalizeModuleInfo() { 824 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 825 826 finishSubprogramDefinitions(); 827 828 finishEntityDefinitions(); 829 830 // Include the DWO file name in the hash if there's more than one CU. 831 // This handles ThinLTO's situation where imported CUs may very easily be 832 // duplicate with the same CU partially imported into another ThinLTO unit. 833 StringRef DWOName; 834 if (CUMap.size() > 1) 835 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile; 836 837 // Handle anything that needs to be done on a per-unit basis after 838 // all other generation. 839 for (const auto &P : CUMap) { 840 auto &TheCU = *P.second; 841 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 842 continue; 843 // Emit DW_AT_containing_type attribute to connect types with their 844 // vtable holding type. 845 TheCU.constructContainingTypeDIEs(); 846 847 // Add CU specific attributes if we need to add any. 848 // If we're splitting the dwarf out now that we've got the entire 849 // CU then add the dwo id to it. 850 auto *SkCU = TheCU.getSkeleton(); 851 if (useSplitDwarf()) { 852 // Emit a unique identifier for this CU. 853 uint64_t ID = 854 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie()); 855 if (getDwarfVersion() >= 5) { 856 TheCU.setDWOId(ID); 857 SkCU->setDWOId(ID); 858 } else { 859 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 860 dwarf::DW_FORM_data8, ID); 861 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 862 dwarf::DW_FORM_data8, ID); 863 } 864 865 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) { 866 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol(); 867 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base, 868 Sym, Sym); 869 } 870 } 871 872 // If we have code split among multiple sections or non-contiguous 873 // ranges of code then emit a DW_AT_ranges attribute on the unit that will 874 // remain in the .o file, otherwise add a DW_AT_low_pc. 875 // FIXME: We should use ranges allow reordering of code ala 876 // .subsections_via_symbols in mach-o. This would mean turning on 877 // ranges for all subprogram DIEs for mach-o. 878 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 879 880 // We don't keep track of which addresses are used in which CU so this 881 // is a bit pessimistic under LTO. 882 if (!AddrPool.isEmpty()) 883 U.addAddrTableBase(); 884 885 if (unsigned NumRanges = TheCU.getRanges().size()) { 886 if (NumRanges > 1 && useRangesSection()) 887 // A DW_AT_low_pc attribute may also be specified in combination with 888 // DW_AT_ranges to specify the default base address for use in 889 // location lists (see Section 2.6.2) and range lists (see Section 890 // 2.17.3). 891 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0); 892 else 893 U.setBaseAddress(TheCU.getRanges().front().getStart()); 894 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges()); 895 } 896 897 if (getDwarfVersion() >= 5) { 898 if (U.hasRangeLists()) 899 U.addRnglistsBase(); 900 901 if (!DebugLocs.getLists().empty() && !useSplitDwarf()) 902 U.addLoclistsBase(); 903 } 904 905 auto *CUNode = cast<DICompileUnit>(P.first); 906 // If compile Unit has macros, emit "DW_AT_macro_info" attribute. 907 if (CUNode->getMacros()) 908 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info, 909 U.getMacroLabelBegin(), 910 TLOF.getDwarfMacinfoSection()->getBeginSymbol()); 911 } 912 913 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules. 914 for (auto *CUNode : MMI->getModule()->debug_compile_units()) 915 if (CUNode->getDWOId()) 916 getOrCreateDwarfCompileUnit(CUNode); 917 918 // Compute DIE offsets and sizes. 919 InfoHolder.computeSizeAndOffsets(); 920 if (useSplitDwarf()) 921 SkeletonHolder.computeSizeAndOffsets(); 922 } 923 924 // Emit all Dwarf sections that should come after the content. 925 void DwarfDebug::endModule() { 926 assert(CurFn == nullptr); 927 assert(CurMI == nullptr); 928 929 // If we aren't actually generating debug info (check beginModule - 930 // conditionalized on !DisableDebugInfoPrinting and the presence of the 931 // llvm.dbg.cu metadata node) 932 if (!MMI->hasDebugInfo()) 933 return; 934 935 // Finalize the debug info for the module. 936 finalizeModuleInfo(); 937 938 emitDebugStr(); 939 940 if (useSplitDwarf()) 941 emitDebugLocDWO(); 942 else 943 // Emit info into a debug loc section. 944 emitDebugLoc(); 945 946 // Corresponding abbreviations into a abbrev section. 947 emitAbbreviations(); 948 949 // Emit all the DIEs into a debug info section. 950 emitDebugInfo(); 951 952 // Emit info into a debug aranges section. 953 if (GenerateARangeSection) 954 emitDebugARanges(); 955 956 // Emit info into a debug ranges section. 957 emitDebugRanges(); 958 959 // Emit info into a debug macinfo section. 960 emitDebugMacinfo(); 961 962 if (useSplitDwarf()) { 963 emitDebugStrDWO(); 964 emitDebugInfoDWO(); 965 emitDebugAbbrevDWO(); 966 emitDebugLineDWO(); 967 emitDebugRangesDWO(); 968 } 969 970 emitDebugAddr(); 971 972 // Emit info into the dwarf accelerator table sections. 973 switch (getAccelTableKind()) { 974 case AccelTableKind::Apple: 975 emitAccelNames(); 976 emitAccelObjC(); 977 emitAccelNamespaces(); 978 emitAccelTypes(); 979 break; 980 case AccelTableKind::Dwarf: 981 emitAccelDebugNames(); 982 break; 983 case AccelTableKind::None: 984 break; 985 case AccelTableKind::Default: 986 llvm_unreachable("Default should have already been resolved."); 987 } 988 989 // Emit the pubnames and pubtypes sections if requested. 990 emitDebugPubSections(); 991 992 // clean up. 993 // FIXME: AbstractVariables.clear(); 994 } 995 996 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU, 997 const DINode *Node, 998 const MDNode *ScopeNode) { 999 if (CU.getExistingAbstractEntity(Node)) 1000 return; 1001 1002 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope( 1003 cast<DILocalScope>(ScopeNode))); 1004 } 1005 1006 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU, 1007 const DINode *Node, const MDNode *ScopeNode) { 1008 if (CU.getExistingAbstractEntity(Node)) 1009 return; 1010 1011 if (LexicalScope *Scope = 1012 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode))) 1013 CU.createAbstractEntity(Node, Scope); 1014 } 1015 1016 // Collect variable information from side table maintained by MF. 1017 void DwarfDebug::collectVariableInfoFromMFTable( 1018 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) { 1019 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars; 1020 for (const auto &VI : Asm->MF->getVariableDbgInfo()) { 1021 if (!VI.Var) 1022 continue; 1023 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 1024 "Expected inlined-at fields to agree"); 1025 1026 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt()); 1027 Processed.insert(Var); 1028 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 1029 1030 // If variable scope is not found then skip this variable. 1031 if (!Scope) 1032 continue; 1033 1034 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode()); 1035 auto RegVar = llvm::make_unique<DbgVariable>( 1036 cast<DILocalVariable>(Var.first), Var.second); 1037 RegVar->initializeMMI(VI.Expr, VI.Slot); 1038 if (DbgVariable *DbgVar = MFVars.lookup(Var)) 1039 DbgVar->addMMIEntry(*RegVar); 1040 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) { 1041 MFVars.insert({Var, RegVar.get()}); 1042 ConcreteEntities.push_back(std::move(RegVar)); 1043 } 1044 } 1045 } 1046 1047 // Get .debug_loc entry for the instruction range starting at MI. 1048 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) { 1049 const DIExpression *Expr = MI->getDebugExpression(); 1050 assert(MI->getNumOperands() == 4); 1051 if (MI->getOperand(0).isReg()) { 1052 auto RegOp = MI->getOperand(0); 1053 auto Op1 = MI->getOperand(1); 1054 // If the second operand is an immediate, this is a 1055 // register-indirect address. 1056 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"); 1057 MachineLocation MLoc(RegOp.getReg(), Op1.isImm()); 1058 return DebugLocEntry::Value(Expr, MLoc); 1059 } 1060 if (MI->getOperand(0).isImm()) 1061 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm()); 1062 if (MI->getOperand(0).isFPImm()) 1063 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm()); 1064 if (MI->getOperand(0).isCImm()) 1065 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm()); 1066 1067 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!"); 1068 } 1069 1070 /// If this and Next are describing different fragments of the same 1071 /// variable, merge them by appending Next's values to the current 1072 /// list of values. 1073 /// Return true if the merge was successful. 1074 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) { 1075 if (Begin == Next.Begin) { 1076 auto *FirstExpr = cast<DIExpression>(Values[0].Expression); 1077 auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression); 1078 if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment()) 1079 return false; 1080 1081 // We can only merge entries if none of the fragments overlap any others. 1082 // In doing so, we can take advantage of the fact that both lists are 1083 // sorted. 1084 for (unsigned i = 0, j = 0; i < Values.size(); ++i) { 1085 for (; j < Next.Values.size(); ++j) { 1086 int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp( 1087 cast<DIExpression>(Next.Values[j].Expression)); 1088 if (res == 0) // The two expressions overlap, we can't merge. 1089 return false; 1090 // Values[i] is entirely before Next.Values[j], 1091 // so go back to the next entry of Values. 1092 else if (res == -1) 1093 break; 1094 // Next.Values[j] is entirely before Values[i], so go on to the 1095 // next entry of Next.Values. 1096 } 1097 } 1098 1099 addValues(Next.Values); 1100 End = Next.End; 1101 return true; 1102 } 1103 return false; 1104 } 1105 1106 /// Build the location list for all DBG_VALUEs in the function that 1107 /// describe the same variable. If the ranges of several independent 1108 /// fragments of the same variable overlap partially, split them up and 1109 /// combine the ranges. The resulting DebugLocEntries are will have 1110 /// strict monotonically increasing begin addresses and will never 1111 /// overlap. 1112 // 1113 // Input: 1114 // 1115 // Ranges History [var, loc, fragment ofs size] 1116 // 0 | [x, (reg0, fragment 0, 32)] 1117 // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry 1118 // 2 | | ... 1119 // 3 | [clobber reg0] 1120 // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of 1121 // x. 1122 // 1123 // Output: 1124 // 1125 // [0-1] [x, (reg0, fragment 0, 32)] 1126 // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)] 1127 // [3-4] [x, (reg1, fragment 32, 32)] 1128 // [4- ] [x, (mem, fragment 0, 64)] 1129 void 1130 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 1131 const DbgValueHistoryMap::InstrRanges &Ranges) { 1132 SmallVector<DebugLocEntry::Value, 4> OpenRanges; 1133 1134 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 1135 const MachineInstr *Begin = I->first; 1136 const MachineInstr *End = I->second; 1137 assert(Begin->isDebugValue() && "Invalid History entry"); 1138 1139 // Check if a variable is inaccessible in this range. 1140 if (Begin->getNumOperands() > 1 && 1141 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) { 1142 OpenRanges.clear(); 1143 continue; 1144 } 1145 1146 // If this fragment overlaps with any open ranges, truncate them. 1147 const DIExpression *DIExpr = Begin->getDebugExpression(); 1148 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) { 1149 return DIExpr->fragmentsOverlap(R.getExpression()); 1150 }); 1151 OpenRanges.erase(Last, OpenRanges.end()); 1152 1153 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin); 1154 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!"); 1155 1156 const MCSymbol *EndLabel; 1157 if (End != nullptr) 1158 EndLabel = getLabelAfterInsn(End); 1159 else if (std::next(I) == Ranges.end()) 1160 EndLabel = Asm->getFunctionEnd(); 1161 else 1162 EndLabel = getLabelBeforeInsn(std::next(I)->first); 1163 assert(EndLabel && "Forgot label after instruction ending a range!"); 1164 1165 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n"); 1166 1167 auto Value = getDebugLocValue(Begin); 1168 DebugLocEntry Loc(StartLabel, EndLabel, Value); 1169 bool couldMerge = false; 1170 1171 // If this is a fragment, it may belong to the current DebugLocEntry. 1172 if (DIExpr->isFragment()) { 1173 // Add this value to the list of open ranges. 1174 OpenRanges.push_back(Value); 1175 1176 // Attempt to add the fragment to the last entry. 1177 if (!DebugLoc.empty()) 1178 if (DebugLoc.back().MergeValues(Loc)) 1179 couldMerge = true; 1180 } 1181 1182 if (!couldMerge) { 1183 // Need to add a new DebugLocEntry. Add all values from still 1184 // valid non-overlapping fragments. 1185 if (OpenRanges.size()) 1186 Loc.addValues(OpenRanges); 1187 1188 DebugLoc.push_back(std::move(Loc)); 1189 } 1190 1191 // Attempt to coalesce the ranges of two otherwise identical 1192 // DebugLocEntries. 1193 auto CurEntry = DebugLoc.rbegin(); 1194 LLVM_DEBUG({ 1195 dbgs() << CurEntry->getValues().size() << " Values:\n"; 1196 for (auto &Value : CurEntry->getValues()) 1197 Value.dump(); 1198 dbgs() << "-----\n"; 1199 }); 1200 1201 auto PrevEntry = std::next(CurEntry); 1202 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 1203 DebugLoc.pop_back(); 1204 } 1205 } 1206 1207 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU, 1208 LexicalScope &Scope, 1209 const DINode *Node, 1210 const DILocation *Location, 1211 const MCSymbol *Sym) { 1212 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode()); 1213 if (isa<const DILocalVariable>(Node)) { 1214 ConcreteEntities.push_back( 1215 llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node), 1216 Location)); 1217 InfoHolder.addScopeVariable(&Scope, 1218 cast<DbgVariable>(ConcreteEntities.back().get())); 1219 } else if (isa<const DILabel>(Node)) { 1220 ConcreteEntities.push_back( 1221 llvm::make_unique<DbgLabel>(cast<const DILabel>(Node), 1222 Location, Sym)); 1223 InfoHolder.addScopeLabel(&Scope, 1224 cast<DbgLabel>(ConcreteEntities.back().get())); 1225 } 1226 return ConcreteEntities.back().get(); 1227 } 1228 1229 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its 1230 /// enclosing lexical scope. The check ensures there are no other instructions 1231 /// in the same lexical scope preceding the DBG_VALUE and that its range is 1232 /// either open or otherwise rolls off the end of the scope. 1233 static bool validThroughout(LexicalScopes &LScopes, 1234 const MachineInstr *DbgValue, 1235 const MachineInstr *RangeEnd) { 1236 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location"); 1237 auto MBB = DbgValue->getParent(); 1238 auto DL = DbgValue->getDebugLoc(); 1239 auto *LScope = LScopes.findLexicalScope(DL); 1240 // Scope doesn't exist; this is a dead DBG_VALUE. 1241 if (!LScope) 1242 return false; 1243 auto &LSRange = LScope->getRanges(); 1244 if (LSRange.size() == 0) 1245 return false; 1246 1247 // Determine if the DBG_VALUE is valid at the beginning of its lexical block. 1248 const MachineInstr *LScopeBegin = LSRange.front().first; 1249 // Early exit if the lexical scope begins outside of the current block. 1250 if (LScopeBegin->getParent() != MBB) 1251 return false; 1252 MachineBasicBlock::const_reverse_iterator Pred(DbgValue); 1253 for (++Pred; Pred != MBB->rend(); ++Pred) { 1254 if (Pred->getFlag(MachineInstr::FrameSetup)) 1255 break; 1256 auto PredDL = Pred->getDebugLoc(); 1257 if (!PredDL || Pred->isMetaInstruction()) 1258 continue; 1259 // Check whether the instruction preceding the DBG_VALUE is in the same 1260 // (sub)scope as the DBG_VALUE. 1261 if (DL->getScope() == PredDL->getScope()) 1262 return false; 1263 auto *PredScope = LScopes.findLexicalScope(PredDL); 1264 if (!PredScope || LScope->dominates(PredScope)) 1265 return false; 1266 } 1267 1268 // If the range of the DBG_VALUE is open-ended, report success. 1269 if (!RangeEnd) 1270 return true; 1271 1272 // Fail if there are instructions belonging to our scope in another block. 1273 const MachineInstr *LScopeEnd = LSRange.back().second; 1274 if (LScopeEnd->getParent() != MBB) 1275 return false; 1276 1277 // Single, constant DBG_VALUEs in the prologue are promoted to be live 1278 // throughout the function. This is a hack, presumably for DWARF v2 and not 1279 // necessarily correct. It would be much better to use a dbg.declare instead 1280 // if we know the constant is live throughout the scope. 1281 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty()) 1282 return true; 1283 1284 return false; 1285 } 1286 1287 // Find variables for each lexical scope. 1288 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU, 1289 const DISubprogram *SP, 1290 DenseSet<InlinedEntity> &Processed) { 1291 // Grab the variable info that was squirreled away in the MMI side-table. 1292 collectVariableInfoFromMFTable(TheCU, Processed); 1293 1294 for (const auto &I : DbgValues) { 1295 InlinedEntity IV = I.first; 1296 if (Processed.count(IV)) 1297 continue; 1298 1299 // Instruction ranges, specifying where IV is accessible. 1300 const auto &Ranges = I.second; 1301 if (Ranges.empty()) 1302 continue; 1303 1304 LexicalScope *Scope = nullptr; 1305 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first); 1306 if (const DILocation *IA = IV.second) 1307 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA); 1308 else 1309 Scope = LScopes.findLexicalScope(LocalVar->getScope()); 1310 // If variable scope is not found then skip this variable. 1311 if (!Scope) 1312 continue; 1313 1314 Processed.insert(IV); 1315 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU, 1316 *Scope, LocalVar, IV.second)); 1317 1318 const MachineInstr *MInsn = Ranges.front().first; 1319 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1320 1321 // Check if there is a single DBG_VALUE, valid throughout the var's scope. 1322 if (Ranges.size() == 1 && 1323 validThroughout(LScopes, MInsn, Ranges.front().second)) { 1324 RegVar->initializeDbgValue(MInsn); 1325 continue; 1326 } 1327 // Do not emit location lists if .debug_loc secton is disabled. 1328 if (!useLocSection()) 1329 continue; 1330 1331 // Handle multiple DBG_VALUE instructions describing one variable. 1332 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 1333 1334 // Build the location list for this variable. 1335 SmallVector<DebugLocEntry, 8> Entries; 1336 buildLocationList(Entries, Ranges); 1337 1338 // If the variable has a DIBasicType, extract it. Basic types cannot have 1339 // unique identifiers, so don't bother resolving the type with the 1340 // identifier map. 1341 const DIBasicType *BT = dyn_cast<DIBasicType>( 1342 static_cast<const Metadata *>(LocalVar->getType())); 1343 1344 // Finalize the entry by lowering it into a DWARF bytestream. 1345 for (auto &Entry : Entries) 1346 Entry.finalize(*Asm, List, BT); 1347 } 1348 1349 // For each InlinedEntity collected from DBG_LABEL instructions, convert to 1350 // DWARF-related DbgLabel. 1351 for (const auto &I : DbgLabels) { 1352 InlinedEntity IL = I.first; 1353 const MachineInstr *MI = I.second; 1354 if (MI == nullptr) 1355 continue; 1356 1357 LexicalScope *Scope = nullptr; 1358 const DILabel *Label = cast<DILabel>(IL.first); 1359 // Get inlined DILocation if it is inlined label. 1360 if (const DILocation *IA = IL.second) 1361 Scope = LScopes.findInlinedScope(Label->getScope(), IA); 1362 else 1363 Scope = LScopes.findLexicalScope(Label->getScope()); 1364 // If label scope is not found then skip this label. 1365 if (!Scope) 1366 continue; 1367 1368 Processed.insert(IL); 1369 /// At this point, the temporary label is created. 1370 /// Save the temporary label to DbgLabel entity to get the 1371 /// actually address when generating Dwarf DIE. 1372 MCSymbol *Sym = getLabelBeforeInsn(MI); 1373 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym); 1374 } 1375 1376 // Collect info for variables/labels that were optimized out. 1377 for (const DINode *DN : SP->getRetainedNodes()) { 1378 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1379 continue; 1380 LexicalScope *Scope = nullptr; 1381 if (auto *DV = dyn_cast<DILocalVariable>(DN)) { 1382 Scope = LScopes.findLexicalScope(DV->getScope()); 1383 } else if (auto *DL = dyn_cast<DILabel>(DN)) { 1384 Scope = LScopes.findLexicalScope(DL->getScope()); 1385 } 1386 1387 if (Scope) 1388 createConcreteEntity(TheCU, *Scope, DN, nullptr); 1389 } 1390 } 1391 1392 // Process beginning of an instruction. 1393 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1394 DebugHandlerBase::beginInstruction(MI); 1395 assert(CurMI); 1396 1397 const auto *SP = MI->getMF()->getFunction().getSubprogram(); 1398 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1399 return; 1400 1401 // Check if source location changes, but ignore DBG_VALUE and CFI locations. 1402 // If the instruction is part of the function frame setup code, do not emit 1403 // any line record, as there is no correspondence with any user code. 1404 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup)) 1405 return; 1406 const DebugLoc &DL = MI->getDebugLoc(); 1407 // When we emit a line-0 record, we don't update PrevInstLoc; so look at 1408 // the last line number actually emitted, to see if it was line 0. 1409 unsigned LastAsmLine = 1410 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine(); 1411 1412 // Request a label after the call in order to emit AT_return_pc information 1413 // in call site entries. TODO: Add support for targets with delay slots. 1414 if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot()) 1415 requestLabelAfterInsn(MI); 1416 1417 if (DL == PrevInstLoc) { 1418 // If we have an ongoing unspecified location, nothing to do here. 1419 if (!DL) 1420 return; 1421 // We have an explicit location, same as the previous location. 1422 // But we might be coming back to it after a line 0 record. 1423 if (LastAsmLine == 0 && DL.getLine() != 0) { 1424 // Reinstate the source location but not marked as a statement. 1425 const MDNode *Scope = DL.getScope(); 1426 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0); 1427 } 1428 return; 1429 } 1430 1431 if (!DL) { 1432 // We have an unspecified location, which might want to be line 0. 1433 // If we have already emitted a line-0 record, don't repeat it. 1434 if (LastAsmLine == 0) 1435 return; 1436 // If user said Don't Do That, don't do that. 1437 if (UnknownLocations == Disable) 1438 return; 1439 // See if we have a reason to emit a line-0 record now. 1440 // Reasons to emit a line-0 record include: 1441 // - User asked for it (UnknownLocations). 1442 // - Instruction has a label, so it's referenced from somewhere else, 1443 // possibly debug information; we want it to have a source location. 1444 // - Instruction is at the top of a block; we don't want to inherit the 1445 // location from the physically previous (maybe unrelated) block. 1446 if (UnknownLocations == Enable || PrevLabel || 1447 (PrevInstBB && PrevInstBB != MI->getParent())) { 1448 // Preserve the file and column numbers, if we can, to save space in 1449 // the encoded line table. 1450 // Do not update PrevInstLoc, it remembers the last non-0 line. 1451 const MDNode *Scope = nullptr; 1452 unsigned Column = 0; 1453 if (PrevInstLoc) { 1454 Scope = PrevInstLoc.getScope(); 1455 Column = PrevInstLoc.getCol(); 1456 } 1457 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0); 1458 } 1459 return; 1460 } 1461 1462 // We have an explicit location, different from the previous location. 1463 // Don't repeat a line-0 record, but otherwise emit the new location. 1464 // (The new location might be an explicit line 0, which we do emit.) 1465 if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0) 1466 return; 1467 unsigned Flags = 0; 1468 if (DL == PrologEndLoc) { 1469 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT; 1470 PrologEndLoc = DebugLoc(); 1471 } 1472 // If the line changed, we call that a new statement; unless we went to 1473 // line 0 and came back, in which case it is not a new statement. 1474 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine; 1475 if (DL.getLine() && DL.getLine() != OldLine) 1476 Flags |= DWARF2_FLAG_IS_STMT; 1477 1478 const MDNode *Scope = DL.getScope(); 1479 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1480 1481 // If we're not at line 0, remember this location. 1482 if (DL.getLine()) 1483 PrevInstLoc = DL; 1484 } 1485 1486 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1487 // First known non-DBG_VALUE and non-frame setup location marks 1488 // the beginning of the function body. 1489 for (const auto &MBB : *MF) 1490 for (const auto &MI : MBB) 1491 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1492 MI.getDebugLoc()) 1493 return MI.getDebugLoc(); 1494 return DebugLoc(); 1495 } 1496 1497 // Gather pre-function debug information. Assumes being called immediately 1498 // after the function entry point has been emitted. 1499 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) { 1500 CurFn = MF; 1501 1502 auto *SP = MF->getFunction().getSubprogram(); 1503 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode()); 1504 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1505 return; 1506 1507 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 1508 1509 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1510 // belongs to so that we add to the correct per-cu line table in the 1511 // non-asm case. 1512 if (Asm->OutStreamer->hasRawTextSupport()) 1513 // Use a single line table if we are generating assembly. 1514 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1515 else 1516 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID()); 1517 1518 // Record beginning of function. 1519 PrologEndLoc = findPrologueEndLoc(MF); 1520 if (PrologEndLoc) { 1521 // We'd like to list the prologue as "not statements" but GDB behaves 1522 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1523 auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram(); 1524 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT); 1525 } 1526 } 1527 1528 void DwarfDebug::skippedNonDebugFunction() { 1529 // If we don't have a subprogram for this function then there will be a hole 1530 // in the range information. Keep note of this by setting the previously used 1531 // section to nullptr. 1532 PrevCU = nullptr; 1533 CurFn = nullptr; 1534 } 1535 1536 // Gather and emit post-function debug information. 1537 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) { 1538 const DISubprogram *SP = MF->getFunction().getSubprogram(); 1539 1540 assert(CurFn == MF && 1541 "endFunction should be called with the same function as beginFunction"); 1542 1543 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1544 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1545 1546 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1547 assert(!FnScope || SP == FnScope->getScopeNode()); 1548 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit()); 1549 if (TheCU.getCUNode()->isDebugDirectivesOnly()) { 1550 PrevLabel = nullptr; 1551 CurFn = nullptr; 1552 return; 1553 } 1554 1555 DenseSet<InlinedEntity> Processed; 1556 collectEntityInfo(TheCU, SP, Processed); 1557 1558 // Add the range of this function to the list of ranges for the CU. 1559 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd())); 1560 1561 // Under -gmlt, skip building the subprogram if there are no inlined 1562 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram 1563 // is still needed as we need its source location. 1564 if (!TheCU.getCUNode()->getDebugInfoForProfiling() && 1565 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly && 1566 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1567 assert(InfoHolder.getScopeVariables().empty()); 1568 PrevLabel = nullptr; 1569 CurFn = nullptr; 1570 return; 1571 } 1572 1573 #ifndef NDEBUG 1574 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1575 #endif 1576 // Construct abstract scopes. 1577 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1578 auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 1579 for (const DINode *DN : SP->getRetainedNodes()) { 1580 if (!Processed.insert(InlinedEntity(DN, nullptr)).second) 1581 continue; 1582 1583 const MDNode *Scope = nullptr; 1584 if (auto *DV = dyn_cast<DILocalVariable>(DN)) 1585 Scope = DV->getScope(); 1586 else if (auto *DL = dyn_cast<DILabel>(DN)) 1587 Scope = DL->getScope(); 1588 else 1589 llvm_unreachable("Unexpected DI type!"); 1590 1591 // Collect info for variables/labels that were optimized out. 1592 ensureAbstractEntityIsCreated(TheCU, DN, Scope); 1593 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1594 && "ensureAbstractEntityIsCreated inserted abstract scopes"); 1595 } 1596 constructAbstractSubprogramScopeDIE(TheCU, AScope); 1597 } 1598 1599 ProcessedSPNodes.insert(SP); 1600 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope); 1601 if (auto *SkelCU = TheCU.getSkeleton()) 1602 if (!LScopes.getAbstractScopesList().empty() && 1603 TheCU.getCUNode()->getSplitDebugInlining()) 1604 SkelCU->constructSubprogramScopeDIE(SP, FnScope); 1605 1606 // Construct call site entries. 1607 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF); 1608 1609 // Clear debug info 1610 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1611 // DbgVariables except those that are also in AbstractVariables (since they 1612 // can be used cross-function) 1613 InfoHolder.getScopeVariables().clear(); 1614 InfoHolder.getScopeLabels().clear(); 1615 PrevLabel = nullptr; 1616 CurFn = nullptr; 1617 } 1618 1619 // Register a source line with debug info. Returns the unique label that was 1620 // emitted and which provides correspondence to the source line list. 1621 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1622 unsigned Flags) { 1623 StringRef Fn; 1624 unsigned FileNo = 1; 1625 unsigned Discriminator = 0; 1626 if (auto *Scope = cast_or_null<DIScope>(S)) { 1627 Fn = Scope->getFilename(); 1628 if (Line != 0 && getDwarfVersion() >= 4) 1629 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 1630 Discriminator = LBF->getDiscriminator(); 1631 1632 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID(); 1633 FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID]) 1634 .getOrCreateSourceID(Scope->getFile()); 1635 } 1636 Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0, 1637 Discriminator, Fn); 1638 } 1639 1640 //===----------------------------------------------------------------------===// 1641 // Emit Methods 1642 //===----------------------------------------------------------------------===// 1643 1644 // Emit the debug info section. 1645 void DwarfDebug::emitDebugInfo() { 1646 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1647 Holder.emitUnits(/* UseOffsets */ false); 1648 } 1649 1650 // Emit the abbreviation section. 1651 void DwarfDebug::emitAbbreviations() { 1652 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1653 1654 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1655 } 1656 1657 void DwarfDebug::emitStringOffsetsTableHeader() { 1658 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1659 Holder.getStringPool().emitStringOffsetsTableHeader( 1660 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(), 1661 Holder.getStringOffsetsStartSym()); 1662 } 1663 1664 template <typename AccelTableT> 1665 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section, 1666 StringRef TableName) { 1667 Asm->OutStreamer->SwitchSection(Section); 1668 1669 // Emit the full data. 1670 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol()); 1671 } 1672 1673 void DwarfDebug::emitAccelDebugNames() { 1674 // Don't emit anything if we have no compilation units to index. 1675 if (getUnits().empty()) 1676 return; 1677 1678 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits()); 1679 } 1680 1681 // Emit visible names into a hashed accelerator table section. 1682 void DwarfDebug::emitAccelNames() { 1683 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1684 "Names"); 1685 } 1686 1687 // Emit objective C classes and categories into a hashed accelerator table 1688 // section. 1689 void DwarfDebug::emitAccelObjC() { 1690 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1691 "ObjC"); 1692 } 1693 1694 // Emit namespace dies into a hashed accelerator table. 1695 void DwarfDebug::emitAccelNamespaces() { 1696 emitAccel(AccelNamespace, 1697 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1698 "namespac"); 1699 } 1700 1701 // Emit type dies into a hashed accelerator table. 1702 void DwarfDebug::emitAccelTypes() { 1703 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1704 "types"); 1705 } 1706 1707 // Public name handling. 1708 // The format for the various pubnames: 1709 // 1710 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1711 // for the DIE that is named. 1712 // 1713 // gnu pubnames - offset/index value/name tuples where the offset is the offset 1714 // into the CU and the index value is computed according to the type of value 1715 // for the DIE that is named. 1716 // 1717 // For type units the offset is the offset of the skeleton DIE. For split dwarf 1718 // it's the offset within the debug_info/debug_types dwo section, however, the 1719 // reference in the pubname header doesn't change. 1720 1721 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 1722 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1723 const DIE *Die) { 1724 // Entities that ended up only in a Type Unit reference the CU instead (since 1725 // the pub entry has offsets within the CU there's no real offset that can be 1726 // provided anyway). As it happens all such entities (namespaces and types, 1727 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out 1728 // not to be true it would be necessary to persist this information from the 1729 // point at which the entry is added to the index data structure - since by 1730 // the time the index is built from that, the original type/namespace DIE in a 1731 // type unit has already been destroyed so it can't be queried for properties 1732 // like tag, etc. 1733 if (Die->getTag() == dwarf::DW_TAG_compile_unit) 1734 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, 1735 dwarf::GIEL_EXTERNAL); 1736 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1737 1738 // We could have a specification DIE that has our most of our knowledge, 1739 // look for that now. 1740 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 1741 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 1742 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1743 Linkage = dwarf::GIEL_EXTERNAL; 1744 } else if (Die->findAttribute(dwarf::DW_AT_external)) 1745 Linkage = dwarf::GIEL_EXTERNAL; 1746 1747 switch (Die->getTag()) { 1748 case dwarf::DW_TAG_class_type: 1749 case dwarf::DW_TAG_structure_type: 1750 case dwarf::DW_TAG_union_type: 1751 case dwarf::DW_TAG_enumeration_type: 1752 return dwarf::PubIndexEntryDescriptor( 1753 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1754 ? dwarf::GIEL_STATIC 1755 : dwarf::GIEL_EXTERNAL); 1756 case dwarf::DW_TAG_typedef: 1757 case dwarf::DW_TAG_base_type: 1758 case dwarf::DW_TAG_subrange_type: 1759 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1760 case dwarf::DW_TAG_namespace: 1761 return dwarf::GIEK_TYPE; 1762 case dwarf::DW_TAG_subprogram: 1763 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1764 case dwarf::DW_TAG_variable: 1765 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1766 case dwarf::DW_TAG_enumerator: 1767 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1768 dwarf::GIEL_STATIC); 1769 default: 1770 return dwarf::GIEK_NONE; 1771 } 1772 } 1773 1774 /// emitDebugPubSections - Emit visible names and types into debug pubnames and 1775 /// pubtypes sections. 1776 void DwarfDebug::emitDebugPubSections() { 1777 for (const auto &NU : CUMap) { 1778 DwarfCompileUnit *TheU = NU.second; 1779 if (!TheU->hasDwarfPubSections()) 1780 continue; 1781 1782 bool GnuStyle = TheU->getCUNode()->getNameTableKind() == 1783 DICompileUnit::DebugNameTableKind::GNU; 1784 1785 Asm->OutStreamer->SwitchSection( 1786 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1787 : Asm->getObjFileLowering().getDwarfPubNamesSection()); 1788 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames()); 1789 1790 Asm->OutStreamer->SwitchSection( 1791 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1792 : Asm->getObjFileLowering().getDwarfPubTypesSection()); 1793 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes()); 1794 } 1795 } 1796 1797 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) { 1798 if (useSectionsAsReferences()) 1799 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(), 1800 CU.getDebugSectionOffset()); 1801 else 1802 Asm->emitDwarfSymbolReference(CU.getLabelBegin()); 1803 } 1804 1805 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name, 1806 DwarfCompileUnit *TheU, 1807 const StringMap<const DIE *> &Globals) { 1808 if (auto *Skeleton = TheU->getSkeleton()) 1809 TheU = Skeleton; 1810 1811 // Emit the header. 1812 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info"); 1813 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 1814 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 1815 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1816 1817 Asm->OutStreamer->EmitLabel(BeginLabel); 1818 1819 Asm->OutStreamer->AddComment("DWARF Version"); 1820 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); 1821 1822 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 1823 emitSectionReference(*TheU); 1824 1825 Asm->OutStreamer->AddComment("Compilation Unit Length"); 1826 Asm->emitInt32(TheU->getLength()); 1827 1828 // Emit the pubnames for this compilation unit. 1829 for (const auto &GI : Globals) { 1830 const char *Name = GI.getKeyData(); 1831 const DIE *Entity = GI.second; 1832 1833 Asm->OutStreamer->AddComment("DIE offset"); 1834 Asm->emitInt32(Entity->getOffset()); 1835 1836 if (GnuStyle) { 1837 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1838 Asm->OutStreamer->AddComment( 1839 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " + 1840 dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1841 Asm->emitInt8(Desc.toBits()); 1842 } 1843 1844 Asm->OutStreamer->AddComment("External Name"); 1845 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1846 } 1847 1848 Asm->OutStreamer->AddComment("End Mark"); 1849 Asm->emitInt32(0); 1850 Asm->OutStreamer->EmitLabel(EndLabel); 1851 } 1852 1853 /// Emit null-terminated strings into a debug str section. 1854 void DwarfDebug::emitDebugStr() { 1855 MCSection *StringOffsetsSection = nullptr; 1856 if (useSegmentedStringOffsetsTable()) { 1857 emitStringOffsetsTableHeader(); 1858 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection(); 1859 } 1860 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1861 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(), 1862 StringOffsetsSection, /* UseRelativeOffsets = */ true); 1863 } 1864 1865 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 1866 const DebugLocStream::Entry &Entry) { 1867 auto &&Comments = DebugLocs.getComments(Entry); 1868 auto Comment = Comments.begin(); 1869 auto End = Comments.end(); 1870 for (uint8_t Byte : DebugLocs.getBytes(Entry)) 1871 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : ""); 1872 } 1873 1874 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 1875 const DebugLocEntry::Value &Value, 1876 DwarfExpression &DwarfExpr) { 1877 auto *DIExpr = Value.getExpression(); 1878 DIExpressionCursor ExprCursor(DIExpr); 1879 DwarfExpr.addFragmentOffset(DIExpr); 1880 // Regular entry. 1881 if (Value.isInt()) { 1882 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 1883 BT->getEncoding() == dwarf::DW_ATE_signed_char)) 1884 DwarfExpr.addSignedConstant(Value.getInt()); 1885 else 1886 DwarfExpr.addUnsignedConstant(Value.getInt()); 1887 } else if (Value.isLocation()) { 1888 MachineLocation Location = Value.getLoc(); 1889 if (Location.isIndirect()) 1890 DwarfExpr.setMemoryLocationKind(); 1891 DIExpressionCursor Cursor(DIExpr); 1892 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo(); 1893 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1894 return; 1895 return DwarfExpr.addExpression(std::move(Cursor)); 1896 } else if (Value.isConstantFP()) { 1897 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt(); 1898 DwarfExpr.addUnsignedConstant(RawBytes); 1899 } 1900 DwarfExpr.addExpression(std::move(ExprCursor)); 1901 } 1902 1903 void DebugLocEntry::finalize(const AsmPrinter &AP, 1904 DebugLocStream::ListBuilder &List, 1905 const DIBasicType *BT) { 1906 DebugLocStream::EntryBuilder Entry(List, Begin, End); 1907 BufferByteStreamer Streamer = Entry.getStreamer(); 1908 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer); 1909 const DebugLocEntry::Value &Value = Values[0]; 1910 if (Value.isFragment()) { 1911 // Emit all fragments that belong to the same variable and range. 1912 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) { 1913 return P.isFragment(); 1914 }) && "all values are expected to be fragments"); 1915 assert(std::is_sorted(Values.begin(), Values.end()) && 1916 "fragments are expected to be sorted"); 1917 1918 for (auto Fragment : Values) 1919 emitDebugLocValue(AP, BT, Fragment, DwarfExpr); 1920 1921 } else { 1922 assert(Values.size() == 1 && "only fragments may have >1 value"); 1923 emitDebugLocValue(AP, BT, Value, DwarfExpr); 1924 } 1925 DwarfExpr.finalize(); 1926 } 1927 1928 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) { 1929 // Emit the size. 1930 Asm->OutStreamer->AddComment("Loc expr size"); 1931 Asm->emitInt16(DebugLocs.getBytes(Entry).size()); 1932 1933 // Emit the entry. 1934 APByteStreamer Streamer(*Asm); 1935 emitDebugLocEntry(Streamer, Entry); 1936 } 1937 1938 // Emit the common part of the DWARF 5 range/locations list tables header. 1939 static void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder, 1940 MCSymbol *TableStart, 1941 MCSymbol *TableEnd) { 1942 // Build the table header, which starts with the length field. 1943 Asm->OutStreamer->AddComment("Length"); 1944 Asm->EmitLabelDifference(TableEnd, TableStart, 4); 1945 Asm->OutStreamer->EmitLabel(TableStart); 1946 // Version number (DWARF v5 and later). 1947 Asm->OutStreamer->AddComment("Version"); 1948 Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion()); 1949 // Address size. 1950 Asm->OutStreamer->AddComment("Address size"); 1951 Asm->emitInt8(Asm->MAI->getCodePointerSize()); 1952 // Segment selector size. 1953 Asm->OutStreamer->AddComment("Segment selector size"); 1954 Asm->emitInt8(0); 1955 } 1956 1957 // Emit the header of a DWARF 5 range list table list table. Returns the symbol 1958 // that designates the end of the table for the caller to emit when the table is 1959 // complete. 1960 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm, 1961 const DwarfFile &Holder) { 1962 MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start"); 1963 MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end"); 1964 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 1965 1966 Asm->OutStreamer->AddComment("Offset entry count"); 1967 Asm->emitInt32(Holder.getRangeLists().size()); 1968 Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym()); 1969 1970 for (const RangeSpanList &List : Holder.getRangeLists()) 1971 Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(), 1972 4); 1973 1974 return TableEnd; 1975 } 1976 1977 // Emit the header of a DWARF 5 locations list table. Returns the symbol that 1978 // designates the end of the table for the caller to emit when the table is 1979 // complete. 1980 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm, 1981 const DwarfFile &Holder) { 1982 MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start"); 1983 MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end"); 1984 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd); 1985 1986 // FIXME: Generate the offsets table and use DW_FORM_loclistx with the 1987 // DW_AT_loclists_base attribute. Until then set the number of offsets to 0. 1988 Asm->OutStreamer->AddComment("Offset entry count"); 1989 Asm->emitInt32(0); 1990 Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym()); 1991 1992 return TableEnd; 1993 } 1994 1995 // Emit locations into the .debug_loc/.debug_rnglists section. 1996 void DwarfDebug::emitDebugLoc() { 1997 if (DebugLocs.getLists().empty()) 1998 return; 1999 2000 bool IsLocLists = getDwarfVersion() >= 5; 2001 MCSymbol *TableEnd = nullptr; 2002 if (IsLocLists) { 2003 Asm->OutStreamer->SwitchSection( 2004 Asm->getObjFileLowering().getDwarfLoclistsSection()); 2005 TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder 2006 : InfoHolder); 2007 } else { 2008 Asm->OutStreamer->SwitchSection( 2009 Asm->getObjFileLowering().getDwarfLocSection()); 2010 } 2011 2012 unsigned char Size = Asm->MAI->getCodePointerSize(); 2013 for (const auto &List : DebugLocs.getLists()) { 2014 Asm->OutStreamer->EmitLabel(List.Label); 2015 2016 const DwarfCompileUnit *CU = List.CU; 2017 const MCSymbol *Base = CU->getBaseAddress(); 2018 for (const auto &Entry : DebugLocs.getEntries(List)) { 2019 if (Base) { 2020 // Set up the range. This range is relative to the entry point of the 2021 // compile unit. This is a hard coded 0 for low_pc when we're emitting 2022 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 2023 if (IsLocLists) { 2024 Asm->OutStreamer->AddComment("DW_LLE_offset_pair"); 2025 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1); 2026 Asm->OutStreamer->AddComment(" starting offset"); 2027 Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base); 2028 Asm->OutStreamer->AddComment(" ending offset"); 2029 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base); 2030 } else { 2031 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 2032 Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 2033 } 2034 2035 emitDebugLocEntryLocation(Entry); 2036 continue; 2037 } 2038 2039 // We have no base address. 2040 if (IsLocLists) { 2041 // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or 2042 // DW_LLE_startx_length in case if there is only a single range. 2043 // That should reduce the size of the debug data emited. 2044 // For now just use the DW_LLE_startx_length for all cases. 2045 Asm->OutStreamer->AddComment("DW_LLE_startx_length"); 2046 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2047 Asm->OutStreamer->AddComment(" start idx"); 2048 Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym)); 2049 Asm->OutStreamer->AddComment(" length"); 2050 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym); 2051 } else { 2052 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 2053 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 2054 } 2055 2056 emitDebugLocEntryLocation(Entry); 2057 } 2058 2059 if (IsLocLists) { 2060 // .debug_loclists section ends with DW_LLE_end_of_list. 2061 Asm->OutStreamer->AddComment("DW_LLE_end_of_list"); 2062 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1); 2063 } else { 2064 // Terminate the .debug_loc list with two 0 values. 2065 Asm->OutStreamer->EmitIntValue(0, Size); 2066 Asm->OutStreamer->EmitIntValue(0, Size); 2067 } 2068 } 2069 2070 if (TableEnd) 2071 Asm->OutStreamer->EmitLabel(TableEnd); 2072 } 2073 2074 void DwarfDebug::emitDebugLocDWO() { 2075 Asm->OutStreamer->SwitchSection( 2076 Asm->getObjFileLowering().getDwarfLocDWOSection()); 2077 for (const auto &List : DebugLocs.getLists()) { 2078 Asm->OutStreamer->EmitLabel(List.Label); 2079 for (const auto &Entry : DebugLocs.getEntries(List)) { 2080 // GDB only supports startx_length in pre-standard split-DWARF. 2081 // (in v5 standard loclists, it currently* /only/ supports base_address + 2082 // offset_pair, so the implementations can't really share much since they 2083 // need to use different representations) 2084 // * as of October 2018, at least 2085 // Ideally/in v5, this could use SectionLabels to reuse existing addresses 2086 // in the address pool to minimize object size/relocations. 2087 Asm->emitInt8(dwarf::DW_LLE_startx_length); 2088 unsigned idx = AddrPool.getIndex(Entry.BeginSym); 2089 Asm->EmitULEB128(idx); 2090 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 2091 2092 emitDebugLocEntryLocation(Entry); 2093 } 2094 Asm->emitInt8(dwarf::DW_LLE_end_of_list); 2095 } 2096 } 2097 2098 struct ArangeSpan { 2099 const MCSymbol *Start, *End; 2100 }; 2101 2102 // Emit a debug aranges section, containing a CU lookup for any 2103 // address we can tie back to a CU. 2104 void DwarfDebug::emitDebugARanges() { 2105 // Provides a unique id per text section. 2106 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 2107 2108 // Filter labels by section. 2109 for (const SymbolCU &SCU : ArangeLabels) { 2110 if (SCU.Sym->isInSection()) { 2111 // Make a note of this symbol and it's section. 2112 MCSection *Section = &SCU.Sym->getSection(); 2113 if (!Section->getKind().isMetadata()) 2114 SectionMap[Section].push_back(SCU); 2115 } else { 2116 // Some symbols (e.g. common/bss on mach-o) can have no section but still 2117 // appear in the output. This sucks as we rely on sections to build 2118 // arange spans. We can do it without, but it's icky. 2119 SectionMap[nullptr].push_back(SCU); 2120 } 2121 } 2122 2123 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 2124 2125 for (auto &I : SectionMap) { 2126 MCSection *Section = I.first; 2127 SmallVector<SymbolCU, 8> &List = I.second; 2128 if (List.size() < 1) 2129 continue; 2130 2131 // If we have no section (e.g. common), just write out 2132 // individual spans for each symbol. 2133 if (!Section) { 2134 for (const SymbolCU &Cur : List) { 2135 ArangeSpan Span; 2136 Span.Start = Cur.Sym; 2137 Span.End = nullptr; 2138 assert(Cur.CU); 2139 Spans[Cur.CU].push_back(Span); 2140 } 2141 continue; 2142 } 2143 2144 // Sort the symbols by offset within the section. 2145 std::stable_sort( 2146 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) { 2147 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 2148 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 2149 2150 // Symbols with no order assigned should be placed at the end. 2151 // (e.g. section end labels) 2152 if (IA == 0) 2153 return false; 2154 if (IB == 0) 2155 return true; 2156 return IA < IB; 2157 }); 2158 2159 // Insert a final terminator. 2160 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section))); 2161 2162 // Build spans between each label. 2163 const MCSymbol *StartSym = List[0].Sym; 2164 for (size_t n = 1, e = List.size(); n < e; n++) { 2165 const SymbolCU &Prev = List[n - 1]; 2166 const SymbolCU &Cur = List[n]; 2167 2168 // Try and build the longest span we can within the same CU. 2169 if (Cur.CU != Prev.CU) { 2170 ArangeSpan Span; 2171 Span.Start = StartSym; 2172 Span.End = Cur.Sym; 2173 assert(Prev.CU); 2174 Spans[Prev.CU].push_back(Span); 2175 StartSym = Cur.Sym; 2176 } 2177 } 2178 } 2179 2180 // Start the dwarf aranges section. 2181 Asm->OutStreamer->SwitchSection( 2182 Asm->getObjFileLowering().getDwarfARangesSection()); 2183 2184 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 2185 2186 // Build a list of CUs used. 2187 std::vector<DwarfCompileUnit *> CUs; 2188 for (const auto &it : Spans) { 2189 DwarfCompileUnit *CU = it.first; 2190 CUs.push_back(CU); 2191 } 2192 2193 // Sort the CU list (again, to ensure consistent output order). 2194 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 2195 return A->getUniqueID() < B->getUniqueID(); 2196 }); 2197 2198 // Emit an arange table for each CU we used. 2199 for (DwarfCompileUnit *CU : CUs) { 2200 std::vector<ArangeSpan> &List = Spans[CU]; 2201 2202 // Describe the skeleton CU's offset and length, not the dwo file's. 2203 if (auto *Skel = CU->getSkeleton()) 2204 CU = Skel; 2205 2206 // Emit size of content not including length itself. 2207 unsigned ContentSize = 2208 sizeof(int16_t) + // DWARF ARange version number 2209 sizeof(int32_t) + // Offset of CU in the .debug_info section 2210 sizeof(int8_t) + // Pointer Size (in bytes) 2211 sizeof(int8_t); // Segment Size (in bytes) 2212 2213 unsigned TupleSize = PtrSize * 2; 2214 2215 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 2216 unsigned Padding = 2217 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 2218 2219 ContentSize += Padding; 2220 ContentSize += (List.size() + 1) * TupleSize; 2221 2222 // For each compile unit, write the list of spans it covers. 2223 Asm->OutStreamer->AddComment("Length of ARange Set"); 2224 Asm->emitInt32(ContentSize); 2225 Asm->OutStreamer->AddComment("DWARF Arange version number"); 2226 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); 2227 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 2228 emitSectionReference(*CU); 2229 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 2230 Asm->emitInt8(PtrSize); 2231 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 2232 Asm->emitInt8(0); 2233 2234 Asm->OutStreamer->emitFill(Padding, 0xff); 2235 2236 for (const ArangeSpan &Span : List) { 2237 Asm->EmitLabelReference(Span.Start, PtrSize); 2238 2239 // Calculate the size as being from the span start to it's end. 2240 if (Span.End) { 2241 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 2242 } else { 2243 // For symbols without an end marker (e.g. common), we 2244 // write a single arange entry containing just that one symbol. 2245 uint64_t Size = SymSize[Span.Start]; 2246 if (Size == 0) 2247 Size = 1; 2248 2249 Asm->OutStreamer->EmitIntValue(Size, PtrSize); 2250 } 2251 } 2252 2253 Asm->OutStreamer->AddComment("ARange terminator"); 2254 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2255 Asm->OutStreamer->EmitIntValue(0, PtrSize); 2256 } 2257 } 2258 2259 /// Emit a single range list. We handle both DWARF v5 and earlier. 2260 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, 2261 const RangeSpanList &List) { 2262 2263 auto DwarfVersion = DD.getDwarfVersion(); 2264 // Emit our symbol so we can find the beginning of the range. 2265 Asm->OutStreamer->EmitLabel(List.getSym()); 2266 // Gather all the ranges that apply to the same section so they can share 2267 // a base address entry. 2268 MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges; 2269 // Size for our labels. 2270 auto Size = Asm->MAI->getCodePointerSize(); 2271 2272 for (const RangeSpan &Range : List.getRanges()) 2273 SectionRanges[&Range.getStart()->getSection()].push_back(&Range); 2274 2275 const MCSymbol *CUBase = List.getBaseAddress(); 2276 bool BaseIsSet = false; 2277 for (const auto &P : SectionRanges) { 2278 // Don't bother with a base address entry if there's only one range in 2279 // this section in this range list - for example ranges for a CU will 2280 // usually consist of single regions from each of many sections 2281 // (-ffunction-sections, or just C++ inline functions) except under LTO 2282 // or optnone where there may be holes in a single CU's section 2283 // contributions. 2284 auto *Base = CUBase; 2285 if (!Base && (P.second.size() > 1 || DwarfVersion < 5) && 2286 (UseDwarfRangesBaseAddressSpecifier || DwarfVersion >= 5)) { 2287 BaseIsSet = true; 2288 // FIXME/use care: This may not be a useful base address if it's not 2289 // the lowest address/range in this object. 2290 Base = P.second.front()->getStart(); 2291 if (DwarfVersion >= 5) { 2292 Base = DD.getSectionLabel(&Base->getSection()); 2293 Asm->OutStreamer->AddComment("DW_RLE_base_addressx"); 2294 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1); 2295 Asm->OutStreamer->AddComment(" base address index"); 2296 Asm->EmitULEB128(DD.getAddressPool().getIndex(Base)); 2297 } else { 2298 Asm->OutStreamer->EmitIntValue(-1, Size); 2299 Asm->OutStreamer->AddComment(" base address"); 2300 Asm->OutStreamer->EmitSymbolValue(Base, Size); 2301 } 2302 } else if (BaseIsSet && DwarfVersion < 5) { 2303 BaseIsSet = false; 2304 assert(!Base); 2305 Asm->OutStreamer->EmitIntValue(-1, Size); 2306 Asm->OutStreamer->EmitIntValue(0, Size); 2307 } 2308 2309 for (const auto *RS : P.second) { 2310 const MCSymbol *Begin = RS->getStart(); 2311 const MCSymbol *End = RS->getEnd(); 2312 assert(Begin && "Range without a begin symbol?"); 2313 assert(End && "Range without an end symbol?"); 2314 if (Base) { 2315 if (DwarfVersion >= 5) { 2316 // Emit DW_RLE_offset_pair when we have a base. 2317 Asm->OutStreamer->AddComment("DW_RLE_offset_pair"); 2318 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1); 2319 Asm->OutStreamer->AddComment(" starting offset"); 2320 Asm->EmitLabelDifferenceAsULEB128(Begin, Base); 2321 Asm->OutStreamer->AddComment(" ending offset"); 2322 Asm->EmitLabelDifferenceAsULEB128(End, Base); 2323 } else { 2324 Asm->EmitLabelDifference(Begin, Base, Size); 2325 Asm->EmitLabelDifference(End, Base, Size); 2326 } 2327 } else if (DwarfVersion >= 5) { 2328 Asm->OutStreamer->AddComment("DW_RLE_startx_length"); 2329 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1); 2330 Asm->OutStreamer->AddComment(" start index"); 2331 Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin)); 2332 Asm->OutStreamer->AddComment(" length"); 2333 Asm->EmitLabelDifferenceAsULEB128(End, Begin); 2334 } else { 2335 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 2336 Asm->OutStreamer->EmitSymbolValue(End, Size); 2337 } 2338 } 2339 } 2340 if (DwarfVersion >= 5) { 2341 Asm->OutStreamer->AddComment("DW_RLE_end_of_list"); 2342 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1); 2343 } else { 2344 // Terminate the list with two 0 values. 2345 Asm->OutStreamer->EmitIntValue(0, Size); 2346 Asm->OutStreamer->EmitIntValue(0, Size); 2347 } 2348 } 2349 2350 void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm, 2351 const DwarfFile &Holder, MCSymbol *TableEnd) { 2352 for (const RangeSpanList &List : Holder.getRangeLists()) 2353 emitRangeList(DD, Asm, List); 2354 2355 if (TableEnd) 2356 Asm->OutStreamer->EmitLabel(TableEnd); 2357 } 2358 2359 /// Emit address ranges into the .debug_ranges section or into the DWARF v5 2360 /// .debug_rnglists section. 2361 void DwarfDebug::emitDebugRanges() { 2362 if (CUMap.empty()) 2363 return; 2364 2365 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2366 2367 if (Holder.getRangeLists().empty()) 2368 return; 2369 2370 assert(useRangesSection()); 2371 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2372 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2373 })); 2374 2375 // Start the dwarf ranges section. 2376 MCSymbol *TableEnd = nullptr; 2377 if (getDwarfVersion() >= 5) { 2378 Asm->OutStreamer->SwitchSection( 2379 Asm->getObjFileLowering().getDwarfRnglistsSection()); 2380 TableEnd = emitRnglistsTableHeader(Asm, Holder); 2381 } else 2382 Asm->OutStreamer->SwitchSection( 2383 Asm->getObjFileLowering().getDwarfRangesSection()); 2384 2385 emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2386 } 2387 2388 void DwarfDebug::emitDebugRangesDWO() { 2389 assert(useSplitDwarf()); 2390 2391 if (CUMap.empty()) 2392 return; 2393 2394 const auto &Holder = InfoHolder; 2395 2396 if (Holder.getRangeLists().empty()) 2397 return; 2398 2399 assert(getDwarfVersion() >= 5); 2400 assert(useRangesSection()); 2401 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2402 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2403 })); 2404 2405 // Start the dwarf ranges section. 2406 Asm->OutStreamer->SwitchSection( 2407 Asm->getObjFileLowering().getDwarfRnglistsDWOSection()); 2408 MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder); 2409 2410 emitDebugRangesImpl(*this, Asm, Holder, TableEnd); 2411 } 2412 2413 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 2414 for (auto *MN : Nodes) { 2415 if (auto *M = dyn_cast<DIMacro>(MN)) 2416 emitMacro(*M); 2417 else if (auto *F = dyn_cast<DIMacroFile>(MN)) 2418 emitMacroFile(*F, U); 2419 else 2420 llvm_unreachable("Unexpected DI type!"); 2421 } 2422 } 2423 2424 void DwarfDebug::emitMacro(DIMacro &M) { 2425 Asm->EmitULEB128(M.getMacinfoType()); 2426 Asm->EmitULEB128(M.getLine()); 2427 StringRef Name = M.getName(); 2428 StringRef Value = M.getValue(); 2429 Asm->OutStreamer->EmitBytes(Name); 2430 if (!Value.empty()) { 2431 // There should be one space between macro name and macro value. 2432 Asm->emitInt8(' '); 2433 Asm->OutStreamer->EmitBytes(Value); 2434 } 2435 Asm->emitInt8('\0'); 2436 } 2437 2438 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 2439 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 2440 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file); 2441 Asm->EmitULEB128(F.getLine()); 2442 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile())); 2443 handleMacroNodes(F.getElements(), U); 2444 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file); 2445 } 2446 2447 /// Emit macros into a debug macinfo section. 2448 void DwarfDebug::emitDebugMacinfo() { 2449 if (CUMap.empty()) 2450 return; 2451 2452 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { 2453 return Pair.second->getCUNode()->isDebugDirectivesOnly(); 2454 })) 2455 return; 2456 2457 // Start the dwarf macinfo section. 2458 Asm->OutStreamer->SwitchSection( 2459 Asm->getObjFileLowering().getDwarfMacinfoSection()); 2460 2461 for (const auto &P : CUMap) { 2462 auto &TheCU = *P.second; 2463 if (TheCU.getCUNode()->isDebugDirectivesOnly()) 2464 continue; 2465 auto *SkCU = TheCU.getSkeleton(); 2466 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 2467 auto *CUNode = cast<DICompileUnit>(P.first); 2468 DIMacroNodeArray Macros = CUNode->getMacros(); 2469 if (!Macros.empty()) { 2470 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin()); 2471 handleMacroNodes(Macros, U); 2472 } 2473 } 2474 Asm->OutStreamer->AddComment("End Of Macro List Mark"); 2475 Asm->emitInt8(0); 2476 } 2477 2478 // DWARF5 Experimental Separate Dwarf emitters. 2479 2480 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 2481 std::unique_ptr<DwarfCompileUnit> NewU) { 2482 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name, 2483 Asm->TM.Options.MCOptions.SplitDwarfFile); 2484 2485 if (!CompilationDir.empty()) 2486 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2487 2488 addGnuPubAttributes(*NewU, Die); 2489 2490 SkeletonHolder.addUnit(std::move(NewU)); 2491 } 2492 2493 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 2494 2495 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 2496 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 2497 DwarfCompileUnit &NewCU = *OwnedUnit; 2498 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 2499 2500 NewCU.initStmtList(); 2501 2502 if (useSegmentedStringOffsetsTable()) 2503 NewCU.addStringOffsetsStart(); 2504 2505 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 2506 2507 return NewCU; 2508 } 2509 2510 // Emit the .debug_info.dwo section for separated dwarf. This contains the 2511 // compile units that would normally be in debug_info. 2512 void DwarfDebug::emitDebugInfoDWO() { 2513 assert(useSplitDwarf() && "No split dwarf debug info?"); 2514 // Don't emit relocations into the dwo file. 2515 InfoHolder.emitUnits(/* UseOffsets */ true); 2516 } 2517 2518 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2519 // abbreviations for the .debug_info.dwo section. 2520 void DwarfDebug::emitDebugAbbrevDWO() { 2521 assert(useSplitDwarf() && "No split dwarf?"); 2522 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2523 } 2524 2525 void DwarfDebug::emitDebugLineDWO() { 2526 assert(useSplitDwarf() && "No split dwarf?"); 2527 SplitTypeUnitFileTable.Emit( 2528 *Asm->OutStreamer, MCDwarfLineTableParams(), 2529 Asm->getObjFileLowering().getDwarfLineDWOSection()); 2530 } 2531 2532 void DwarfDebug::emitStringOffsetsTableHeaderDWO() { 2533 assert(useSplitDwarf() && "No split dwarf?"); 2534 InfoHolder.getStringPool().emitStringOffsetsTableHeader( 2535 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(), 2536 InfoHolder.getStringOffsetsStartSym()); 2537 } 2538 2539 // Emit the .debug_str.dwo section for separated dwarf. This contains the 2540 // string section and is identical in format to traditional .debug_str 2541 // sections. 2542 void DwarfDebug::emitDebugStrDWO() { 2543 if (useSegmentedStringOffsetsTable()) 2544 emitStringOffsetsTableHeaderDWO(); 2545 assert(useSplitDwarf() && "No split dwarf?"); 2546 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2547 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2548 OffSec, /* UseRelativeOffsets = */ false); 2549 } 2550 2551 // Emit address pool. 2552 void DwarfDebug::emitDebugAddr() { 2553 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 2554 } 2555 2556 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2557 if (!useSplitDwarf()) 2558 return nullptr; 2559 const DICompileUnit *DIUnit = CU.getCUNode(); 2560 SplitTypeUnitFileTable.maybeSetRootFile( 2561 DIUnit->getDirectory(), DIUnit->getFilename(), 2562 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource()); 2563 return &SplitTypeUnitFileTable; 2564 } 2565 2566 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 2567 MD5 Hash; 2568 Hash.update(Identifier); 2569 // ... take the least significant 8 bytes and return those. Our MD5 2570 // implementation always returns its results in little endian, so we actually 2571 // need the "high" word. 2572 MD5::MD5Result Result; 2573 Hash.final(Result); 2574 return Result.high(); 2575 } 2576 2577 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2578 StringRef Identifier, DIE &RefDie, 2579 const DICompositeType *CTy) { 2580 // Fast path if we're building some type units and one has already used the 2581 // address pool we know we're going to throw away all this work anyway, so 2582 // don't bother building dependent types. 2583 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 2584 return; 2585 2586 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 2587 if (!Ins.second) { 2588 CU.addDIETypeSignature(RefDie, Ins.first->second); 2589 return; 2590 } 2591 2592 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 2593 AddrPool.resetUsedFlag(); 2594 2595 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 2596 getDwoLineTable(CU)); 2597 DwarfTypeUnit &NewTU = *OwnedUnit; 2598 DIE &UnitDie = NewTU.getUnitDie(); 2599 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy); 2600 2601 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2602 CU.getLanguage()); 2603 2604 uint64_t Signature = makeTypeSignature(Identifier); 2605 NewTU.setTypeSignature(Signature); 2606 Ins.first->second = Signature; 2607 2608 if (useSplitDwarf()) 2609 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection()); 2610 else { 2611 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature)); 2612 // Non-split type units reuse the compile unit's line table. 2613 CU.applyStmtList(UnitDie); 2614 } 2615 2616 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 2617 // units. 2618 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 2619 NewTU.addStringOffsetsStart(); 2620 2621 NewTU.setType(NewTU.createTypeDIE(CTy)); 2622 2623 if (TopLevelType) { 2624 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 2625 TypeUnitsUnderConstruction.clear(); 2626 2627 // Types referencing entries in the address table cannot be placed in type 2628 // units. 2629 if (AddrPool.hasBeenUsed()) { 2630 2631 // Remove all the types built while building this type. 2632 // This is pessimistic as some of these types might not be dependent on 2633 // the type that used an address. 2634 for (const auto &TU : TypeUnitsToAdd) 2635 TypeSignatures.erase(TU.second); 2636 2637 // Construct this type in the CU directly. 2638 // This is inefficient because all the dependent types will be rebuilt 2639 // from scratch, including building them in type units, discovering that 2640 // they depend on addresses, throwing them out and rebuilding them. 2641 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 2642 return; 2643 } 2644 2645 // If the type wasn't dependent on fission addresses, finish adding the type 2646 // and all its dependent types. 2647 for (auto &TU : TypeUnitsToAdd) { 2648 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 2649 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 2650 } 2651 } 2652 CU.addDIETypeSignature(RefDie, Signature); 2653 } 2654 2655 // Add the Name along with its companion DIE to the appropriate accelerator 2656 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for 2657 // AccelTableKind::Apple, we use the table we got as an argument). If 2658 // accelerator tables are disabled, this function does nothing. 2659 template <typename DataT> 2660 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU, 2661 AccelTable<DataT> &AppleAccel, StringRef Name, 2662 const DIE &Die) { 2663 if (getAccelTableKind() == AccelTableKind::None) 2664 return; 2665 2666 if (getAccelTableKind() != AccelTableKind::Apple && 2667 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None) 2668 return; 2669 2670 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2671 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name); 2672 2673 switch (getAccelTableKind()) { 2674 case AccelTableKind::Apple: 2675 AppleAccel.addName(Ref, Die); 2676 break; 2677 case AccelTableKind::Dwarf: 2678 AccelDebugNames.addName(Ref, Die); 2679 break; 2680 case AccelTableKind::Default: 2681 llvm_unreachable("Default should have already been resolved."); 2682 case AccelTableKind::None: 2683 llvm_unreachable("None handled above"); 2684 } 2685 } 2686 2687 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name, 2688 const DIE &Die) { 2689 addAccelNameImpl(CU, AccelNames, Name, Die); 2690 } 2691 2692 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name, 2693 const DIE &Die) { 2694 // ObjC names go only into the Apple accelerator tables. 2695 if (getAccelTableKind() == AccelTableKind::Apple) 2696 addAccelNameImpl(CU, AccelObjC, Name, Die); 2697 } 2698 2699 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name, 2700 const DIE &Die) { 2701 addAccelNameImpl(CU, AccelNamespace, Name, Die); 2702 } 2703 2704 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name, 2705 const DIE &Die, char Flags) { 2706 addAccelNameImpl(CU, AccelTypes, Name, Die); 2707 } 2708 2709 uint16_t DwarfDebug::getDwarfVersion() const { 2710 return Asm->OutStreamer->getContext().getDwarfVersion(); 2711 } 2712 2713 void DwarfDebug::addSectionLabel(const MCSymbol *Sym) { 2714 SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym)); 2715 } 2716 2717 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) { 2718 return SectionLabels.find(S)->second; 2719 } 2720