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