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