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