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