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