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.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 // Determine whether this DBG_VALUE is valid at the beginning of the function. 939 static bool validAtEntry(const MachineInstr *MInsn) { 940 auto MBB = MInsn->getParent(); 941 // Is it in the entry basic block? 942 if (!MBB->pred_empty()) 943 return false; 944 for (MachineBasicBlock::const_reverse_iterator I(MInsn); I != MBB->rend(); ++I) 945 if (!(I->isDebugValue() || I->getFlag(MachineInstr::FrameSetup))) 946 return false; 947 return true; 948 } 949 950 // Find variables for each lexical scope. 951 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, 952 const DISubprogram *SP, 953 DenseSet<InlinedVariable> &Processed) { 954 // Grab the variable info that was squirreled away in the MMI side-table. 955 collectVariableInfoFromMMITable(Processed); 956 957 for (const auto &I : DbgValues) { 958 InlinedVariable IV = I.first; 959 if (Processed.count(IV)) 960 continue; 961 962 // Instruction ranges, specifying where IV is accessible. 963 const auto &Ranges = I.second; 964 if (Ranges.empty()) 965 continue; 966 967 LexicalScope *Scope = nullptr; 968 if (const DILocation *IA = IV.second) 969 Scope = LScopes.findInlinedScope(IV.first->getScope(), IA); 970 else 971 Scope = LScopes.findLexicalScope(IV.first->getScope()); 972 // If variable scope is not found then skip this variable. 973 if (!Scope) 974 continue; 975 976 Processed.insert(IV); 977 DbgVariable *RegVar = createConcreteVariable(*Scope, IV); 978 979 const MachineInstr *MInsn = Ranges.front().first; 980 assert(MInsn->isDebugValue() && "History must begin with debug value"); 981 982 // Check if there is a single DBG_VALUE, valid throughout the function. 983 // A single constant is also considered valid for the entire function. 984 if (Ranges.size() == 1 && 985 (MInsn->getOperand(0).isImm() || 986 (validAtEntry(MInsn) && Ranges.front().second == nullptr))) { 987 RegVar->initializeDbgValue(MInsn); 988 continue; 989 } 990 991 // Handle multiple DBG_VALUE instructions describing one variable. 992 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn); 993 994 // Build the location list for this variable. 995 SmallVector<DebugLocEntry, 8> Entries; 996 buildLocationList(Entries, Ranges); 997 998 // If the variable has a DIBasicType, extract it. Basic types cannot have 999 // unique identifiers, so don't bother resolving the type with the 1000 // identifier map. 1001 const DIBasicType *BT = dyn_cast<DIBasicType>( 1002 static_cast<const Metadata *>(IV.first->getType())); 1003 1004 // Finalize the entry by lowering it into a DWARF bytestream. 1005 for (auto &Entry : Entries) 1006 Entry.finalize(*Asm, List, BT); 1007 } 1008 1009 // Collect info for variables that were optimized out. 1010 for (const DILocalVariable *DV : SP->getVariables()) { 1011 if (Processed.insert(InlinedVariable(DV, nullptr)).second) 1012 if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope())) 1013 createConcreteVariable(*Scope, InlinedVariable(DV, nullptr)); 1014 } 1015 } 1016 1017 // Process beginning of an instruction. 1018 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1019 DebugHandlerBase::beginInstruction(MI); 1020 assert(CurMI); 1021 1022 // Check if source location changes, but ignore DBG_VALUE locations. 1023 if (!MI->isDebugValue()) { 1024 DebugLoc DL = MI->getDebugLoc(); 1025 if (DL != PrevInstLoc) { 1026 if (DL) { 1027 unsigned Flags = 0; 1028 PrevInstLoc = DL; 1029 if (DL == PrologEndLoc) { 1030 Flags |= DWARF2_FLAG_PROLOGUE_END; 1031 PrologEndLoc = DebugLoc(); 1032 Flags |= DWARF2_FLAG_IS_STMT; 1033 } 1034 if (DL.getLine() != 1035 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine()) 1036 Flags |= DWARF2_FLAG_IS_STMT; 1037 1038 const MDNode *Scope = DL.getScope(); 1039 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1040 } else if (UnknownLocations) { 1041 PrevInstLoc = DL; 1042 recordSourceLine(0, 0, nullptr, 0); 1043 } 1044 } 1045 } 1046 } 1047 1048 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) { 1049 // First known non-DBG_VALUE and non-frame setup location marks 1050 // the beginning of the function body. 1051 for (const auto &MBB : *MF) 1052 for (const auto &MI : MBB) 1053 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) && 1054 MI.getDebugLoc()) 1055 return MI.getDebugLoc(); 1056 return DebugLoc(); 1057 } 1058 1059 // Gather pre-function debug information. Assumes being called immediately 1060 // after the function entry point has been emitted. 1061 void DwarfDebug::beginFunction(const MachineFunction *MF) { 1062 CurFn = MF; 1063 1064 // If there's no debug info for the function we're not going to do anything. 1065 if (!MMI->hasDebugInfo()) 1066 return; 1067 1068 auto DI = MF->getFunction()->getSubprogram(); 1069 if (!DI) 1070 return; 1071 1072 // Grab the lexical scopes for the function, if we don't have any of those 1073 // then we're not going to be able to do anything. 1074 DebugHandlerBase::beginFunction(MF); 1075 if (LScopes.empty()) 1076 return; 1077 1078 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1079 // belongs to so that we add to the correct per-cu line table in the 1080 // non-asm case. 1081 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1082 // FnScope->getScopeNode() and DI->second should represent the same function, 1083 // though they may not be the same MDNode due to inline functions merged in 1084 // LTO where the debug info metadata still differs (either due to distinct 1085 // written differences - two versions of a linkonce_odr function 1086 // written/copied into two separate files, or some sub-optimal metadata that 1087 // isn't structurally identical (see: file path/name info from clang, which 1088 // includes the directory of the cpp file being built, even when the file name 1089 // is absolute (such as an <> lookup header))) 1090 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode()); 1091 assert(TheCU && "Unable to find compile unit!"); 1092 if (Asm->OutStreamer->hasRawTextSupport()) 1093 // Use a single line table if we are generating assembly. 1094 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1095 else 1096 Asm->OutStreamer->getContext().setDwarfCompileUnitID(TheCU->getUniqueID()); 1097 1098 // Record beginning of function. 1099 PrologEndLoc = findPrologueEndLoc(MF); 1100 if (DILocation *L = PrologEndLoc) { 1101 // We'd like to list the prologue as "not statements" but GDB behaves 1102 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1103 auto *SP = L->getInlinedAtScope()->getSubprogram(); 1104 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT); 1105 } 1106 } 1107 1108 // Gather and emit post-function debug information. 1109 void DwarfDebug::endFunction(const MachineFunction *MF) { 1110 assert(CurFn == MF && 1111 "endFunction should be called with the same function as beginFunction"); 1112 1113 if (!MMI->hasDebugInfo() || LScopes.empty() || 1114 !MF->getFunction()->getSubprogram()) { 1115 // If we don't have a lexical scope for this function then there will 1116 // be a hole in the range information. Keep note of this by setting the 1117 // previously used section to nullptr. 1118 PrevCU = nullptr; 1119 CurFn = nullptr; 1120 DebugHandlerBase::endFunction(MF); 1121 return; 1122 } 1123 1124 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1125 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0); 1126 1127 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1128 auto *SP = cast<DISubprogram>(FnScope->getScopeNode()); 1129 DwarfCompileUnit &TheCU = *SPMap.lookup(SP); 1130 1131 DenseSet<InlinedVariable> ProcessedVars; 1132 collectVariableInfo(TheCU, SP, ProcessedVars); 1133 1134 // Add the range of this function to the list of ranges for the CU. 1135 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd())); 1136 1137 // Under -gmlt, skip building the subprogram if there are no inlined 1138 // subroutines inside it. 1139 if (TheCU.getCUNode()->getEmissionKind() == DIBuilder::LineTablesOnly && 1140 LScopes.getAbstractScopesList().empty() && !IsDarwin) { 1141 assert(InfoHolder.getScopeVariables().empty()); 1142 assert(DbgValues.empty()); 1143 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed 1144 // by a -gmlt CU. Add a test and remove this assertion. 1145 assert(AbstractVariables.empty()); 1146 PrevLabel = nullptr; 1147 CurFn = nullptr; 1148 DebugHandlerBase::endFunction(MF); 1149 return; 1150 } 1151 1152 #ifndef NDEBUG 1153 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size(); 1154 #endif 1155 // Construct abstract scopes. 1156 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1157 auto *SP = cast<DISubprogram>(AScope->getScopeNode()); 1158 // Collect info for variables that were optimized out. 1159 for (const DILocalVariable *DV : SP->getVariables()) { 1160 if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second) 1161 continue; 1162 ensureAbstractVariableIsCreated(InlinedVariable(DV, nullptr), 1163 DV->getScope()); 1164 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes 1165 && "ensureAbstractVariableIsCreated inserted abstract scopes"); 1166 } 1167 constructAbstractSubprogramScopeDIE(AScope); 1168 } 1169 1170 TheCU.constructSubprogramScopeDIE(FnScope); 1171 if (auto *SkelCU = TheCU.getSkeleton()) 1172 if (!LScopes.getAbstractScopesList().empty()) 1173 SkelCU->constructSubprogramScopeDIE(FnScope); 1174 1175 // Clear debug info 1176 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the 1177 // DbgVariables except those that are also in AbstractVariables (since they 1178 // can be used cross-function) 1179 InfoHolder.getScopeVariables().clear(); 1180 PrevLabel = nullptr; 1181 CurFn = nullptr; 1182 DebugHandlerBase::endFunction(MF); 1183 } 1184 1185 // Register a source line with debug info. Returns the unique label that was 1186 // emitted and which provides correspondence to the source line list. 1187 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1188 unsigned Flags) { 1189 StringRef Fn; 1190 StringRef Dir; 1191 unsigned Src = 1; 1192 unsigned Discriminator = 0; 1193 if (auto *Scope = cast_or_null<DIScope>(S)) { 1194 Fn = Scope->getFilename(); 1195 Dir = Scope->getDirectory(); 1196 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope)) 1197 Discriminator = LBF->getDiscriminator(); 1198 1199 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID(); 1200 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID]) 1201 .getOrCreateSourceID(Fn, Dir); 1202 } 1203 Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 1204 Discriminator, Fn); 1205 } 1206 1207 //===----------------------------------------------------------------------===// 1208 // Emit Methods 1209 //===----------------------------------------------------------------------===// 1210 1211 // Emit the debug info section. 1212 void DwarfDebug::emitDebugInfo() { 1213 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1214 Holder.emitUnits(/* UseOffsets */ false); 1215 } 1216 1217 // Emit the abbreviation section. 1218 void DwarfDebug::emitAbbreviations() { 1219 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1220 1221 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1222 } 1223 1224 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section, 1225 StringRef TableName) { 1226 Accel.FinalizeTable(Asm, TableName); 1227 Asm->OutStreamer->SwitchSection(Section); 1228 1229 // Emit the full data. 1230 Accel.emit(Asm, Section->getBeginSymbol(), this); 1231 } 1232 1233 // Emit visible names into a hashed accelerator table section. 1234 void DwarfDebug::emitAccelNames() { 1235 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(), 1236 "Names"); 1237 } 1238 1239 // Emit objective C classes and categories into a hashed accelerator table 1240 // section. 1241 void DwarfDebug::emitAccelObjC() { 1242 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(), 1243 "ObjC"); 1244 } 1245 1246 // Emit namespace dies into a hashed accelerator table. 1247 void DwarfDebug::emitAccelNamespaces() { 1248 emitAccel(AccelNamespace, 1249 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(), 1250 "namespac"); 1251 } 1252 1253 // Emit type dies into a hashed accelerator table. 1254 void DwarfDebug::emitAccelTypes() { 1255 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(), 1256 "types"); 1257 } 1258 1259 // Public name handling. 1260 // The format for the various pubnames: 1261 // 1262 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 1263 // for the DIE that is named. 1264 // 1265 // gnu pubnames - offset/index value/name tuples where the offset is the offset 1266 // into the CU and the index value is computed according to the type of value 1267 // for the DIE that is named. 1268 // 1269 // For type units the offset is the offset of the skeleton DIE. For split dwarf 1270 // it's the offset within the debug_info/debug_types dwo section, however, the 1271 // reference in the pubname header doesn't change. 1272 1273 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 1274 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 1275 const DIE *Die) { 1276 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 1277 1278 // We could have a specification DIE that has our most of our knowledge, 1279 // look for that now. 1280 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) { 1281 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry(); 1282 if (SpecDIE.findAttribute(dwarf::DW_AT_external)) 1283 Linkage = dwarf::GIEL_EXTERNAL; 1284 } else if (Die->findAttribute(dwarf::DW_AT_external)) 1285 Linkage = dwarf::GIEL_EXTERNAL; 1286 1287 switch (Die->getTag()) { 1288 case dwarf::DW_TAG_class_type: 1289 case dwarf::DW_TAG_structure_type: 1290 case dwarf::DW_TAG_union_type: 1291 case dwarf::DW_TAG_enumeration_type: 1292 return dwarf::PubIndexEntryDescriptor( 1293 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 1294 ? dwarf::GIEL_STATIC 1295 : dwarf::GIEL_EXTERNAL); 1296 case dwarf::DW_TAG_typedef: 1297 case dwarf::DW_TAG_base_type: 1298 case dwarf::DW_TAG_subrange_type: 1299 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 1300 case dwarf::DW_TAG_namespace: 1301 return dwarf::GIEK_TYPE; 1302 case dwarf::DW_TAG_subprogram: 1303 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 1304 case dwarf::DW_TAG_variable: 1305 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 1306 case dwarf::DW_TAG_enumerator: 1307 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 1308 dwarf::GIEL_STATIC); 1309 default: 1310 return dwarf::GIEK_NONE; 1311 } 1312 } 1313 1314 /// emitDebugPubNames - Emit visible names into a debug pubnames section. 1315 /// 1316 void DwarfDebug::emitDebugPubNames(bool GnuStyle) { 1317 MCSection *PSec = GnuStyle 1318 ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 1319 : Asm->getObjFileLowering().getDwarfPubNamesSection(); 1320 1321 emitDebugPubSection(GnuStyle, PSec, "Names", 1322 &DwarfCompileUnit::getGlobalNames); 1323 } 1324 1325 void DwarfDebug::emitDebugPubSection( 1326 bool GnuStyle, MCSection *PSec, StringRef Name, 1327 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) { 1328 for (const auto &NU : CUMap) { 1329 DwarfCompileUnit *TheU = NU.second; 1330 1331 const auto &Globals = (TheU->*Accessor)(); 1332 1333 if (Globals.empty()) 1334 continue; 1335 1336 if (auto *Skeleton = TheU->getSkeleton()) 1337 TheU = Skeleton; 1338 1339 // Start the dwarf pubnames section. 1340 Asm->OutStreamer->SwitchSection(PSec); 1341 1342 // Emit the header. 1343 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info"); 1344 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin"); 1345 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end"); 1346 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 1347 1348 Asm->OutStreamer->EmitLabel(BeginLabel); 1349 1350 Asm->OutStreamer->AddComment("DWARF Version"); 1351 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); 1352 1353 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info"); 1354 Asm->emitDwarfSymbolReference(TheU->getLabelBegin()); 1355 1356 Asm->OutStreamer->AddComment("Compilation Unit Length"); 1357 Asm->EmitInt32(TheU->getLength()); 1358 1359 // Emit the pubnames for this compilation unit. 1360 for (const auto &GI : Globals) { 1361 const char *Name = GI.getKeyData(); 1362 const DIE *Entity = GI.second; 1363 1364 Asm->OutStreamer->AddComment("DIE offset"); 1365 Asm->EmitInt32(Entity->getOffset()); 1366 1367 if (GnuStyle) { 1368 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 1369 Asm->OutStreamer->AddComment( 1370 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " + 1371 dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 1372 Asm->EmitInt8(Desc.toBits()); 1373 } 1374 1375 Asm->OutStreamer->AddComment("External Name"); 1376 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 1377 } 1378 1379 Asm->OutStreamer->AddComment("End Mark"); 1380 Asm->EmitInt32(0); 1381 Asm->OutStreamer->EmitLabel(EndLabel); 1382 } 1383 } 1384 1385 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) { 1386 MCSection *PSec = GnuStyle 1387 ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 1388 : Asm->getObjFileLowering().getDwarfPubTypesSection(); 1389 1390 emitDebugPubSection(GnuStyle, PSec, "Types", 1391 &DwarfCompileUnit::getGlobalTypes); 1392 } 1393 1394 /// Emit null-terminated strings into a debug str section. 1395 void DwarfDebug::emitDebugStr() { 1396 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1397 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection()); 1398 } 1399 1400 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 1401 const DebugLocStream::Entry &Entry) { 1402 auto &&Comments = DebugLocs.getComments(Entry); 1403 auto Comment = Comments.begin(); 1404 auto End = Comments.end(); 1405 for (uint8_t Byte : DebugLocs.getBytes(Entry)) 1406 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : ""); 1407 } 1408 1409 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, 1410 ByteStreamer &Streamer, 1411 const DebugLocEntry::Value &Value, 1412 unsigned PieceOffsetInBits) { 1413 DebugLocDwarfExpression DwarfExpr(*AP.MF->getSubtarget().getRegisterInfo(), 1414 AP.getDwarfDebug()->getDwarfVersion(), 1415 Streamer); 1416 // Regular entry. 1417 if (Value.isInt()) { 1418 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed || 1419 BT->getEncoding() == dwarf::DW_ATE_signed_char)) 1420 DwarfExpr.AddSignedConstant(Value.getInt()); 1421 else 1422 DwarfExpr.AddUnsignedConstant(Value.getInt()); 1423 } else if (Value.isLocation()) { 1424 MachineLocation Loc = Value.getLoc(); 1425 const DIExpression *Expr = Value.getExpression(); 1426 if (!Expr || !Expr->getNumElements()) 1427 // Regular entry. 1428 AP.EmitDwarfRegOp(Streamer, Loc); 1429 else { 1430 // Complex address entry. 1431 if (Loc.getOffset()) { 1432 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset()); 1433 DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end(), 1434 PieceOffsetInBits); 1435 } else 1436 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(), 1437 PieceOffsetInBits); 1438 } 1439 } 1440 // else ... ignore constant fp. There is not any good way to 1441 // to represent them here in dwarf. 1442 // FIXME: ^ 1443 } 1444 1445 void DebugLocEntry::finalize(const AsmPrinter &AP, 1446 DebugLocStream::ListBuilder &List, 1447 const DIBasicType *BT) { 1448 DebugLocStream::EntryBuilder Entry(List, Begin, End); 1449 BufferByteStreamer Streamer = Entry.getStreamer(); 1450 const DebugLocEntry::Value &Value = Values[0]; 1451 if (Value.isBitPiece()) { 1452 // Emit all pieces that belong to the same variable and range. 1453 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) { 1454 return P.isBitPiece(); 1455 }) && "all values are expected to be pieces"); 1456 assert(std::is_sorted(Values.begin(), Values.end()) && 1457 "pieces are expected to be sorted"); 1458 1459 unsigned Offset = 0; 1460 for (auto Piece : Values) { 1461 const DIExpression *Expr = Piece.getExpression(); 1462 unsigned PieceOffset = Expr->getBitPieceOffset(); 1463 unsigned PieceSize = Expr->getBitPieceSize(); 1464 assert(Offset <= PieceOffset && "overlapping or duplicate pieces"); 1465 if (Offset < PieceOffset) { 1466 // The DWARF spec seriously mandates pieces with no locations for gaps. 1467 DebugLocDwarfExpression Expr(*AP.MF->getSubtarget().getRegisterInfo(), 1468 AP.getDwarfDebug()->getDwarfVersion(), 1469 Streamer); 1470 Expr.AddOpPiece(PieceOffset-Offset, 0); 1471 Offset += PieceOffset-Offset; 1472 } 1473 Offset += PieceSize; 1474 1475 emitDebugLocValue(AP, BT, Streamer, Piece, PieceOffset); 1476 } 1477 } else { 1478 assert(Values.size() == 1 && "only pieces may have >1 value"); 1479 emitDebugLocValue(AP, BT, Streamer, Value, 0); 1480 } 1481 } 1482 1483 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) { 1484 // Emit the size. 1485 Asm->OutStreamer->AddComment("Loc expr size"); 1486 Asm->EmitInt16(DebugLocs.getBytes(Entry).size()); 1487 1488 // Emit the entry. 1489 APByteStreamer Streamer(*Asm); 1490 emitDebugLocEntry(Streamer, Entry); 1491 } 1492 1493 // Emit locations into the debug loc section. 1494 void DwarfDebug::emitDebugLoc() { 1495 // Start the dwarf loc section. 1496 Asm->OutStreamer->SwitchSection( 1497 Asm->getObjFileLowering().getDwarfLocSection()); 1498 unsigned char Size = Asm->getDataLayout().getPointerSize(); 1499 for (const auto &List : DebugLocs.getLists()) { 1500 Asm->OutStreamer->EmitLabel(List.Label); 1501 const DwarfCompileUnit *CU = List.CU; 1502 for (const auto &Entry : DebugLocs.getEntries(List)) { 1503 // Set up the range. This range is relative to the entry point of the 1504 // compile unit. This is a hard coded 0 for low_pc when we're emitting 1505 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 1506 if (auto *Base = CU->getBaseAddress()) { 1507 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size); 1508 Asm->EmitLabelDifference(Entry.EndSym, Base, Size); 1509 } else { 1510 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size); 1511 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size); 1512 } 1513 1514 emitDebugLocEntryLocation(Entry); 1515 } 1516 Asm->OutStreamer->EmitIntValue(0, Size); 1517 Asm->OutStreamer->EmitIntValue(0, Size); 1518 } 1519 } 1520 1521 void DwarfDebug::emitDebugLocDWO() { 1522 Asm->OutStreamer->SwitchSection( 1523 Asm->getObjFileLowering().getDwarfLocDWOSection()); 1524 for (const auto &List : DebugLocs.getLists()) { 1525 Asm->OutStreamer->EmitLabel(List.Label); 1526 for (const auto &Entry : DebugLocs.getEntries(List)) { 1527 // Just always use start_length for now - at least that's one address 1528 // rather than two. We could get fancier and try to, say, reuse an 1529 // address we know we've emitted elsewhere (the start of the function? 1530 // The start of the CU or CU subrange that encloses this range?) 1531 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry); 1532 unsigned idx = AddrPool.getIndex(Entry.BeginSym); 1533 Asm->EmitULEB128(idx); 1534 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4); 1535 1536 emitDebugLocEntryLocation(Entry); 1537 } 1538 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry); 1539 } 1540 } 1541 1542 struct ArangeSpan { 1543 const MCSymbol *Start, *End; 1544 }; 1545 1546 // Emit a debug aranges section, containing a CU lookup for any 1547 // address we can tie back to a CU. 1548 void DwarfDebug::emitDebugARanges() { 1549 // Provides a unique id per text section. 1550 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap; 1551 1552 // Filter labels by section. 1553 for (const SymbolCU &SCU : ArangeLabels) { 1554 if (SCU.Sym->isInSection()) { 1555 // Make a note of this symbol and it's section. 1556 MCSection *Section = &SCU.Sym->getSection(); 1557 if (!Section->getKind().isMetadata()) 1558 SectionMap[Section].push_back(SCU); 1559 } else { 1560 // Some symbols (e.g. common/bss on mach-o) can have no section but still 1561 // appear in the output. This sucks as we rely on sections to build 1562 // arange spans. We can do it without, but it's icky. 1563 SectionMap[nullptr].push_back(SCU); 1564 } 1565 } 1566 1567 // Add terminating symbols for each section. 1568 for (const auto &I : SectionMap) { 1569 MCSection *Section = I.first; 1570 MCSymbol *Sym = nullptr; 1571 1572 if (Section) 1573 Sym = Asm->OutStreamer->endSection(Section); 1574 1575 // Insert a final terminator. 1576 SectionMap[Section].push_back(SymbolCU(nullptr, Sym)); 1577 } 1578 1579 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans; 1580 1581 for (auto &I : SectionMap) { 1582 const MCSection *Section = I.first; 1583 SmallVector<SymbolCU, 8> &List = I.second; 1584 if (List.size() < 2) 1585 continue; 1586 1587 // If we have no section (e.g. common), just write out 1588 // individual spans for each symbol. 1589 if (!Section) { 1590 for (const SymbolCU &Cur : List) { 1591 ArangeSpan Span; 1592 Span.Start = Cur.Sym; 1593 Span.End = nullptr; 1594 if (Cur.CU) 1595 Spans[Cur.CU].push_back(Span); 1596 } 1597 continue; 1598 } 1599 1600 // Sort the symbols by offset within the section. 1601 std::sort(List.begin(), List.end(), 1602 [&](const SymbolCU &A, const SymbolCU &B) { 1603 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0; 1604 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0; 1605 1606 // Symbols with no order assigned should be placed at the end. 1607 // (e.g. section end labels) 1608 if (IA == 0) 1609 return false; 1610 if (IB == 0) 1611 return true; 1612 return IA < IB; 1613 }); 1614 1615 // Build spans between each label. 1616 const MCSymbol *StartSym = List[0].Sym; 1617 for (size_t n = 1, e = List.size(); n < e; n++) { 1618 const SymbolCU &Prev = List[n - 1]; 1619 const SymbolCU &Cur = List[n]; 1620 1621 // Try and build the longest span we can within the same CU. 1622 if (Cur.CU != Prev.CU) { 1623 ArangeSpan Span; 1624 Span.Start = StartSym; 1625 Span.End = Cur.Sym; 1626 Spans[Prev.CU].push_back(Span); 1627 StartSym = Cur.Sym; 1628 } 1629 } 1630 } 1631 1632 // Start the dwarf aranges section. 1633 Asm->OutStreamer->SwitchSection( 1634 Asm->getObjFileLowering().getDwarfARangesSection()); 1635 1636 unsigned PtrSize = Asm->getDataLayout().getPointerSize(); 1637 1638 // Build a list of CUs used. 1639 std::vector<DwarfCompileUnit *> CUs; 1640 for (const auto &it : Spans) { 1641 DwarfCompileUnit *CU = it.first; 1642 CUs.push_back(CU); 1643 } 1644 1645 // Sort the CU list (again, to ensure consistent output order). 1646 std::sort(CUs.begin(), CUs.end(), 1647 [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) { 1648 return A->getUniqueID() < B->getUniqueID(); 1649 }); 1650 1651 // Emit an arange table for each CU we used. 1652 for (DwarfCompileUnit *CU : CUs) { 1653 std::vector<ArangeSpan> &List = Spans[CU]; 1654 1655 // Describe the skeleton CU's offset and length, not the dwo file's. 1656 if (auto *Skel = CU->getSkeleton()) 1657 CU = Skel; 1658 1659 // Emit size of content not including length itself. 1660 unsigned ContentSize = 1661 sizeof(int16_t) + // DWARF ARange version number 1662 sizeof(int32_t) + // Offset of CU in the .debug_info section 1663 sizeof(int8_t) + // Pointer Size (in bytes) 1664 sizeof(int8_t); // Segment Size (in bytes) 1665 1666 unsigned TupleSize = PtrSize * 2; 1667 1668 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 1669 unsigned Padding = 1670 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 1671 1672 ContentSize += Padding; 1673 ContentSize += (List.size() + 1) * TupleSize; 1674 1675 // For each compile unit, write the list of spans it covers. 1676 Asm->OutStreamer->AddComment("Length of ARange Set"); 1677 Asm->EmitInt32(ContentSize); 1678 Asm->OutStreamer->AddComment("DWARF Arange version number"); 1679 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); 1680 Asm->OutStreamer->AddComment("Offset Into Debug Info Section"); 1681 Asm->emitDwarfSymbolReference(CU->getLabelBegin()); 1682 Asm->OutStreamer->AddComment("Address Size (in bytes)"); 1683 Asm->EmitInt8(PtrSize); 1684 Asm->OutStreamer->AddComment("Segment Size (in bytes)"); 1685 Asm->EmitInt8(0); 1686 1687 Asm->OutStreamer->EmitFill(Padding, 0xff); 1688 1689 for (const ArangeSpan &Span : List) { 1690 Asm->EmitLabelReference(Span.Start, PtrSize); 1691 1692 // Calculate the size as being from the span start to it's end. 1693 if (Span.End) { 1694 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 1695 } else { 1696 // For symbols without an end marker (e.g. common), we 1697 // write a single arange entry containing just that one symbol. 1698 uint64_t Size = SymSize[Span.Start]; 1699 if (Size == 0) 1700 Size = 1; 1701 1702 Asm->OutStreamer->EmitIntValue(Size, PtrSize); 1703 } 1704 } 1705 1706 Asm->OutStreamer->AddComment("ARange terminator"); 1707 Asm->OutStreamer->EmitIntValue(0, PtrSize); 1708 Asm->OutStreamer->EmitIntValue(0, PtrSize); 1709 } 1710 } 1711 1712 /// Emit address ranges into a debug ranges section. 1713 void DwarfDebug::emitDebugRanges() { 1714 // Start the dwarf ranges section. 1715 Asm->OutStreamer->SwitchSection( 1716 Asm->getObjFileLowering().getDwarfRangesSection()); 1717 1718 // Size for our labels. 1719 unsigned char Size = Asm->getDataLayout().getPointerSize(); 1720 1721 // Grab the specific ranges for the compile units in the module. 1722 for (const auto &I : CUMap) { 1723 DwarfCompileUnit *TheCU = I.second; 1724 1725 if (auto *Skel = TheCU->getSkeleton()) 1726 TheCU = Skel; 1727 1728 // Iterate over the misc ranges for the compile units in the module. 1729 for (const RangeSpanList &List : TheCU->getRangeLists()) { 1730 // Emit our symbol so we can find the beginning of the range. 1731 Asm->OutStreamer->EmitLabel(List.getSym()); 1732 1733 for (const RangeSpan &Range : List.getRanges()) { 1734 const MCSymbol *Begin = Range.getStart(); 1735 const MCSymbol *End = Range.getEnd(); 1736 assert(Begin && "Range without a begin symbol?"); 1737 assert(End && "Range without an end symbol?"); 1738 if (auto *Base = TheCU->getBaseAddress()) { 1739 Asm->EmitLabelDifference(Begin, Base, Size); 1740 Asm->EmitLabelDifference(End, Base, Size); 1741 } else { 1742 Asm->OutStreamer->EmitSymbolValue(Begin, Size); 1743 Asm->OutStreamer->EmitSymbolValue(End, Size); 1744 } 1745 } 1746 1747 // And terminate the list with two 0 values. 1748 Asm->OutStreamer->EmitIntValue(0, Size); 1749 Asm->OutStreamer->EmitIntValue(0, Size); 1750 } 1751 } 1752 } 1753 1754 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) { 1755 for (auto *MN : Nodes) { 1756 if (auto *M = dyn_cast<DIMacro>(MN)) 1757 emitMacro(*M); 1758 else if (auto *F = dyn_cast<DIMacroFile>(MN)) 1759 emitMacroFile(*F, U); 1760 else 1761 llvm_unreachable("Unexpected DI type!"); 1762 } 1763 } 1764 1765 void DwarfDebug::emitMacro(DIMacro &M) { 1766 Asm->EmitULEB128(M.getMacinfoType()); 1767 Asm->EmitULEB128(M.getLine()); 1768 StringRef Name = M.getName(); 1769 StringRef Value = M.getValue(); 1770 Asm->OutStreamer->EmitBytes(Name); 1771 if (!Value.empty()) { 1772 // There should be one space between macro name and macro value. 1773 Asm->EmitInt8(' '); 1774 Asm->OutStreamer->EmitBytes(Value); 1775 } 1776 Asm->EmitInt8('\0'); 1777 } 1778 1779 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) { 1780 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file); 1781 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file); 1782 Asm->EmitULEB128(F.getLine()); 1783 DIFile *File = F.getFile(); 1784 unsigned FID = 1785 U.getOrCreateSourceID(File->getFilename(), File->getDirectory()); 1786 Asm->EmitULEB128(FID); 1787 handleMacroNodes(F.getElements(), U); 1788 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file); 1789 } 1790 1791 /// Emit macros into a debug macinfo section. 1792 void DwarfDebug::emitDebugMacinfo() { 1793 // Start the dwarf macinfo section. 1794 Asm->OutStreamer->SwitchSection( 1795 Asm->getObjFileLowering().getDwarfMacinfoSection()); 1796 1797 for (const auto &P : CUMap) { 1798 auto &TheCU = *P.second; 1799 auto *SkCU = TheCU.getSkeleton(); 1800 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU; 1801 auto *CUNode = cast<DICompileUnit>(P.first); 1802 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin()); 1803 handleMacroNodes(CUNode->getMacros(), U); 1804 } 1805 Asm->OutStreamer->AddComment("End Of Macro List Mark"); 1806 Asm->EmitInt8(0); 1807 } 1808 1809 // DWARF5 Experimental Separate Dwarf emitters. 1810 1811 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die, 1812 std::unique_ptr<DwarfCompileUnit> NewU) { 1813 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name, 1814 U.getCUNode()->getSplitDebugFilename()); 1815 1816 if (!CompilationDir.empty()) 1817 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 1818 1819 addGnuPubAttributes(*NewU, Die); 1820 1821 SkeletonHolder.addUnit(std::move(NewU)); 1822 } 1823 1824 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list, 1825 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id, 1826 // DW_AT_addr_base, DW_AT_ranges_base. 1827 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) { 1828 1829 auto OwnedUnit = make_unique<DwarfCompileUnit>( 1830 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder); 1831 DwarfCompileUnit &NewCU = *OwnedUnit; 1832 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection()); 1833 1834 NewCU.initStmtList(); 1835 1836 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit)); 1837 1838 return NewCU; 1839 } 1840 1841 // Emit the .debug_info.dwo section for separated dwarf. This contains the 1842 // compile units that would normally be in debug_info. 1843 void DwarfDebug::emitDebugInfoDWO() { 1844 assert(useSplitDwarf() && "No split dwarf debug info?"); 1845 // Don't emit relocations into the dwo file. 1846 InfoHolder.emitUnits(/* UseOffsets */ true); 1847 } 1848 1849 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 1850 // abbreviations for the .debug_info.dwo section. 1851 void DwarfDebug::emitDebugAbbrevDWO() { 1852 assert(useSplitDwarf() && "No split dwarf?"); 1853 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 1854 } 1855 1856 void DwarfDebug::emitDebugLineDWO() { 1857 assert(useSplitDwarf() && "No split dwarf?"); 1858 Asm->OutStreamer->SwitchSection( 1859 Asm->getObjFileLowering().getDwarfLineDWOSection()); 1860 SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams()); 1861 } 1862 1863 // Emit the .debug_str.dwo section for separated dwarf. This contains the 1864 // string section and is identical in format to traditional .debug_str 1865 // sections. 1866 void DwarfDebug::emitDebugStrDWO() { 1867 assert(useSplitDwarf() && "No split dwarf?"); 1868 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 1869 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 1870 OffSec); 1871 } 1872 1873 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 1874 if (!useSplitDwarf()) 1875 return nullptr; 1876 if (SingleCU) 1877 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory()); 1878 return &SplitTypeUnitFileTable; 1879 } 1880 1881 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) { 1882 MD5 Hash; 1883 Hash.update(Identifier); 1884 // ... take the least significant 8 bytes and return those. Our MD5 1885 // implementation always returns its results in little endian, swap bytes 1886 // appropriately. 1887 MD5::MD5Result Result; 1888 Hash.final(Result); 1889 return support::endian::read64le(Result + 8); 1890 } 1891 1892 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 1893 StringRef Identifier, DIE &RefDie, 1894 const DICompositeType *CTy) { 1895 // Fast path if we're building some type units and one has already used the 1896 // address pool we know we're going to throw away all this work anyway, so 1897 // don't bother building dependent types. 1898 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed()) 1899 return; 1900 1901 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0)); 1902 if (!Ins.second) { 1903 CU.addDIETypeSignature(RefDie, Ins.first->second); 1904 return; 1905 } 1906 1907 bool TopLevelType = TypeUnitsUnderConstruction.empty(); 1908 AddrPool.resetUsedFlag(); 1909 1910 auto OwnedUnit = make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder, 1911 getDwoLineTable(CU)); 1912 DwarfTypeUnit &NewTU = *OwnedUnit; 1913 DIE &UnitDie = NewTU.getUnitDie(); 1914 TypeUnitsUnderConstruction.push_back( 1915 std::make_pair(std::move(OwnedUnit), CTy)); 1916 1917 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 1918 CU.getLanguage()); 1919 1920 uint64_t Signature = makeTypeSignature(Identifier); 1921 NewTU.setTypeSignature(Signature); 1922 Ins.first->second = Signature; 1923 1924 if (useSplitDwarf()) 1925 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection()); 1926 else { 1927 CU.applyStmtList(UnitDie); 1928 NewTU.initSection( 1929 Asm->getObjFileLowering().getDwarfTypesSection(Signature)); 1930 } 1931 1932 NewTU.setType(NewTU.createTypeDIE(CTy)); 1933 1934 if (TopLevelType) { 1935 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction); 1936 TypeUnitsUnderConstruction.clear(); 1937 1938 // Types referencing entries in the address table cannot be placed in type 1939 // units. 1940 if (AddrPool.hasBeenUsed()) { 1941 1942 // Remove all the types built while building this type. 1943 // This is pessimistic as some of these types might not be dependent on 1944 // the type that used an address. 1945 for (const auto &TU : TypeUnitsToAdd) 1946 TypeSignatures.erase(TU.second); 1947 1948 // Construct this type in the CU directly. 1949 // This is inefficient because all the dependent types will be rebuilt 1950 // from scratch, including building them in type units, discovering that 1951 // they depend on addresses, throwing them out and rebuilding them. 1952 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy)); 1953 return; 1954 } 1955 1956 // If the type wasn't dependent on fission addresses, finish adding the type 1957 // and all its dependent types. 1958 for (auto &TU : TypeUnitsToAdd) { 1959 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get()); 1960 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf()); 1961 } 1962 } 1963 CU.addDIETypeSignature(RefDie, Signature); 1964 } 1965 1966 // Accelerator table mutators - add each name along with its companion 1967 // DIE to the proper table while ensuring that the name that we're going 1968 // to reference is in the string table. We do this since the names we 1969 // add may not only be identical to the names in the DIE. 1970 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) { 1971 if (!useDwarfAccelTables()) 1972 return; 1973 AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 1974 } 1975 1976 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) { 1977 if (!useDwarfAccelTables()) 1978 return; 1979 AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 1980 } 1981 1982 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) { 1983 if (!useDwarfAccelTables()) 1984 return; 1985 AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 1986 } 1987 1988 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) { 1989 if (!useDwarfAccelTables()) 1990 return; 1991 AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die); 1992 } 1993