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