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