1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains support for writing dwarf debug info into asm files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "DwarfDebug.h" 15 #include "ByteStreamer.h" 16 #include "DIEHash.h" 17 #include "DebugLocEntry.h" 18 #include "DebugLocStream.h" 19 #include "DwarfCompileUnit.h" 20 #include "DwarfExpression.h" 21 #include "DwarfFile.h" 22 #include "DwarfUnit.h" 23 #include "llvm/ADT/APInt.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/DenseSet.h" 26 #include "llvm/ADT/MapVector.h" 27 #include "llvm/ADT/STLExtras.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/StringRef.h" 30 #include "llvm/ADT/Triple.h" 31 #include "llvm/ADT/Twine.h" 32 #include "llvm/BinaryFormat/Dwarf.h" 33 #include "llvm/CodeGen/AccelTable.h" 34 #include "llvm/CodeGen/AsmPrinter.h" 35 #include "llvm/CodeGen/DIE.h" 36 #include "llvm/CodeGen/LexicalScopes.h" 37 #include "llvm/CodeGen/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineInstr.h" 40 #include "llvm/CodeGen/MachineModuleInfo.h" 41 #include "llvm/CodeGen/MachineOperand.h" 42 #include "llvm/CodeGen/TargetRegisterInfo.h" 43 #include "llvm/CodeGen/TargetSubtargetInfo.h" 44 #include "llvm/IR/Constants.h" 45 #include "llvm/IR/DebugInfoMetadata.h" 46 #include "llvm/IR/DebugLoc.h" 47 #include "llvm/IR/Function.h" 48 #include "llvm/IR/GlobalVariable.h" 49 #include "llvm/IR/Module.h" 50 #include "llvm/MC/MCAsmInfo.h" 51 #include "llvm/MC/MCContext.h" 52 #include "llvm/MC/MCDwarf.h" 53 #include "llvm/MC/MCSection.h" 54 #include "llvm/MC/MCStreamer.h" 55 #include "llvm/MC/MCSymbol.h" 56 #include "llvm/MC/MCTargetOptions.h" 57 #include "llvm/MC/MachineLocation.h" 58 #include "llvm/MC/SectionKind.h" 59 #include "llvm/Pass.h" 60 #include "llvm/Support/Casting.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/MD5.h" 65 #include "llvm/Support/MathExtras.h" 66 #include "llvm/Support/Timer.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Target/TargetLoweringObjectFile.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include "llvm/Target/TargetOptions.h" 71 #include <algorithm> 72 #include <cassert> 73 #include <cstddef> 74 #include <cstdint> 75 #include <iterator> 76 #include <string> 77 #include <utility> 78 #include <vector> 79 80 using namespace llvm; 81 82 #define DEBUG_TYPE "dwarfdebug" 83 84 static cl::opt<bool> 85 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, 86 cl::desc("Disable debug info printing")); 87 88 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier( 89 "use-dwarf-ranges-base-address-specifier", cl::Hidden, 90 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false)); 91 92 static cl::opt<bool> GenerateARangeSection("generate-arange-section", 93 cl::Hidden, 94 cl::desc("Generate dwarf aranges"), 95 cl::init(false)); 96 97 static cl::opt<bool> SplitDwarfCrossCuReferences( 98 "split-dwarf-cross-cu-references", cl::Hidden, 99 cl::desc("Enable cross-cu references in DWO files"), cl::init(false)); 100 101 enum DefaultOnOff { Default, Enable, Disable }; 102 103 static cl::opt<DefaultOnOff> UnknownLocations( 104 "use-unknown-locations", cl::Hidden, 105 cl::desc("Make an absence of debug location information explicit."), 106 cl::values(clEnumVal(Default, "At top of block or after label"), 107 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")), 108 cl::init(Default)); 109 110 static cl::opt<AccelTableKind> AccelTables( 111 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), 112 cl::values(clEnumValN(AccelTableKind::Default, "Default", 113 "Default for platform"), 114 clEnumValN(AccelTableKind::None, "Disable", "Disabled."), 115 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), 116 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), 117 cl::init(AccelTableKind::Default)); 118 119 static cl::opt<DefaultOnOff> 120 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden, 121 cl::desc("Use inlined strings rather than string section."), 122 cl::values(clEnumVal(Default, "Default for platform"), 123 clEnumVal(Enable, "Enabled"), 124 clEnumVal(Disable, "Disabled")), 125 cl::init(Default)); 126 127 static cl::opt<bool> 128 NoDwarfPubSections("no-dwarf-pub-sections", cl::Hidden, 129 cl::desc("Disable emission of DWARF pub sections."), 130 cl::init(false)); 131 132 static cl::opt<bool> 133 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, 134 cl::desc("Disable emission .debug_ranges section."), 135 cl::init(false)); 136 137 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences( 138 "dwarf-sections-as-references", cl::Hidden, 139 cl::desc("Use sections+offset as references rather than labels."), 140 cl::values(clEnumVal(Default, "Default for platform"), 141 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), 142 cl::init(Default)); 143 144 enum LinkageNameOption { 145 DefaultLinkageNames, 146 AllLinkageNames, 147 AbstractLinkageNames 148 }; 149 150 static cl::opt<LinkageNameOption> 151 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden, 152 cl::desc("Which DWARF linkage-name attributes to emit."), 153 cl::values(clEnumValN(DefaultLinkageNames, "Default", 154 "Default for platform"), 155 clEnumValN(AllLinkageNames, "All", "All"), 156 clEnumValN(AbstractLinkageNames, "Abstract", 157 "Abstract subprograms")), 158 cl::init(DefaultLinkageNames)); 159 160 static const char *const DWARFGroupName = "dwarf"; 161 static const char *const DWARFGroupDescription = "DWARF Emission"; 162 static const char *const DbgTimerName = "writer"; 163 static const char *const DbgTimerDescription = "DWARF Debug Writer"; 164 165 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) { 166 BS.EmitInt8( 167 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op) 168 : dwarf::OperationEncodingString(Op)); 169 } 170 171 void DebugLocDwarfExpression::emitSigned(int64_t Value) { 172 BS.EmitSLEB128(Value, Twine(Value)); 173 } 174 175 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) { 176 BS.EmitULEB128(Value, Twine(Value)); 177 } 178 179 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI, 180 unsigned MachineReg) { 181 // This information is not available while emitting .debug_loc entries. 182 return false; 183 } 184 185 bool DbgVariable::isBlockByrefVariable() const { 186 assert(Var && "Invalid complex DbgVariable!"); 187 return Var->getType().resolve()->isBlockByrefStruct(); 188 } 189 190 const DIType *DbgVariable::getType() const { 191 DIType *Ty = Var->getType().resolve(); 192 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 193 // addresses instead. 194 if (Ty->isBlockByrefStruct()) { 195 /* Byref variables, in Blocks, are declared by the programmer as 196 "SomeType VarName;", but the compiler creates a 197 __Block_byref_x_VarName struct, and gives the variable VarName 198 either the struct, or a pointer to the struct, as its type. This 199 is necessary for various behind-the-scenes things the compiler 200 needs to do with by-reference variables in blocks. 201 202 However, as far as the original *programmer* is concerned, the 203 variable should still have type 'SomeType', as originally declared. 204 205 The following function dives into the __Block_byref_x_VarName 206 struct to find the original type of the variable. This will be 207 passed back to the code generating the type for the Debug 208 Information Entry for the variable 'VarName'. 'VarName' will then 209 have the original type 'SomeType' in its debug information. 210 211 The original type 'SomeType' will be the type of the field named 212 'VarName' inside the __Block_byref_x_VarName struct. 213 214 NOTE: In order for this to not completely fail on the debugger 215 side, the Debug Information Entry for the variable VarName needs to 216 have a DW_AT_location that tells the debugger how to unwind through 217 the pointers and __Block_byref_x_VarName struct to find the actual 218 value of the variable. The function addBlockByrefType does this. */ 219 DIType *subType = Ty; 220 uint16_t tag = Ty->getTag(); 221 222 if (tag == dwarf::DW_TAG_pointer_type) 223 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType()); 224 225 auto Elements = cast<DICompositeType>(subType)->getElements(); 226 for (unsigned i = 0, N = Elements.size(); i < N; ++i) { 227 auto *DT = cast<DIDerivedType>(Elements[i]); 228 if (getName() == DT->getName()) 229 return resolve(DT->getBaseType()); 230 } 231 } 232 return Ty; 233 } 234 235 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const { 236 if (FrameIndexExprs.size() == 1) 237 return FrameIndexExprs; 238 239 assert(llvm::all_of(FrameIndexExprs, 240 [](const FrameIndexExpr &A) { 241 return A.Expr->isFragment(); 242 }) && 243 "multiple FI expressions without DW_OP_LLVM_fragment"); 244 llvm::sort(FrameIndexExprs.begin(), FrameIndexExprs.end(), 245 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool { 246 return A.Expr->getFragmentInfo()->OffsetInBits < 247 B.Expr->getFragmentInfo()->OffsetInBits; 248 }); 249 250 return FrameIndexExprs; 251 } 252 253 void DbgVariable::addMMIEntry(const DbgVariable &V) { 254 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry"); 255 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry"); 256 assert(V.Var == Var && "conflicting variable"); 257 assert(V.IA == IA && "conflicting inlined-at location"); 258 259 assert(!FrameIndexExprs.empty() && "Expected an MMI entry"); 260 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry"); 261 262 // FIXME: This logic should not be necessary anymore, as we now have proper 263 // deduplication. However, without it, we currently run into the assertion 264 // below, which means that we are likely dealing with broken input, i.e. two 265 // non-fragment entries for the same variable at different frame indices. 266 if (FrameIndexExprs.size()) { 267 auto *Expr = FrameIndexExprs.back().Expr; 268 if (!Expr || !Expr->isFragment()) 269 return; 270 } 271 272 for (const auto &FIE : V.FrameIndexExprs) 273 // Ignore duplicate entries. 274 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) { 275 return FIE.FI == Other.FI && FIE.Expr == Other.Expr; 276 })) 277 FrameIndexExprs.push_back(FIE); 278 279 assert((FrameIndexExprs.size() == 1 || 280 llvm::all_of(FrameIndexExprs, 281 [](FrameIndexExpr &FIE) { 282 return FIE.Expr && FIE.Expr->isFragment(); 283 })) && 284 "conflicting locations for variable"); 285 } 286 287 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 288 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()), 289 InfoHolder(A, "info_string", DIEValueAllocator), 290 SkeletonHolder(A, "skel_string", DIEValueAllocator), 291 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) { 292 const Triple &TT = Asm->TM.getTargetTriple(); 293 294 // Make sure we know our "debugger tuning." The target option takes 295 // precedence; fall back to triple-based defaults. 296 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default) 297 DebuggerTuning = Asm->TM.Options.DebuggerTuning; 298 else if (IsDarwin) 299 DebuggerTuning = DebuggerKind::LLDB; 300 else if (TT.isPS4CPU()) 301 DebuggerTuning = DebuggerKind::SCE; 302 else 303 DebuggerTuning = DebuggerKind::GDB; 304 305 // Turn on accelerator tables by default, if tuning for LLDB and the target is 306 // supported. 307 if (AccelTables == AccelTableKind::Default) { 308 if (tuneForLLDB() && A->TM.getTargetTriple().isOSBinFormatMachO()) 309 TheAccelTableKind = AccelTableKind::Apple; 310 else 311 TheAccelTableKind = AccelTableKind::None; 312 } else 313 TheAccelTableKind = AccelTables; 314 315 UseInlineStrings = DwarfInlinedStrings == Enable; 316 HasAppleExtensionAttributes = tuneForLLDB(); 317 318 // Handle split DWARF. 319 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty(); 320 321 // SCE defaults to linkage names only for abstract subprograms. 322 if (DwarfLinkageNames == DefaultLinkageNames) 323 UseAllLinkageNames = !tuneForSCE(); 324 else 325 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames; 326 327 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion; 328 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber 329 : MMI->getModule()->getDwarfVersion(); 330 // Use dwarf 4 by default if nothing is requested. 331 DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION; 332 333 UsePubSections = !NoDwarfPubSections; 334 UseRangesSection = !NoDwarfRangesSection; 335 336 // Use sections as references. 337 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable; 338 339 // Work around a GDB bug. GDB doesn't support the standard opcode; 340 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which 341 // is defined as of DWARF 3. 342 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented 343 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616 344 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3; 345 346 // GDB does not fully support the DWARF 4 representation for bitfields. 347 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB(); 348 349 // The DWARF v5 string offsets table has - possibly shared - contributions 350 // from each compile and type unit each preceded by a header. The string 351 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses 352 // a monolithic string offsets table without any header. 353 UseSegmentedStringOffsetsTable = DwarfVersion >= 5; 354 355 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion); 356 } 357 358 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h. 359 DwarfDebug::~DwarfDebug() = default; 360 361 static bool isObjCClass(StringRef Name) { 362 return Name.startswith("+") || Name.startswith("-"); 363 } 364 365 static bool hasObjCCategory(StringRef Name) { 366 if (!isObjCClass(Name)) 367 return false; 368 369 return Name.find(") ") != StringRef::npos; 370 } 371 372 static void getObjCClassCategory(StringRef In, StringRef &Class, 373 StringRef &Category) { 374 if (!hasObjCCategory(In)) { 375 Class = In.slice(In.find('[') + 1, In.find(' ')); 376 Category = ""; 377 return; 378 } 379 380 Class = In.slice(In.find('[') + 1, In.find('(')); 381 Category = In.slice(In.find('[') + 1, In.find(' ')); 382 } 383 384 static StringRef getObjCMethodName(StringRef In) { 385 return In.slice(In.find(' ') + 1, In.find(']')); 386 } 387 388 // Add the various names to the Dwarf accelerator table names. 389 void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) { 390 if (!SP->isDefinition()) 391 return; 392 393 if (SP->getName() != "") 394 addAccelName(SP->getName(), Die); 395 396 // If the linkage name is different than the name, go ahead and output that as 397 // well into the name table. Only do that if we are going to actually emit 398 // that name. 399 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() && 400 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP))) 401 addAccelName(SP->getLinkageName(), Die); 402 403 // If this is an Objective-C selector name add it to the ObjC accelerator 404 // too. 405 if (isObjCClass(SP->getName())) { 406 StringRef Class, Category; 407 getObjCClassCategory(SP->getName(), Class, Category); 408 addAccelObjC(Class, Die); 409 if (Category != "") 410 addAccelObjC(Category, Die); 411 // Also add the base method name to the name table. 412 addAccelName(getObjCMethodName(SP->getName()), Die); 413 } 414 } 415 416 /// Check whether we should create a DIE for the given Scope, return true 417 /// if we don't create a DIE (the corresponding DIE is null). 418 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) { 419 if (Scope->isAbstractScope()) 420 return false; 421 422 // We don't create a DIE if there is no Range. 423 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges(); 424 if (Ranges.empty()) 425 return true; 426 427 if (Ranges.size() > 1) 428 return false; 429 430 // We don't create a DIE if we have a single Range and the end label 431 // is null. 432 return !getLabelAfterInsn(Ranges.front().second); 433 } 434 435 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) { 436 F(CU); 437 if (auto *SkelCU = CU.getSkeleton()) 438 if (CU.getCUNode()->getSplitDebugInlining()) 439 F(*SkelCU); 440 } 441 442 bool DwarfDebug::shareAcrossDWOCUs() const { 443 return SplitDwarfCrossCuReferences; 444 } 445 446 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, 447 LexicalScope *Scope) { 448 assert(Scope && Scope->getScopeNode()); 449 assert(Scope->isAbstractScope()); 450 assert(!Scope->getInlinedAt()); 451 452 auto *SP = cast<DISubprogram>(Scope->getScopeNode()); 453 454 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram 455 // was inlined from another compile unit. 456 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining()) 457 // Avoid building the original CU if it won't be used 458 SrcCU.constructAbstractSubprogramScopeDIE(Scope); 459 else { 460 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 461 if (auto *SkelCU = CU.getSkeleton()) { 462 (shareAcrossDWOCUs() ? CU : SrcCU) 463 .constructAbstractSubprogramScopeDIE(Scope); 464 if (CU.getCUNode()->getSplitDebugInlining()) 465 SkelCU->constructAbstractSubprogramScopeDIE(Scope); 466 } else 467 CU.constructAbstractSubprogramScopeDIE(Scope); 468 } 469 } 470 471 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const { 472 if (!U.hasDwarfPubSections()) 473 return; 474 475 U.addFlag(D, dwarf::DW_AT_GNU_pubnames); 476 } 477 478 // Create new DwarfCompileUnit for the given metadata node with tag 479 // DW_TAG_compile_unit. 480 DwarfCompileUnit & 481 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) { 482 if (auto *CU = CUMap.lookup(DIUnit)) 483 return *CU; 484 StringRef FN = DIUnit->getFilename(); 485 CompilationDir = DIUnit->getDirectory(); 486 487 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 488 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder); 489 DwarfCompileUnit &NewCU = *OwnedUnit; 490 DIE &Die = NewCU.getUnitDie(); 491 InfoHolder.addUnit(std::move(OwnedUnit)); 492 if (useSplitDwarf()) { 493 NewCU.setSkeleton(constructSkeletonCU(NewCU)); 494 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name, 495 Asm->TM.Options.MCOptions.SplitDwarfFile); 496 } 497 498 for (auto *IE : DIUnit->getImportedEntities()) 499 NewCU.addImportedEntity(IE); 500 501 // LTO with assembly output shares a single line table amongst multiple CUs. 502 // To avoid the compilation directory being ambiguous, let the line table 503 // explicitly describe the directory of all files, never relying on the 504 // compilation directory. 505 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU) 506 Asm->OutStreamer->emitDwarfFile0Directive( 507 CompilationDir, FN, NewCU.getMD5AsBytes(DIUnit->getFile()), 508 DIUnit->getSource(), NewCU.getUniqueID()); 509 510 StringRef Producer = DIUnit->getProducer(); 511 StringRef Flags = DIUnit->getFlags(); 512 if (!Flags.empty()) { 513 std::string ProducerWithFlags = Producer.str() + " " + Flags.str(); 514 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags); 515 } else 516 NewCU.addString(Die, dwarf::DW_AT_producer, Producer); 517 518 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 519 DIUnit->getSourceLanguage()); 520 NewCU.addString(Die, dwarf::DW_AT_name, FN); 521 522 // Add DW_str_offsets_base to the unit DIE, except for split units. 523 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 524 NewCU.addStringOffsetsStart(); 525 526 if (!useSplitDwarf()) { 527 NewCU.initStmtList(); 528 529 // If we're using split dwarf the compilation dir is going to be in the 530 // skeleton CU and so we don't need to duplicate it here. 531 if (!CompilationDir.empty()) 532 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 533 534 addGnuPubAttributes(NewCU, Die); 535 } 536 537 if (useAppleExtensionAttributes()) { 538 if (DIUnit->isOptimized()) 539 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized); 540 541 StringRef Flags = DIUnit->getFlags(); 542 if (!Flags.empty()) 543 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 544 545 if (unsigned RVer = DIUnit->getRuntimeVersion()) 546 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 547 dwarf::DW_FORM_data1, RVer); 548 } 549 550 if (useSplitDwarf()) 551 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection()); 552 else 553 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 554 555 if (DIUnit->getDWOId()) { 556 // This CU is either a clang module DWO or a skeleton CU. 557 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 558 DIUnit->getDWOId()); 559 if (!DIUnit->getSplitDebugFilename().empty()) 560 // This is a prefabricated skeleton CU. 561 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name, 562 DIUnit->getSplitDebugFilename()); 563 } 564 565 CUMap.insert({DIUnit, &NewCU}); 566 CUDieMap.insert({&Die, &NewCU}); 567 return NewCU; 568 } 569 570 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU, 571 const DIImportedEntity *N) { 572 if (isa<DILocalScope>(N->getScope())) 573 return; 574 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope())) 575 D->addChild(TheCU.constructImportedEntityDIE(N)); 576 } 577 578 /// Sort and unique GVEs by comparing their fragment offset. 579 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> & 580 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) { 581 llvm::sort(GVEs.begin(), GVEs.end(), 582 [](DwarfCompileUnit::GlobalExpr A, 583 DwarfCompileUnit::GlobalExpr B) { 584 // Sort order: first null exprs, then exprs without fragment 585 // info, then sort by fragment offset in bits. 586 // FIXME: Come up with a more comprehensive comparator so 587 // the sorting isn't non-deterministic, and so the following 588 // std::unique call works correctly. 589 if (!A.Expr || !B.Expr) 590 return !!B.Expr; 591 auto FragmentA = A.Expr->getFragmentInfo(); 592 auto FragmentB = B.Expr->getFragmentInfo(); 593 if (!FragmentA || !FragmentB) 594 return !!FragmentB; 595 return FragmentA->OffsetInBits < FragmentB->OffsetInBits; 596 }); 597 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(), 598 [](DwarfCompileUnit::GlobalExpr A, 599 DwarfCompileUnit::GlobalExpr B) { 600 return A.Expr == B.Expr; 601 }), 602 GVEs.end()); 603 return GVEs; 604 } 605 606 // Emit all Dwarf sections that should come prior to the content. Create 607 // global DIEs and emit initial debug info sections. This is invoked by 608 // the target AsmPrinter. 609 void DwarfDebug::beginModule() { 610 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName, 611 DWARFGroupDescription, TimePassesIsEnabled); 612 if (DisableDebugInfoPrinting) 613 return; 614 615 const Module *M = MMI->getModule(); 616 617 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(), 618 M->debug_compile_units_end()); 619 // Tell MMI whether we have debug info. 620 MMI->setDebugInfoAvailability(NumDebugCUs > 0); 621 SingleCU = NumDebugCUs == 1; 622 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>> 623 GVMap; 624 for (const GlobalVariable &Global : M->globals()) { 625 SmallVector<DIGlobalVariableExpression *, 1> GVs; 626 Global.getDebugInfo(GVs); 627 for (auto *GVE : GVs) 628 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()}); 629 } 630 631 // Create the symbol that designates the start of the unit's contribution 632 // to the string offsets table. In a split DWARF scenario, only the skeleton 633 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol). 634 if (useSegmentedStringOffsetsTable()) 635 (useSplitDwarf() ? SkeletonHolder : InfoHolder) 636 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base")); 637 638 for (DICompileUnit *CUNode : M->debug_compile_units()) { 639 // FIXME: Move local imported entities into a list attached to the 640 // subprogram, then this search won't be needed and a 641 // getImportedEntities().empty() test should go below with the rest. 642 bool HasNonLocalImportedEntities = llvm::any_of( 643 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) { 644 return !isa<DILocalScope>(IE->getScope()); 645 }); 646 647 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() && 648 CUNode->getRetainedTypes().empty() && 649 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty()) 650 continue; 651 652 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode); 653 654 // Global Variables. 655 for (auto *GVE : CUNode->getGlobalVariables()) { 656 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we 657 // already know about the variable and it isn't adding a constant 658 // expression. 659 auto &GVMapEntry = GVMap[GVE->getVariable()]; 660 auto *Expr = GVE->getExpression(); 661 if (!GVMapEntry.size() || (Expr && Expr->isConstant())) 662 GVMapEntry.push_back({nullptr, Expr}); 663 } 664 DenseSet<DIGlobalVariable *> Processed; 665 for (auto *GVE : CUNode->getGlobalVariables()) { 666 DIGlobalVariable *GV = GVE->getVariable(); 667 if (Processed.insert(GV).second) 668 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV])); 669 } 670 671 for (auto *Ty : CUNode->getEnumTypes()) { 672 // The enum types array by design contains pointers to 673 // MDNodes rather than DIRefs. Unique them here. 674 CU.getOrCreateTypeDIE(cast<DIType>(Ty)); 675 } 676 for (auto *Ty : CUNode->getRetainedTypes()) { 677 // The retained types array by design contains pointers to 678 // MDNodes rather than DIRefs. Unique them here. 679 if (DIType *RT = dyn_cast<DIType>(Ty)) 680 // There is no point in force-emitting a forward declaration. 681 CU.getOrCreateTypeDIE(RT); 682 } 683 // Emit imported_modules last so that the relevant context is already 684 // available. 685 for (auto *IE : CUNode->getImportedEntities()) 686 constructAndAddImportedEntityDIE(CU, IE); 687 } 688 } 689 690 void DwarfDebug::finishVariableDefinitions() { 691 for (const auto &Var : ConcreteVariables) { 692 DIE *VariableDie = Var->getDIE(); 693 assert(VariableDie); 694 // FIXME: Consider the time-space tradeoff of just storing the unit pointer 695 // in the ConcreteVariables list, rather than looking it up again here. 696 // DIE::getUnit isn't simple - it walks parent pointers, etc. 697 DwarfCompileUnit *Unit = CUDieMap.lookup(VariableDie->getUnitDie()); 698 assert(Unit); 699 Unit->finishVariableDefinition(*Var); 700 } 701 } 702 703 void DwarfDebug::finishSubprogramDefinitions() { 704 for (const DISubprogram *SP : ProcessedSPNodes) { 705 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug); 706 forBothCUs( 707 getOrCreateDwarfCompileUnit(SP->getUnit()), 708 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); }); 709 } 710 } 711 712 void DwarfDebug::finalizeModuleInfo() { 713 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 714 715 finishSubprogramDefinitions(); 716 717 finishVariableDefinitions(); 718 719 // Include the DWO file name in the hash if there's more than one CU. 720 // This handles ThinLTO's situation where imported CUs may very easily be 721 // duplicate with the same CU partially imported into another ThinLTO unit. 722 StringRef DWOName; 723 if (CUMap.size() > 1) 724 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile; 725 726 // Handle anything that needs to be done on a per-unit basis after 727 // all other generation. 728 for (const auto &P : CUMap) { 729 auto &TheCU = *P.second; 730 // Emit DW_AT_containing_type attribute to connect types with their 731 // vtable holding type. 732 TheCU.constructContainingTypeDIEs(); 733 734 // Add CU specific attributes if we need to add any. 735 // If we're splitting the dwarf out now that we've got the entire 736 // CU then add the dwo id to it. 737 auto *SkCU = TheCU.getSkeleton(); 738 if (useSplitDwarf()) { 739 // Emit a unique identifier for this CU. 740 uint64_t ID = 741 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie()); 742 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 743 dwarf::DW_FORM_data8, ID); 744 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 745 dwarf::DW_FORM_data8, ID); 746 747 // We don't keep track of which addresses are used in which CU so this 748 // is a bit pessimistic under LTO. 749 if (!AddrPool.isEmpty()) { 750 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol(); 751 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base, 752 Sym, Sym); 753 } 754 if (!SkCU->getRangeLists().empty()) { 755 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol(); 756 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base, 757 Sym, Sym); 758 } 759 } 760 761 // If we have code split among multiple sections or non-contiguous 762 // ranges of code then emit a DW_AT_ranges attribute on the unit that will 763 // remain in the .o file, otherwise add a DW_AT_low_pc. 764 // FIXME: We should use ranges allow reordering of code ala 765 // .subsections_via_symbols in mach-o. This would mean turning on 766 // ranges for all subprogram DIEs for mach-o. 767 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 768 if (unsigned NumRanges = TheCU.getRanges().size()) { 769 if (NumRanges > 1 && useRangesSection()) 770 // A DW_AT_low_pc attribute may also be specified in combination with 771 // DW_AT_ranges to specify the default base address for use in 772 // location lists (see Section 2.6.2) and range lists (see Section 773 // 2.17.3). 774 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0); 775 else 776 U.setBaseAddress(TheCU.getRanges().front().getStart()); 777 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges()); 778 } 779 780 auto *CUNode = cast<DICompileUnit>(P.first); 781 // If compile Unit has macros, emit "DW_AT_macro_info" attribute. 782 if (CUNode->getMacros()) 783 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info, 784 U.getMacroLabelBegin(), 785 TLOF.getDwarfMacinfoSection()->getBeginSymbol()); 786 } 787 788 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules. 789 for (auto *CUNode : MMI->getModule()->debug_compile_units()) 790 if (CUNode->getDWOId()) 791 getOrCreateDwarfCompileUnit(CUNode); 792 793 // Compute DIE offsets and sizes. 794 InfoHolder.computeSizeAndOffsets(); 795 if (useSplitDwarf()) 796 SkeletonHolder.computeSizeAndOffsets(); 797 } 798 799 // Emit all Dwarf sections that should come after the content. 800 void DwarfDebug::endModule() { 801 assert(CurFn == nullptr); 802 assert(CurMI == nullptr); 803 804 // If we aren't actually generating debug info (check beginModule - 805 // conditionalized on !DisableDebugInfoPrinting and the presence of the 806 // llvm.dbg.cu metadata node) 807 if (!MMI->hasDebugInfo()) 808 return; 809 810 // Finalize the debug info for the module. 811 finalizeModuleInfo(); 812 813 emitDebugStr(); 814 815 if (useSplitDwarf()) 816 emitDebugLocDWO(); 817 else 818 // Emit info into a debug loc section. 819 emitDebugLoc(); 820 821 // Corresponding abbreviations into a abbrev section. 822 emitAbbreviations(); 823 824 // Emit all the DIEs into a debug info section. 825 emitDebugInfo(); 826 827 // Emit info into a debug aranges section. 828 if (GenerateARangeSection) 829 emitDebugARanges(); 830 831 // Emit info into a debug ranges section. 832 emitDebugRanges(); 833 834 // Emit info into a debug macinfo section. 835 emitDebugMacinfo(); 836 837 if (useSplitDwarf()) { 838 emitDebugStrDWO(); 839 emitDebugInfoDWO(); 840 emitDebugAbbrevDWO(); 841 emitDebugLineDWO(); 842 // Emit DWO addresses. 843 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection()); 844 } 845 846 // Emit info into the dwarf accelerator table sections. 847 switch (getAccelTableKind()) { 848 case AccelTableKind::Apple: 849 emitAccelNames(); 850 emitAccelObjC(); 851 emitAccelNamespaces(); 852 emitAccelTypes(); 853 break; 854 case AccelTableKind::Dwarf: 855 emitAccelDebugNames(); 856 break; 857 case AccelTableKind::None: 858 break; 859 case AccelTableKind::Default: 860 llvm_unreachable("Default should have already been resolved."); 861 } 862 863 // Emit the pubnames and pubtypes sections if requested. 864 emitDebugPubSections(); 865 866 // clean up. 867 // FIXME: AbstractVariables.clear(); 868 } 869 870 void DwarfDebug::ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable IV, 871 const MDNode *ScopeNode) { 872 const DILocalVariable *Cleansed = nullptr; 873 if (CU.getExistingAbstractVariable(IV, Cleansed)) 874 return; 875 876 CU.createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope( 877 cast<DILocalScope>(ScopeNode))); 878 } 879 880 void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU, 881 InlinedVariable IV, const MDNode *ScopeNode) { 882 const DILocalVariable *Cleansed = nullptr; 883 if (CU.getExistingAbstractVariable(IV, Cleansed)) 884 return; 885 886 if (LexicalScope *Scope = 887 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode))) 888 CU.createAbstractVariable(Cleansed, Scope); 889 } 890 891 // Collect variable information from side table maintained by MF. 892 void DwarfDebug::collectVariableInfoFromMFTable( 893 DwarfCompileUnit &TheCU, DenseSet<InlinedVariable> &Processed) { 894 SmallDenseMap<InlinedVariable, DbgVariable *> MFVars; 895 for (const auto &VI : Asm->MF->getVariableDbgInfo()) { 896 if (!VI.Var) 897 continue; 898 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && 899 "Expected inlined-at fields to agree"); 900 901 InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt()); 902 Processed.insert(Var); 903 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 904 905 // If variable scope is not found then skip this variable. 906 if (!Scope) 907 continue; 908 909 ensureAbstractVariableIsCreatedIfScoped(TheCU, Var, Scope->getScopeNode()); 910 auto RegVar = llvm::make_unique<DbgVariable>(Var.first, Var.second); 911 RegVar->initializeMMI(VI.Expr, VI.Slot); 912 if (DbgVariable *DbgVar = MFVars.lookup(Var)) 913 DbgVar->addMMIEntry(*RegVar); 914 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) { 915 MFVars.insert({Var, RegVar.get()}); 916 ConcreteVariables.push_back(std::move(RegVar)); 917 } 918 } 919 } 920 921 // Get .debug_loc entry for the instruction range starting at MI. 922 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) { 923 const DIExpression *Expr = MI->getDebugExpression(); 924 assert(MI->getNumOperands() == 4); 925 if (MI->getOperand(0).isReg()) { 926 auto RegOp = MI->getOperand(0); 927 auto Op1 = MI->getOperand(1); 928 // If the second operand is an immediate, this is a 929 // register-indirect address. 930 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset"); 931 MachineLocation MLoc(RegOp.getReg(), Op1.isImm()); 932 return DebugLocEntry::Value(Expr, MLoc); 933 } 934 if (MI->getOperand(0).isImm()) 935 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm()); 936 if (MI->getOperand(0).isFPImm()) 937 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm()); 938 if (MI->getOperand(0).isCImm()) 939 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm()); 940 941 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!"); 942 } 943 944 /// If this and Next are describing different fragments of the same 945 /// variable, merge them by appending Next's values to the current 946 /// list of values. 947 /// Return true if the merge was successful. 948 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) { 949 if (Begin == Next.Begin) { 950 auto *FirstExpr = cast<DIExpression>(Values[0].Expression); 951 auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression); 952 if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment()) 953 return false; 954 955 // We can only merge entries if none of the fragments overlap any others. 956 // In doing so, we can take advantage of the fact that both lists are 957 // sorted. 958 for (unsigned i = 0, j = 0; i < Values.size(); ++i) { 959 for (; j < Next.Values.size(); ++j) { 960 int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp( 961 cast<DIExpression>(Next.Values[j].Expression)); 962 if (res == 0) // The two expressions overlap, we can't merge. 963 return false; 964 // Values[i] is entirely before Next.Values[j], 965 // so go back to the next entry of Values. 966 else if (res == -1) 967 break; 968 // Next.Values[j] is entirely before Values[i], so go on to the 969 // next entry of Next.Values. 970 } 971 } 972 973 addValues(Next.Values); 974 End = Next.End; 975 return true; 976 } 977 return false; 978 } 979 980 /// Build the location list for all DBG_VALUEs in the function that 981 /// describe the same variable. If the ranges of several independent 982 /// fragments of the same variable overlap partially, split them up and 983 /// combine the ranges. The resulting DebugLocEntries are will have 984 /// strict monotonically increasing begin addresses and will never 985 /// overlap. 986 // 987 // Input: 988 // 989 // Ranges History [var, loc, fragment ofs size] 990 // 0 | [x, (reg0, fragment 0, 32)] 991 // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry 992 // 2 | | ... 993 // 3 | [clobber reg0] 994 // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of 995 // x. 996 // 997 // Output: 998 // 999 // [0-1] [x, (reg0, fragment 0, 32)] 1000 // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)] 1001 // [3-4] [x, (reg1, fragment 32, 32)] 1002 // [4- ] [x, (mem, fragment 0, 64)] 1003 void 1004 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, 1005 const DbgValueHistoryMap::InstrRanges &Ranges) { 1006 SmallVector<DebugLocEntry::Value, 4> OpenRanges; 1007 1008 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { 1009 const MachineInstr *Begin = I->first; 1010 const MachineInstr *End = I->second; 1011 assert(Begin->isDebugValue() && "Invalid History entry"); 1012 1013 // Check if a variable is inaccessible in this range. 1014 if (Begin->getNumOperands() > 1 && 1015 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) { 1016 OpenRanges.clear(); 1017 continue; 1018 } 1019 1020 // If this fragment overlaps with any open ranges, truncate them. 1021 const DIExpression *DIExpr = Begin->getDebugExpression(); 1022 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) { 1023 return DIExpr->fragmentsOverlap(R.getExpression()); 1024 }); 1025 OpenRanges.erase(Last, OpenRanges.end()); 1026 1027 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin); 1028 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!"); 1029 1030 const MCSymbol *EndLabel; 1031 if (End != nullptr) 1032 EndLabel = getLabelAfterInsn(End); 1033 else if (std::next(I) == Ranges.end()) 1034 EndLabel = Asm->getFunctionEnd(); 1035 else 1036 EndLabel = getLabelBeforeInsn(std::next(I)->first); 1037 assert(EndLabel && "Forgot label after instruction ending a range!"); 1038 1039 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n"); 1040 1041 auto Value = getDebugLocValue(Begin); 1042 DebugLocEntry Loc(StartLabel, EndLabel, Value); 1043 bool couldMerge = false; 1044 1045 // If this is a fragment, it may belong to the current DebugLocEntry. 1046 if (DIExpr->isFragment()) { 1047 // Add this value to the list of open ranges. 1048 OpenRanges.push_back(Value); 1049 1050 // Attempt to add the fragment to the last entry. 1051 if (!DebugLoc.empty()) 1052 if (DebugLoc.back().MergeValues(Loc)) 1053 couldMerge = true; 1054 } 1055 1056 if (!couldMerge) { 1057 // Need to add a new DebugLocEntry. Add all values from still 1058 // valid non-overlapping fragments. 1059 if (OpenRanges.size()) 1060 Loc.addValues(OpenRanges); 1061 1062 DebugLoc.push_back(std::move(Loc)); 1063 } 1064 1065 // Attempt to coalesce the ranges of two otherwise identical 1066 // DebugLocEntries. 1067 auto CurEntry = DebugLoc.rbegin(); 1068 LLVM_DEBUG({ 1069 dbgs() << CurEntry->getValues().size() << " Values:\n"; 1070 for (auto &Value : CurEntry->getValues()) 1071 Value.dump(); 1072 dbgs() << "-----\n"; 1073 }); 1074 1075 auto PrevEntry = std::next(CurEntry); 1076 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry)) 1077 DebugLoc.pop_back(); 1078 } 1079 } 1080 1081 DbgVariable *DwarfDebug::createConcreteVariable(DwarfCompileUnit &TheCU, 1082 LexicalScope &Scope, 1083 InlinedVariable IV) { 1084 ensureAbstractVariableIsCreatedIfScoped(TheCU, IV, Scope.getScopeNode()); 1085 ConcreteVariables.push_back( 1086 llvm::make_unique<DbgVariable>(IV.first, IV.second)); 1087 InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get()); 1088 return ConcreteVariables.back().get(); 1089 } 1090 1091 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its 1092 /// enclosing lexical scope. The check ensures there are no other instructions 1093 /// in the same lexical scope preceding the DBG_VALUE and that its range is 1094 /// either open or otherwise rolls off the end of the scope. 1095 static bool validThroughout(LexicalScopes &LScopes, 1096 const MachineInstr *DbgValue, 1097 const MachineInstr *RangeEnd) { 1098 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location"); 1099 auto MBB = DbgValue->getParent(); 1100 auto DL = DbgValue->getDebugLoc(); 1101 auto *LScope = LScopes.findLexicalScope(DL); 1102 // Scope doesn't exist; this is a dead DBG_VALUE. 1103 if (!LScope) 1104 return false; 1105 auto &LSRange = LScope->getRanges(); 1106 if (LSRange.size() == 0) 1107 return false; 1108 1109 // Determine if the DBG_VALUE is valid at the beginning of its lexical block. 1110 const MachineInstr *LScopeBegin = LSRange.front().first; 1111 // Early exit if the lexical scope begins outside of the current block. 1112 if (LScopeBegin->getParent() != MBB) 1113 return false; 1114 MachineBasicBlock::const_reverse_iterator Pred(DbgValue); 1115 for (++Pred; Pred != MBB->rend(); ++Pred) { 1116 if (Pred->getFlag(MachineInstr::FrameSetup)) 1117 break; 1118 auto PredDL = Pred->getDebugLoc(); 1119 if (!PredDL || Pred->isMetaInstruction()) 1120 continue; 1121 // Check whether the instruction preceding the DBG_VALUE is in the same 1122 // (sub)scope as the DBG_VALUE. 1123 if (DL->getScope() == PredDL->getScope()) 1124 return false; 1125 auto *PredScope = LScopes.findLexicalScope(PredDL); 1126 if (!PredScope || LScope->dominates(PredScope)) 1127 return false; 1128 } 1129 1130 // If the range of the DBG_VALUE is open-ended, report success. 1131 if (!RangeEnd) 1132 return true; 1133 1134 // Fail if there are instructions belonging to our scope in another block. 1135 const MachineInstr *LScopeEnd = LSRange.back().second; 1136 if (LScopeEnd->getParent() != MBB) 1137 return false; 1138 1139 // Single, constant DBG_VALUEs in the prologue are promoted to be live 1140 // throughout the function. This is a hack, presumably for DWARF v2 and not 1141 // necessarily correct. It would be much better to use a dbg.declare instead 1142 // if we know the constant is live throughout the scope. 1143 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty()) 1144 return true; 1145 1146 return false; 1147 } 1148 1149 // Find variables for each lexical scope. 1150 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, 1151 const DISubprogram *SP, 1152 DenseSet<InlinedVariable> &Processed) { 1153 // Grab the variable info that was squirreled away in the MMI side-table. 1154 collectVariableInfoFromMFTable(TheCU, Processed); 1155 1156 for (const auto &I : DbgValues) { 1157 InlinedVariable IV = I.first; 1158 if (Processed.count(IV)) 1159 continue; 1160 1161 // Instruction ranges, specifying where IV is accessible. 1162 const auto &Ranges = I.second; 1163 if (Ranges.empty()) 1164 continue; 1165 1166 LexicalScope *Scope = nullptr; 1167 if (const DILocation *IA = IV.second) 1168 Scope = LScopes.findInlinedScope(IV.first->getScope(), IA); 1169 else 1170 Scope = LScopes.findLexicalScope(IV.first->getScope()); 1171 // If variable scope is not found then skip this variable. 1172 if (!Scope) 1173 continue; 1174 1175 Processed.insert(IV); 1176 DbgVariable *RegVar = createConcreteVariable(TheCU, *Scope, IV); 1177 1178 const MachineInstr *MInsn = Ranges.front().first; 1179 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1180 1181 // Check if there is a single DBG_VALUE, valid throughout the var's scope. 1182 if (Ranges.size() == 1 && 1183 validThroughout(LScopes, MInsn, Ranges.front().second)) { 1184 RegVar->initializeDbgValue(MInsn); 1185 continue; 1186 } 1187 1188 // Handle multiple DBG_VALUE instructions describing one variable. 1189 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 1190 1191 // Build the location list for this variable. 1192 SmallVector<DebugLocEntry, 8> Entries; 1193 buildLocationList(Entries, Ranges); 1194 1195 // If the variable has a DIBasicType, extract it. Basic types cannot have 1196 // unique identifiers, so don't bother resolving the type with the 1197 // identifier map. 1198 const DIBasicType *BT = dyn_cast<DIBasicType>( 1199 static_cast<const Metadata *>(IV.first->getType())); 1200 1201 // Finalize the entry by lowering it into a DWARF bytestream. 1202 for (auto &Entry : Entries) 1203 Entry.finalize(*Asm, List, BT); 1204 } 1205 1206 // Collect info for variables that were optimized out. 1207 for (const DINode *DN : SP->getRetainedNodes()) { 1208 if (auto *DV = dyn_cast<DILocalVariable>(DN)) { 1209 if (Processed.insert(InlinedVariable(DV, nullptr)).second) 1210 if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope())) 1211 createConcreteVariable(TheCU, *Scope, InlinedVariable(DV, nullptr)); 1212 } 1213 } 1214 } 1215 1216 // Process beginning of an instruction. 1217 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1218 DebugHandlerBase::beginInstruction(MI); 1219 assert(CurMI); 1220 1221 const auto *SP = MI->getMF()->getFunction().getSubprogram(); 1222 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1223 return; 1224 1225 // Check if source location changes, but ignore DBG_VALUE and CFI locations. 1226 // If the instruction is part of the function frame setup code, do not emit 1227 // any line record, as there is no correspondence with any user code. 1228 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup)) 1229 return; 1230 const DebugLoc &DL = MI->getDebugLoc(); 1231 // When we emit a line-0 record, we don't update PrevInstLoc; so look at 1232 // the last line number actually emitted, to see if it was line 0. 1233 unsigned LastAsmLine = 1234 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine(); 1235 1236 if (DL == PrevInstLoc) { 1237 // If we have an ongoing unspecified location, nothing to do here. 1238 if (!DL) 1239 return; 1240 // We have an explicit location, same as the previous location. 1241 // But we might be coming back to it after a line 0 record. 1242 if (LastAsmLine == 0 && DL.getLine() != 0) { 1243 // Reinstate the source location but not marked as a statement. 1244 const MDNode *Scope = DL.getScope(); 1245 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0); 1246 } 1247 return; 1248 } 1249 1250 if (!DL) { 1251 // We have an unspecified location, which might want to be line 0. 1252 // If we have already emitted a line-0 record, don't repeat it. 1253 if (LastAsmLine == 0) 1254 return; 1255 // If user said Don't Do That, don't do that. 1256 if (UnknownLocations == Disable) 1257 return; 1258 // See if we have a reason to emit a line-0 record now. 1259 // Reasons to emit a line-0 record include: 1260 // - User asked for it (UnknownLocations). 1261 // - Instruction has a label, so it's referenced from somewhere else, 1262 // possibly debug information; we want it to have a source location. 1263 // - Instruction is at the top of a block; we don't want to inherit the 1264 // location from the physically previous (maybe unrelated) block. 1265 if (UnknownLocations == Enable || PrevLabel || 1266 (PrevInstBB && PrevInstBB != MI->getParent())) { 1267 // Preserve the file and column numbers, if we can, to save space in 1268 // the encoded line table. 1269 // Do not update PrevInstLoc, it remembers the last non-0 line. 1270 const MDNode *Scope = nullptr; 1271 unsigned Column = 0; 1272 if (PrevInstLoc) { 1273 Scope = PrevInstLoc.getScope(); 1274 Column = PrevInstLoc.getCol(); 1275 } 1276 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0); 1277 } 1278 return; 1279 } 1280 1281 // We have an explicit location, different from the previous location. 1282 // Don't repeat a line-0 record, but otherwise emit the new location. 1283 // (The new location might be an explicit line 0, which we do emit.) 1284 if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0) 1285 return; 1286 unsigned Flags = 0; 1287 if (DL == PrologEndLoc) { 1288 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT; 1289 PrologEndLoc = DebugLoc(); 1290 } 1291 // If the line changed, we call that a new statement; unless we went to 1292 // line 0 and came back, in which case it is not a new statement. 1293 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine; 1294 if (DL.getLine() && DL.getLine() != OldLine) 1295 Flags |= DWARF2_FLAG_IS_STMT; 1296 1297 const MDNode *Scope = DL.getScope(); 1298 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1299 1300 // If we're not at line 0, remember this location. 1301 if (DL.getLine()) 1302 PrevInstLoc = DL; 1303 } 1304 1305 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1306 // First known non-DBG_VALUE and non-frame setup location marks 1307 // the beginning of the function body. 1308 for (const auto &MBB : *MF) 1309 for (const auto &MI : MBB) 1310 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && 1311 MI.getDebugLoc()) 1312 return MI.getDebugLoc(); 1313 return DebugLoc(); 1314 } 1315 1316 // Gather pre-function debug information. Assumes being called immediately 1317 // after the function entry point has been emitted. 1318 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) { 1319 CurFn = MF; 1320 1321 auto *SP = MF->getFunction().getSubprogram(); 1322 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode()); 1323 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) 1324 return; 1325 1326 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit()); 1327 1328 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1329 // belongs to so that we add to the correct per-cu line table in the 1330 // non-asm case. 1331 if (Asm->OutStreamer->hasRawTextSupport()) 1332 // Use a single line table if we are generating assembly. 1333 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1334 else 1335 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID()); 1336 1337 // Record beginning of function. 1338 PrologEndLoc = findPrologueEndLoc(MF); 1339 if (PrologEndLoc) { 1340 // We'd like to list the prologue as "not statements" but GDB behaves 1341 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1342 auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram(); 1343 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT); 1344 } 1345 } 1346 1347 void DwarfDebug::skippedNonDebugFunction() { 1348 // If we don't have a subprogram for this function then there will be a hole 1349 // in the range information. Keep note of this by setting the previously used 1350 // section to nullptr. 1351 PrevCU = nullptr; 1352 CurFn = nullptr; 1353 } 1354 1355 // Gather and emit post-function debug information. 1356 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) { 1357 const DISubprogram *SP = MF->getFunction().getSubprogram(); 1358 1359 assert(CurFn == MF && 1360 "endFunction should be called with the same function as beginFunction"); 1361 1362 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1363 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1364 1365 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1366 assert(!FnScope || SP == FnScope->getScopeNode()); 1367 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit()); 1368 1369 DenseSet<InlinedVariable> ProcessedVars; 1370 collectVariableInfo(TheCU, SP, ProcessedVars); 1371 1372 // Add the range of this function to the list of ranges for the CU. 1373 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd())); 1374 1375 // Under -gmlt, skip building the subprogram if there are no inlined 1376 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram 1377 // is still needed as we need its source location. 1378 if (!TheCU.getCUNode()->getDebugInfoForProfiling() && 1379 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly && 1380 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1381 assert(InfoHolder.getScopeVariables().empty()); 1382 PrevLabel = nullptr; 1383 CurFn = nullptr; 1384 return; 1385 } 1386 1387 #ifndef NDEBUG 1388 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1389 #endif 1390 // Construct abstract scopes. 1391 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1392 auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 1393 for (const DINode *DN : SP->getRetainedNodes()) { 1394 if (auto *DV = dyn_cast<DILocalVariable>(DN)) { 1395 // Collect info for variables that were optimized out. 1396 if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second) 1397 continue; 1398 ensureAbstractVariableIsCreated(TheCU, InlinedVariable(DV, nullptr), 1399 DV->getScope()); 1400 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1401 && "ensureAbstractVariableIsCreated inserted abstract scopes"); 1402 } 1403 } 1404 constructAbstractSubprogramScopeDIE(TheCU, AScope); 1405 } 1406 1407 ProcessedSPNodes.insert(SP); 1408 TheCU.constructSubprogramScopeDIE(SP, FnScope); 1409 if (auto *SkelCU = TheCU.getSkeleton()) 1410 if (!LScopes.getAbstractScopesList().empty() && 1411 TheCU.getCUNode()->getSplitDebugInlining()) 1412 SkelCU->constructSubprogramScopeDIE(SP, FnScope); 1413 1414 // Clear debug info 1415 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1416 // DbgVariables except those that are also in AbstractVariables (since they 1417 // can be used cross-function) 1418 InfoHolder.getScopeVariables().clear(); 1419 PrevLabel = nullptr; 1420 CurFn = nullptr; 1421 } 1422 1423 // Register a source line with debug info. Returns the unique label that was 1424 // emitted and which provides correspondence to the source line list. 1425 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1426 unsigned Flags) { 1427 StringRef Fn; 1428 unsigned FileNo = 1; 1429 unsigned Discriminator = 0; 1430 if (auto *Scope = cast_or_null<DIScope>(S)) { 1431 Fn = Scope->getFilename(); 1432 if (Line != 0 && getDwarfVersion() >= 4) 1433 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 1434 Discriminator = LBF->getDiscriminator(); 1435 1436 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID(); 1437 FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID]) 1438 .getOrCreateSourceID(Scope->getFile()); 1439 } 1440 Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0, 1441 Discriminator, Fn); 1442 } 1443 1444 //===----------------------------------------------------------------------===// 1445 // Emit Methods 1446 //===----------------------------------------------------------------------===// 1447 1448 // Emit the debug info section. 1449 void DwarfDebug::emitDebugInfo() { 1450 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1451 Holder.emitUnits(/* UseOffsets */ false); 1452 } 1453 1454 // Emit the abbreviation section. 1455 void DwarfDebug::emitAbbreviations() { 1456 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1457 1458 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1459 } 1460 1461 void DwarfDebug::emitStringOffsetsTableHeader() { 1462 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1463 Holder.emitStringOffsetsTableHeader( 1464 Asm->getObjFileLowering().getDwarfStrOffSection()); 1465 } 1466 1467 template <typename AccelTableT> 1468 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section, 1469 StringRef TableName) { 1470 Asm->OutStreamer->SwitchSection(Section); 1471 1472 // Emit the full data. 1473 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol()); 1474 } 1475 1476 void DwarfDebug::emitAccelDebugNames() { 1477 // Don't emit anything if we have no compilation units to index. 1478 if (getUnits().empty()) 1479 return; 1480 1481 Asm->OutStreamer->SwitchSection( 1482 Asm->getObjFileLowering().getDwarfDebugNamesSection()); 1483 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits()); 1484 } 1485 1486 // Emit visible names into a hashed accelerator table section. 1487 void DwarfDebug::emitAccelNames() { 1488 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1489 "Names"); 1490 } 1491 1492 // Emit objective C classes and categories into a hashed accelerator table 1493 // section. 1494 void DwarfDebug::emitAccelObjC() { 1495 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1496 "ObjC"); 1497 } 1498 1499 // Emit namespace dies into a hashed accelerator table. 1500 void DwarfDebug::emitAccelNamespaces() { 1501 emitAccel(AccelNamespace, 1502 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1503 "namespac"); 1504 } 1505 1506 // Emit type dies into a hashed accelerator table. 1507 void DwarfDebug::emitAccelTypes() { 1508 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1509 "types"); 1510 } 1511 1512 // Public name handling. 1513 // The format for the various pubnames: 1514 // 1515 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1516 // for the DIE that is named. 1517 // 1518 // gnu pubnames - offset/index value/name tuples where the offset is the offset 1519 // into the CU and the index value is computed according to the type of value 1520 // for the DIE that is named. 1521 // 1522 // For type units the offset is the offset of the skeleton DIE. For split dwarf 1523 // it's the offset within the debug_info/debug_types dwo section, however, the 1524 // reference in the pubname header doesn't change. 1525 1526 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 1527 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1528 const DIE *Die) { 1529 // Entities that ended up only in a Type Unit reference the CU instead (since 1530 // the pub entry has offsets within the CU there's no real offset that can be 1531 // provided anyway). As it happens all such entities (namespaces and types, 1532 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out 1533 // not to be true it would be necessary to persist this information from the 1534 // point at which the entry is added to the index data structure - since by 1535 // the time the index is built from that, the original type/namespace DIE in a 1536 // type unit has already been destroyed so it can't be queried for properties 1537 // like tag, etc. 1538 if (Die->getTag() == dwarf::DW_TAG_compile_unit) 1539 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, 1540 dwarf::GIEL_EXTERNAL); 1541 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1542 1543 // We could have a specification DIE that has our most of our knowledge, 1544 // look for that now. 1545 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 1546 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 1547 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1548 Linkage = dwarf::GIEL_EXTERNAL; 1549 } else if (Die->findAttribute(dwarf::DW_AT_external)) 1550 Linkage = dwarf::GIEL_EXTERNAL; 1551 1552 switch (Die->getTag()) { 1553 case dwarf::DW_TAG_class_type: 1554 case dwarf::DW_TAG_structure_type: 1555 case dwarf::DW_TAG_union_type: 1556 case dwarf::DW_TAG_enumeration_type: 1557 return dwarf::PubIndexEntryDescriptor( 1558 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1559 ? dwarf::GIEL_STATIC 1560 : dwarf::GIEL_EXTERNAL); 1561 case dwarf::DW_TAG_typedef: 1562 case dwarf::DW_TAG_base_type: 1563 case dwarf::DW_TAG_subrange_type: 1564 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1565 case dwarf::DW_TAG_namespace: 1566 return dwarf::GIEK_TYPE; 1567 case dwarf::DW_TAG_subprogram: 1568 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1569 case dwarf::DW_TAG_variable: 1570 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1571 case dwarf::DW_TAG_enumerator: 1572 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1573 dwarf::GIEL_STATIC); 1574 default: 1575 return dwarf::GIEK_NONE; 1576 } 1577 } 1578 1579 /// emitDebugPubSections - Emit visible names and types into debug pubnames and 1580 /// pubtypes sections. 1581 void DwarfDebug::emitDebugPubSections() { 1582 for (const auto &NU : CUMap) { 1583 DwarfCompileUnit *TheU = NU.second; 1584 if (!TheU->hasDwarfPubSections()) 1585 continue; 1586 1587 bool GnuStyle = TheU->getCUNode()->getGnuPubnames(); 1588 1589 Asm->OutStreamer->SwitchSection( 1590 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1591 : Asm->getObjFileLowering().getDwarfPubNamesSection()); 1592 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames()); 1593 1594 Asm->OutStreamer->SwitchSection( 1595 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1596 : Asm->getObjFileLowering().getDwarfPubTypesSection()); 1597 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes()); 1598 } 1599 } 1600 1601 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) { 1602 if (useSectionsAsReferences()) 1603 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(), 1604 CU.getDebugSectionOffset()); 1605 else 1606 Asm->emitDwarfSymbolReference(CU.getLabelBegin()); 1607 } 1608 1609 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name, 1610 DwarfCompileUnit *TheU, 1611 const StringMap<const DIE *> &Globals) { 1612 if (auto *Skeleton = TheU->getSkeleton()) 1613 TheU = Skeleton; 1614 1615 // Emit the header. 1616 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info"); 1617 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 1618 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 1619 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1620 1621 Asm->OutStreamer->EmitLabel(BeginLabel); 1622 1623 Asm->OutStreamer->AddComment("DWARF Version"); 1624 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); 1625 1626 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 1627 emitSectionReference(*TheU); 1628 1629 Asm->OutStreamer->AddComment("Compilation Unit Length"); 1630 Asm->emitInt32(TheU->getLength()); 1631 1632 // Emit the pubnames for this compilation unit. 1633 for (const auto &GI : Globals) { 1634 const char *Name = GI.getKeyData(); 1635 const DIE *Entity = GI.second; 1636 1637 Asm->OutStreamer->AddComment("DIE offset"); 1638 Asm->emitInt32(Entity->getOffset()); 1639 1640 if (GnuStyle) { 1641 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1642 Asm->OutStreamer->AddComment( 1643 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " + 1644 dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1645 Asm->emitInt8(Desc.toBits()); 1646 } 1647 1648 Asm->OutStreamer->AddComment("External Name"); 1649 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1650 } 1651 1652 Asm->OutStreamer->AddComment("End Mark"); 1653 Asm->emitInt32(0); 1654 Asm->OutStreamer->EmitLabel(EndLabel); 1655 } 1656 1657 /// Emit null-terminated strings into a debug str section. 1658 void DwarfDebug::emitDebugStr() { 1659 MCSection *StringOffsetsSection = nullptr; 1660 if (useSegmentedStringOffsetsTable()) { 1661 emitStringOffsetsTableHeader(); 1662 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection(); 1663 } 1664 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1665 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(), 1666 StringOffsetsSection, /* UseRelativeOffsets = */ true); 1667 } 1668 1669 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 1670 const DebugLocStream::Entry &Entry) { 1671 auto &&Comments = DebugLocs.getComments(Entry); 1672 auto Comment = Comments.begin(); 1673 auto End = Comments.end(); 1674 for (uint8_t Byte : DebugLocs.getBytes(Entry)) 1675 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : ""); 1676 } 1677 1678 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 1679 ByteStreamer &Streamer, 1680 const DebugLocEntry::Value &Value, 1681 DwarfExpression &DwarfExpr) { 1682 auto *DIExpr = Value.getExpression(); 1683 DIExpressionCursor ExprCursor(DIExpr); 1684 DwarfExpr.addFragmentOffset(DIExpr); 1685 // Regular entry. 1686 if (Value.isInt()) { 1687 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 1688 BT->getEncoding() == dwarf::DW_ATE_signed_char)) 1689 DwarfExpr.addSignedConstant(Value.getInt()); 1690 else 1691 DwarfExpr.addUnsignedConstant(Value.getInt()); 1692 } else if (Value.isLocation()) { 1693 MachineLocation Location = Value.getLoc(); 1694 if (Location.isIndirect()) 1695 DwarfExpr.setMemoryLocationKind(); 1696 DIExpressionCursor Cursor(DIExpr); 1697 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo(); 1698 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) 1699 return; 1700 return DwarfExpr.addExpression(std::move(Cursor)); 1701 } else if (Value.isConstantFP()) { 1702 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt(); 1703 DwarfExpr.addUnsignedConstant(RawBytes); 1704 } 1705 DwarfExpr.addExpression(std::move(ExprCursor)); 1706 } 1707 1708 void DebugLocEntry::finalize(const AsmPrinter &AP, 1709 DebugLocStream::ListBuilder &List, 1710 const DIBasicType *BT) { 1711 DebugLocStream::EntryBuilder Entry(List, Begin, End); 1712 BufferByteStreamer Streamer = Entry.getStreamer(); 1713 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer); 1714 const DebugLocEntry::Value &Value = Values[0]; 1715 if (Value.isFragment()) { 1716 // Emit all fragments that belong to the same variable and range. 1717 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) { 1718 return P.isFragment(); 1719 }) && "all values are expected to be fragments"); 1720 assert(std::is_sorted(Values.begin(), Values.end()) && 1721 "fragments are expected to be sorted"); 1722 1723 for (auto Fragment : Values) 1724 emitDebugLocValue(AP, BT, Streamer, Fragment, DwarfExpr); 1725 1726 } else { 1727 assert(Values.size() == 1 && "only fragments may have >1 value"); 1728 emitDebugLocValue(AP, BT, Streamer, Value, DwarfExpr); 1729 } 1730 DwarfExpr.finalize(); 1731 } 1732 1733 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) { 1734 // Emit the size. 1735 Asm->OutStreamer->AddComment("Loc expr size"); 1736 Asm->emitInt16(DebugLocs.getBytes(Entry).size()); 1737 1738 // Emit the entry. 1739 APByteStreamer Streamer(*Asm); 1740 emitDebugLocEntry(Streamer, Entry); 1741 } 1742 1743 // Emit locations into the debug loc section. 1744 void DwarfDebug::emitDebugLoc() { 1745 if (DebugLocs.getLists().empty()) 1746 return; 1747 1748 // Start the dwarf loc section. 1749 Asm->OutStreamer->SwitchSection( 1750 Asm->getObjFileLowering().getDwarfLocSection()); 1751 unsigned char Size = Asm->MAI->getCodePointerSize(); 1752 for (const auto &List : DebugLocs.getLists()) { 1753 Asm->OutStreamer->EmitLabel(List.Label); 1754 const DwarfCompileUnit *CU = List.CU; 1755 for (const auto &Entry : DebugLocs.getEntries(List)) { 1756 // Set up the range. This range is relative to the entry point of the 1757 // compile unit. This is a hard coded 0 for low_pc when we're emitting 1758 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 1759 if (auto *Base = CU->getBaseAddress()) { 1760 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 1761 Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 1762 } else { 1763 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 1764 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 1765 } 1766 1767 emitDebugLocEntryLocation(Entry); 1768 } 1769 Asm->OutStreamer->EmitIntValue(0, Size); 1770 Asm->OutStreamer->EmitIntValue(0, Size); 1771 } 1772 } 1773 1774 void DwarfDebug::emitDebugLocDWO() { 1775 Asm->OutStreamer->SwitchSection( 1776 Asm->getObjFileLowering().getDwarfLocDWOSection()); 1777 for (const auto &List : DebugLocs.getLists()) { 1778 Asm->OutStreamer->EmitLabel(List.Label); 1779 for (const auto &Entry : DebugLocs.getEntries(List)) { 1780 // Just always use start_length for now - at least that's one address 1781 // rather than two. We could get fancier and try to, say, reuse an 1782 // address we know we've emitted elsewhere (the start of the function? 1783 // The start of the CU or CU subrange that encloses this range?) 1784 Asm->emitInt8(dwarf::DW_LLE_startx_length); 1785 unsigned idx = AddrPool.getIndex(Entry.BeginSym); 1786 Asm->EmitULEB128(idx); 1787 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 1788 1789 emitDebugLocEntryLocation(Entry); 1790 } 1791 Asm->emitInt8(dwarf::DW_LLE_end_of_list); 1792 } 1793 } 1794 1795 struct ArangeSpan { 1796 const MCSymbol *Start, *End; 1797 }; 1798 1799 // Emit a debug aranges section, containing a CU lookup for any 1800 // address we can tie back to a CU. 1801 void DwarfDebug::emitDebugARanges() { 1802 // Provides a unique id per text section. 1803 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 1804 1805 // Filter labels by section. 1806 for (const SymbolCU &SCU : ArangeLabels) { 1807 if (SCU.Sym->isInSection()) { 1808 // Make a note of this symbol and it's section. 1809 MCSection *Section = &SCU.Sym->getSection(); 1810 if (!Section->getKind().isMetadata()) 1811 SectionMap[Section].push_back(SCU); 1812 } else { 1813 // Some symbols (e.g. common/bss on mach-o) can have no section but still 1814 // appear in the output. This sucks as we rely on sections to build 1815 // arange spans. We can do it without, but it's icky. 1816 SectionMap[nullptr].push_back(SCU); 1817 } 1818 } 1819 1820 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 1821 1822 for (auto &I : SectionMap) { 1823 MCSection *Section = I.first; 1824 SmallVector<SymbolCU, 8> &List = I.second; 1825 if (List.size() < 1) 1826 continue; 1827 1828 // If we have no section (e.g. common), just write out 1829 // individual spans for each symbol. 1830 if (!Section) { 1831 for (const SymbolCU &Cur : List) { 1832 ArangeSpan Span; 1833 Span.Start = Cur.Sym; 1834 Span.End = nullptr; 1835 assert(Cur.CU); 1836 Spans[Cur.CU].push_back(Span); 1837 } 1838 continue; 1839 } 1840 1841 // Sort the symbols by offset within the section. 1842 std::stable_sort( 1843 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) { 1844 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 1845 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 1846 1847 // Symbols with no order assigned should be placed at the end. 1848 // (e.g. section end labels) 1849 if (IA == 0) 1850 return false; 1851 if (IB == 0) 1852 return true; 1853 return IA < IB; 1854 }); 1855 1856 // Insert a final terminator. 1857 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section))); 1858 1859 // Build spans between each label. 1860 const MCSymbol *StartSym = List[0].Sym; 1861 for (size_t n = 1, e = List.size(); n < e; n++) { 1862 const SymbolCU &Prev = List[n - 1]; 1863 const SymbolCU &Cur = List[n]; 1864 1865 // Try and build the longest span we can within the same CU. 1866 if (Cur.CU != Prev.CU) { 1867 ArangeSpan Span; 1868 Span.Start = StartSym; 1869 Span.End = Cur.Sym; 1870 assert(Prev.CU); 1871 Spans[Prev.CU].push_back(Span); 1872 StartSym = Cur.Sym; 1873 } 1874 } 1875 } 1876 1877 // Start the dwarf aranges section. 1878 Asm->OutStreamer->SwitchSection( 1879 Asm->getObjFileLowering().getDwarfARangesSection()); 1880 1881 unsigned PtrSize = Asm->MAI->getCodePointerSize(); 1882 1883 // Build a list of CUs used. 1884 std::vector<DwarfCompileUnit *> CUs; 1885 for (const auto &it : Spans) { 1886 DwarfCompileUnit *CU = it.first; 1887 CUs.push_back(CU); 1888 } 1889 1890 // Sort the CU list (again, to ensure consistent output order). 1891 llvm::sort(CUs.begin(), CUs.end(), 1892 [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 1893 return A->getUniqueID() < B->getUniqueID(); 1894 }); 1895 1896 // Emit an arange table for each CU we used. 1897 for (DwarfCompileUnit *CU : CUs) { 1898 std::vector<ArangeSpan> &List = Spans[CU]; 1899 1900 // Describe the skeleton CU's offset and length, not the dwo file's. 1901 if (auto *Skel = CU->getSkeleton()) 1902 CU = Skel; 1903 1904 // Emit size of content not including length itself. 1905 unsigned ContentSize = 1906 sizeof(int16_t) + // DWARF ARange version number 1907 sizeof(int32_t) + // Offset of CU in the .debug_info section 1908 sizeof(int8_t) + // Pointer Size (in bytes) 1909 sizeof(int8_t); // Segment Size (in bytes) 1910 1911 unsigned TupleSize = PtrSize * 2; 1912 1913 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 1914 unsigned Padding = 1915 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 1916 1917 ContentSize += Padding; 1918 ContentSize += (List.size() + 1) * TupleSize; 1919 1920 // For each compile unit, write the list of spans it covers. 1921 Asm->OutStreamer->AddComment("Length of ARange Set"); 1922 Asm->emitInt32(ContentSize); 1923 Asm->OutStreamer->AddComment("DWARF Arange version number"); 1924 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); 1925 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 1926 emitSectionReference(*CU); 1927 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 1928 Asm->emitInt8(PtrSize); 1929 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 1930 Asm->emitInt8(0); 1931 1932 Asm->OutStreamer->emitFill(Padding, 0xff); 1933 1934 for (const ArangeSpan &Span : List) { 1935 Asm->EmitLabelReference(Span.Start, PtrSize); 1936 1937 // Calculate the size as being from the span start to it's end. 1938 if (Span.End) { 1939 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 1940 } else { 1941 // For symbols without an end marker (e.g. common), we 1942 // write a single arange entry containing just that one symbol. 1943 uint64_t Size = SymSize[Span.Start]; 1944 if (Size == 0) 1945 Size = 1; 1946 1947 Asm->OutStreamer->EmitIntValue(Size, PtrSize); 1948 } 1949 } 1950 1951 Asm->OutStreamer->AddComment("ARange terminator"); 1952 Asm->OutStreamer->EmitIntValue(0, PtrSize); 1953 Asm->OutStreamer->EmitIntValue(0, PtrSize); 1954 } 1955 } 1956 1957 /// Emit address ranges into a debug ranges section. 1958 void DwarfDebug::emitDebugRanges() { 1959 if (CUMap.empty()) 1960 return; 1961 1962 if (!useRangesSection()) { 1963 assert(llvm::all_of( 1964 CUMap, 1965 [](const decltype(CUMap)::const_iterator::value_type &Pair) { 1966 return Pair.second->getRangeLists().empty(); 1967 }) && 1968 "No debug ranges expected."); 1969 return; 1970 } 1971 1972 // Start the dwarf ranges section. 1973 Asm->OutStreamer->SwitchSection( 1974 Asm->getObjFileLowering().getDwarfRangesSection()); 1975 1976 // Size for our labels. 1977 unsigned char Size = Asm->MAI->getCodePointerSize(); 1978 1979 // Grab the specific ranges for the compile units in the module. 1980 for (const auto &I : CUMap) { 1981 DwarfCompileUnit *TheCU = I.second; 1982 1983 if (auto *Skel = TheCU->getSkeleton()) 1984 TheCU = Skel; 1985 1986 // Iterate over the misc ranges for the compile units in the module. 1987 for (const RangeSpanList &List : TheCU->getRangeLists()) { 1988 // Emit our symbol so we can find the beginning of the range. 1989 Asm->OutStreamer->EmitLabel(List.getSym()); 1990 1991 // Gather all the ranges that apply to the same section so they can share 1992 // a base address entry. 1993 MapVector<const MCSection *, std::vector<const RangeSpan *>> MV; 1994 for (const RangeSpan &Range : List.getRanges()) { 1995 MV[&Range.getStart()->getSection()].push_back(&Range); 1996 } 1997 1998 auto *CUBase = TheCU->getBaseAddress(); 1999 bool BaseIsSet = false; 2000 for (const auto &P : MV) { 2001 // Don't bother with a base address entry if there's only one range in 2002 // this section in this range list - for example ranges for a CU will 2003 // usually consist of single regions from each of many sections 2004 // (-ffunction-sections, or just C++ inline functions) except under LTO 2005 // or optnone where there may be holes in a single CU's section 2006 // contrubutions. 2007 auto *Base = CUBase; 2008 if (!Base && P.second.size() > 1 && 2009 UseDwarfRangesBaseAddressSpecifier) { 2010 BaseIsSet = true; 2011 // FIXME/use care: This may not be a useful base address if it's not 2012 // the lowest address/range in this object. 2013 Base = P.second.front()->getStart(); 2014 Asm->OutStreamer->EmitIntValue(-1, Size); 2015 Asm->OutStreamer->EmitSymbolValue(Base, Size); 2016 } else if (BaseIsSet) { 2017 BaseIsSet = false; 2018 Asm->OutStreamer->EmitIntValue(-1, Size); 2019 Asm->OutStreamer->EmitIntValue(0, Size); 2020 } 2021 2022 for (const auto *RS : P.second) { 2023 const MCSymbol *Begin = RS->getStart(); 2024 const MCSymbol *End = RS->getEnd(); 2025 assert(Begin && "Range without a begin symbol?"); 2026 assert(End && "Range without an end symbol?"); 2027 if (Base) { 2028 Asm->EmitLabelDifference(Begin, Base, Size); 2029 Asm->EmitLabelDifference(End, Base, Size); 2030 } else { 2031 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 2032 Asm->OutStreamer->EmitSymbolValue(End, Size); 2033 } 2034 } 2035 } 2036 2037 // And terminate the list with two 0 values. 2038 Asm->OutStreamer->EmitIntValue(0, Size); 2039 Asm->OutStreamer->EmitIntValue(0, Size); 2040 } 2041 } 2042 } 2043 2044 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 2045 for (auto *MN : Nodes) { 2046 if (auto *M = dyn_cast<DIMacro>(MN)) 2047 emitMacro(*M); 2048 else if (auto *F = dyn_cast<DIMacroFile>(MN)) 2049 emitMacroFile(*F, U); 2050 else 2051 llvm_unreachable("Unexpected DI type!"); 2052 } 2053 } 2054 2055 void DwarfDebug::emitMacro(DIMacro &M) { 2056 Asm->EmitULEB128(M.getMacinfoType()); 2057 Asm->EmitULEB128(M.getLine()); 2058 StringRef Name = M.getName(); 2059 StringRef Value = M.getValue(); 2060 Asm->OutStreamer->EmitBytes(Name); 2061 if (!Value.empty()) { 2062 // There should be one space between macro name and macro value. 2063 Asm->emitInt8(' '); 2064 Asm->OutStreamer->EmitBytes(Value); 2065 } 2066 Asm->emitInt8('\0'); 2067 } 2068 2069 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 2070 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 2071 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file); 2072 Asm->EmitULEB128(F.getLine()); 2073 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile())); 2074 handleMacroNodes(F.getElements(), U); 2075 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file); 2076 } 2077 2078 /// Emit macros into a debug macinfo section. 2079 void DwarfDebug::emitDebugMacinfo() { 2080 if (CUMap.empty()) 2081 return; 2082 2083 // Start the dwarf macinfo section. 2084 Asm->OutStreamer->SwitchSection( 2085 Asm->getObjFileLowering().getDwarfMacinfoSection()); 2086 2087 for (const auto &P : CUMap) { 2088 auto &TheCU = *P.second; 2089 auto *SkCU = TheCU.getSkeleton(); 2090 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 2091 auto *CUNode = cast<DICompileUnit>(P.first); 2092 DIMacroNodeArray Macros = CUNode->getMacros(); 2093 if (!Macros.empty()) { 2094 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin()); 2095 handleMacroNodes(Macros, U); 2096 } 2097 } 2098 Asm->OutStreamer->AddComment("End Of Macro List Mark"); 2099 Asm->emitInt8(0); 2100 } 2101 2102 // DWARF5 Experimental Separate Dwarf emitters. 2103 2104 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 2105 std::unique_ptr<DwarfCompileUnit> NewU) { 2106 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name, 2107 Asm->TM.Options.MCOptions.SplitDwarfFile); 2108 2109 if (!CompilationDir.empty()) 2110 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2111 2112 addGnuPubAttributes(*NewU, Die); 2113 2114 SkeletonHolder.addUnit(std::move(NewU)); 2115 } 2116 2117 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list, 2118 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id, 2119 // DW_AT_addr_base, DW_AT_ranges_base. 2120 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 2121 2122 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>( 2123 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 2124 DwarfCompileUnit &NewCU = *OwnedUnit; 2125 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection()); 2126 2127 NewCU.initStmtList(); 2128 2129 if (useSegmentedStringOffsetsTable()) 2130 NewCU.addStringOffsetsStart(); 2131 2132 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 2133 2134 return NewCU; 2135 } 2136 2137 // Emit the .debug_info.dwo section for separated dwarf. This contains the 2138 // compile units that would normally be in debug_info. 2139 void DwarfDebug::emitDebugInfoDWO() { 2140 assert(useSplitDwarf() && "No split dwarf debug info?"); 2141 // Don't emit relocations into the dwo file. 2142 InfoHolder.emitUnits(/* UseOffsets */ true); 2143 } 2144 2145 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2146 // abbreviations for the .debug_info.dwo section. 2147 void DwarfDebug::emitDebugAbbrevDWO() { 2148 assert(useSplitDwarf() && "No split dwarf?"); 2149 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2150 } 2151 2152 void DwarfDebug::emitDebugLineDWO() { 2153 assert(useSplitDwarf() && "No split dwarf?"); 2154 SplitTypeUnitFileTable.Emit( 2155 *Asm->OutStreamer, MCDwarfLineTableParams(), 2156 Asm->getObjFileLowering().getDwarfLineDWOSection()); 2157 } 2158 2159 void DwarfDebug::emitStringOffsetsTableHeaderDWO() { 2160 assert(useSplitDwarf() && "No split dwarf?"); 2161 InfoHolder.emitStringOffsetsTableHeader( 2162 Asm->getObjFileLowering().getDwarfStrOffDWOSection()); 2163 } 2164 2165 // Emit the .debug_str.dwo section for separated dwarf. This contains the 2166 // string section and is identical in format to traditional .debug_str 2167 // sections. 2168 void DwarfDebug::emitDebugStrDWO() { 2169 if (useSegmentedStringOffsetsTable()) 2170 emitStringOffsetsTableHeaderDWO(); 2171 assert(useSplitDwarf() && "No split dwarf?"); 2172 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2173 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2174 OffSec, /* UseRelativeOffsets = */ false); 2175 } 2176 2177 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2178 if (!useSplitDwarf()) 2179 return nullptr; 2180 const DICompileUnit *DIUnit = CU.getCUNode(); 2181 SplitTypeUnitFileTable.maybeSetRootFile( 2182 DIUnit->getDirectory(), DIUnit->getFilename(), 2183 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource()); 2184 return &SplitTypeUnitFileTable; 2185 } 2186 2187 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 2188 MD5 Hash; 2189 Hash.update(Identifier); 2190 // ... take the least significant 8 bytes and return those. Our MD5 2191 // implementation always returns its results in little endian, so we actually 2192 // need the "high" word. 2193 MD5::MD5Result Result; 2194 Hash.final(Result); 2195 return Result.high(); 2196 } 2197 2198 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2199 StringRef Identifier, DIE &RefDie, 2200 const DICompositeType *CTy) { 2201 // Fast path if we're building some type units and one has already used the 2202 // address pool we know we're going to throw away all this work anyway, so 2203 // don't bother building dependent types. 2204 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 2205 return; 2206 2207 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 2208 if (!Ins.second) { 2209 CU.addDIETypeSignature(RefDie, Ins.first->second); 2210 return; 2211 } 2212 2213 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 2214 AddrPool.resetUsedFlag(); 2215 2216 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 2217 getDwoLineTable(CU)); 2218 DwarfTypeUnit &NewTU = *OwnedUnit; 2219 DIE &UnitDie = NewTU.getUnitDie(); 2220 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy); 2221 2222 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2223 CU.getLanguage()); 2224 2225 uint64_t Signature = makeTypeSignature(Identifier); 2226 NewTU.setTypeSignature(Signature); 2227 Ins.first->second = Signature; 2228 2229 if (useSplitDwarf()) 2230 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection()); 2231 else { 2232 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature)); 2233 // Non-split type units reuse the compile unit's line table. 2234 CU.applyStmtList(UnitDie); 2235 } 2236 2237 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type 2238 // units. 2239 if (useSegmentedStringOffsetsTable() && !useSplitDwarf()) 2240 NewTU.addStringOffsetsStart(); 2241 2242 NewTU.setType(NewTU.createTypeDIE(CTy)); 2243 2244 if (TopLevelType) { 2245 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 2246 TypeUnitsUnderConstruction.clear(); 2247 2248 // Types referencing entries in the address table cannot be placed in type 2249 // units. 2250 if (AddrPool.hasBeenUsed()) { 2251 2252 // Remove all the types built while building this type. 2253 // This is pessimistic as some of these types might not be dependent on 2254 // the type that used an address. 2255 for (const auto &TU : TypeUnitsToAdd) 2256 TypeSignatures.erase(TU.second); 2257 2258 // Construct this type in the CU directly. 2259 // This is inefficient because all the dependent types will be rebuilt 2260 // from scratch, including building them in type units, discovering that 2261 // they depend on addresses, throwing them out and rebuilding them. 2262 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 2263 return; 2264 } 2265 2266 // If the type wasn't dependent on fission addresses, finish adding the type 2267 // and all its dependent types. 2268 for (auto &TU : TypeUnitsToAdd) { 2269 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 2270 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 2271 } 2272 } 2273 CU.addDIETypeSignature(RefDie, Signature); 2274 } 2275 2276 void DwarfDebug::addAccelDebugName(StringRef Name, const DIE &Die) { 2277 assert(getAccelTableKind() == AccelTableKind::Dwarf); 2278 2279 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2280 AccelDebugNames.addName(Holder.getStringPool().getEntry(*Asm, Name), Die); 2281 } 2282 2283 // Accelerator table mutators - add each name along with its companion 2284 // DIE to the proper table while ensuring that the name that we're going 2285 // to reference is in the string table. We do this since the names we 2286 // add may not only be identical to the names in the DIE. 2287 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) { 2288 switch (getAccelTableKind()) { 2289 case AccelTableKind::Apple: 2290 AccelNames.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2291 break; 2292 case AccelTableKind::Dwarf: 2293 addAccelDebugName(Name, Die); 2294 break; 2295 case AccelTableKind::None: 2296 return; 2297 case AccelTableKind::Default: 2298 llvm_unreachable("Default should have already been resolved."); 2299 } 2300 } 2301 2302 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) { 2303 if (getAccelTableKind() != AccelTableKind::Apple) 2304 return; 2305 AccelObjC.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2306 } 2307 2308 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) { 2309 switch (getAccelTableKind()) { 2310 case AccelTableKind::Apple: 2311 AccelNamespace.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), 2312 &Die); 2313 break; 2314 case AccelTableKind::Dwarf: 2315 addAccelDebugName(Name, Die); 2316 break; 2317 case AccelTableKind::None: 2318 return; 2319 case AccelTableKind::Default: 2320 llvm_unreachable("Default should have already been resolved."); 2321 } 2322 } 2323 2324 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) { 2325 switch (getAccelTableKind()) { 2326 case AccelTableKind::Apple: 2327 AccelTypes.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 2328 break; 2329 case AccelTableKind::Dwarf: 2330 addAccelDebugName(Name, Die); 2331 break; 2332 case AccelTableKind::None: 2333 return; 2334 case AccelTableKind::Default: 2335 llvm_unreachable("Default should have already been resolved."); 2336 } 2337 } 2338 2339 uint16_t DwarfDebug::getDwarfVersion() const { 2340 return Asm->OutStreamer->getContext().getDwarfVersion(); 2341 } 2342