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