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