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