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 #define DEBUG_TYPE "dwarfdebug" 15 #include "ByteStreamer.h" 16 #include "DwarfDebug.h" 17 #include "DIE.h" 18 #include "DIEHash.h" 19 #include "DwarfAccelTable.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/MachineFunction.h" 26 #include "llvm/CodeGen/MachineModuleInfo.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DIBuilder.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/MCSection.h" 36 #include "llvm/MC/MCStreamer.h" 37 #include "llvm/MC/MCSymbol.h" 38 #include "llvm/Support/CommandLine.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/Dwarf.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/FormattedStream.h" 43 #include "llvm/Support/LEB128.h" 44 #include "llvm/Support/MD5.h" 45 #include "llvm/Support/Path.h" 46 #include "llvm/Support/Timer.h" 47 #include "llvm/Target/TargetFrameLowering.h" 48 #include "llvm/Target/TargetLoweringObjectFile.h" 49 #include "llvm/Target/TargetMachine.h" 50 #include "llvm/Target/TargetOptions.h" 51 #include "llvm/Target/TargetRegisterInfo.h" 52 using namespace llvm; 53 54 static cl::opt<bool> 55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, 56 cl::desc("Disable debug info printing")); 57 58 static cl::opt<bool> UnknownLocations( 59 "use-unknown-locations", cl::Hidden, 60 cl::desc("Make an absence of debug location information explicit."), 61 cl::init(false)); 62 63 static cl::opt<bool> 64 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden, 65 cl::desc("Generate GNU-style pubnames and pubtypes"), 66 cl::init(false)); 67 68 static cl::opt<bool> GenerateARangeSection("generate-arange-section", 69 cl::Hidden, 70 cl::desc("Generate dwarf aranges"), 71 cl::init(false)); 72 73 namespace { 74 enum DefaultOnOff { Default, Enable, Disable }; 75 } 76 77 static cl::opt<DefaultOnOff> 78 DwarfAccelTables("dwarf-accel-tables", cl::Hidden, 79 cl::desc("Output prototype dwarf accelerator tables."), 80 cl::values(clEnumVal(Default, "Default for platform"), 81 clEnumVal(Enable, "Enabled"), 82 clEnumVal(Disable, "Disabled"), clEnumValEnd), 83 cl::init(Default)); 84 85 static cl::opt<DefaultOnOff> 86 SplitDwarf("split-dwarf", cl::Hidden, 87 cl::desc("Output DWARF5 split debug info."), 88 cl::values(clEnumVal(Default, "Default for platform"), 89 clEnumVal(Enable, "Enabled"), 90 clEnumVal(Disable, "Disabled"), clEnumValEnd), 91 cl::init(Default)); 92 93 static cl::opt<DefaultOnOff> 94 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden, 95 cl::desc("Generate DWARF pubnames and pubtypes sections"), 96 cl::values(clEnumVal(Default, "Default for platform"), 97 clEnumVal(Enable, "Enabled"), 98 clEnumVal(Disable, "Disabled"), clEnumValEnd), 99 cl::init(Default)); 100 101 static cl::opt<unsigned> 102 DwarfVersionNumber("dwarf-version", cl::Hidden, 103 cl::desc("Generate DWARF for dwarf version."), cl::init(0)); 104 105 static const char *const DWARFGroupName = "DWARF Emission"; 106 static const char *const DbgTimerName = "DWARF Debug Writer"; 107 108 //===----------------------------------------------------------------------===// 109 110 namespace llvm { 111 112 /// resolve - Look in the DwarfDebug map for the MDNode that 113 /// corresponds to the reference. 114 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const { 115 return DD->resolve(Ref); 116 } 117 118 bool DbgVariable::isBlockByrefVariable() const { 119 assert(Var.isVariable() && "Invalid complex DbgVariable!"); 120 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap()); 121 } 122 123 124 DIType DbgVariable::getType() const { 125 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap()); 126 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 127 // addresses instead. 128 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) { 129 /* Byref variables, in Blocks, are declared by the programmer as 130 "SomeType VarName;", but the compiler creates a 131 __Block_byref_x_VarName struct, and gives the variable VarName 132 either the struct, or a pointer to the struct, as its type. This 133 is necessary for various behind-the-scenes things the compiler 134 needs to do with by-reference variables in blocks. 135 136 However, as far as the original *programmer* is concerned, the 137 variable should still have type 'SomeType', as originally declared. 138 139 The following function dives into the __Block_byref_x_VarName 140 struct to find the original type of the variable. This will be 141 passed back to the code generating the type for the Debug 142 Information Entry for the variable 'VarName'. 'VarName' will then 143 have the original type 'SomeType' in its debug information. 144 145 The original type 'SomeType' will be the type of the field named 146 'VarName' inside the __Block_byref_x_VarName struct. 147 148 NOTE: In order for this to not completely fail on the debugger 149 side, the Debug Information Entry for the variable VarName needs to 150 have a DW_AT_location that tells the debugger how to unwind through 151 the pointers and __Block_byref_x_VarName struct to find the actual 152 value of the variable. The function addBlockByrefType does this. */ 153 DIType subType = Ty; 154 uint16_t tag = Ty.getTag(); 155 156 if (tag == dwarf::DW_TAG_pointer_type) 157 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom()); 158 159 DIArray Elements = DICompositeType(subType).getTypeArray(); 160 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 161 DIDerivedType DT(Elements.getElement(i)); 162 if (getName() == DT.getName()) 163 return (resolve(DT.getTypeDerivedFrom())); 164 } 165 } 166 return Ty; 167 } 168 169 } // end llvm namespace 170 171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 172 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0), 173 InfoHolder(A, "info_string", DIEValueAllocator), 174 UsedNonDefaultText(false), 175 SkeletonHolder(A, "skel_string", DIEValueAllocator) { 176 177 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0; 178 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0; 179 DwarfAddrSectionSym = 0; 180 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0; 181 FunctionBeginSym = FunctionEndSym = 0; 182 CurFn = 0; 183 CurMI = 0; 184 185 // Turn on accelerator tables for Darwin by default, pubnames by 186 // default for non-Darwin, and handle split dwarf. 187 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin(); 188 189 if (DwarfAccelTables == Default) 190 HasDwarfAccelTables = IsDarwin; 191 else 192 HasDwarfAccelTables = DwarfAccelTables == Enable; 193 194 if (SplitDwarf == Default) 195 HasSplitDwarf = false; 196 else 197 HasSplitDwarf = SplitDwarf == Enable; 198 199 if (DwarfPubSections == Default) 200 HasDwarfPubSections = !IsDarwin; 201 else 202 HasDwarfPubSections = DwarfPubSections == Enable; 203 204 DwarfVersion = DwarfVersionNumber 205 ? DwarfVersionNumber 206 : MMI->getModule()->getDwarfVersion(); 207 208 { 209 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled); 210 beginModule(); 211 } 212 } 213 214 // Switch to the specified MCSection and emit an assembler 215 // temporary label to it if SymbolStem is specified. 216 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section, 217 const char *SymbolStem = 0) { 218 Asm->OutStreamer.SwitchSection(Section); 219 if (!SymbolStem) 220 return 0; 221 222 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem); 223 Asm->OutStreamer.EmitLabel(TmpSym); 224 return TmpSym; 225 } 226 227 DwarfFile::~DwarfFile() { 228 for (DwarfUnit *DU : CUs) 229 delete DU; 230 } 231 232 MCSymbol *DwarfFile::getStringPoolSym() { 233 return Asm->GetTempSymbol(StringPref); 234 } 235 236 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) { 237 std::pair<MCSymbol *, unsigned> &Entry = 238 StringPool.GetOrCreateValue(Str).getValue(); 239 if (Entry.first) 240 return Entry.first; 241 242 Entry.second = NextStringPoolNumber++; 243 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second); 244 } 245 246 unsigned DwarfFile::getStringPoolIndex(StringRef Str) { 247 std::pair<MCSymbol *, unsigned> &Entry = 248 StringPool.GetOrCreateValue(Str).getValue(); 249 if (Entry.first) 250 return Entry.second; 251 252 Entry.second = NextStringPoolNumber++; 253 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second); 254 return Entry.second; 255 } 256 257 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) { 258 std::pair<AddrPool::iterator, bool> P = AddressPool.insert( 259 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS))); 260 if (P.second) 261 ++NextAddrPoolNumber; 262 return P.first->second.Number; 263 } 264 265 // Define a unique number for the abbreviation. 266 // 267 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) { 268 // Check the set for priors. 269 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev); 270 271 // If it's newly added. 272 if (InSet == &Abbrev) { 273 // Add to abbreviation list. 274 Abbreviations.push_back(&Abbrev); 275 276 // Assign the vector position + 1 as its number. 277 Abbrev.setNumber(Abbreviations.size()); 278 } else { 279 // Assign existing abbreviation number. 280 Abbrev.setNumber(InSet->getNumber()); 281 } 282 } 283 284 static bool isObjCClass(StringRef Name) { 285 return Name.startswith("+") || Name.startswith("-"); 286 } 287 288 static bool hasObjCCategory(StringRef Name) { 289 if (!isObjCClass(Name)) 290 return false; 291 292 return Name.find(") ") != StringRef::npos; 293 } 294 295 static void getObjCClassCategory(StringRef In, StringRef &Class, 296 StringRef &Category) { 297 if (!hasObjCCategory(In)) { 298 Class = In.slice(In.find('[') + 1, In.find(' ')); 299 Category = ""; 300 return; 301 } 302 303 Class = In.slice(In.find('[') + 1, In.find('(')); 304 Category = In.slice(In.find('[') + 1, In.find(' ')); 305 return; 306 } 307 308 static StringRef getObjCMethodName(StringRef In) { 309 return In.slice(In.find(' ') + 1, In.find(']')); 310 } 311 312 // Helper for sorting sections into a stable output order. 313 static bool SectionSort(const MCSection *A, const MCSection *B) { 314 std::string LA = (A ? A->getLabelBeginName() : ""); 315 std::string LB = (B ? B->getLabelBeginName() : ""); 316 return LA < LB; 317 } 318 319 // Add the various names to the Dwarf accelerator table names. 320 // TODO: Determine whether or not we should add names for programs 321 // that do not have a DW_AT_name or DW_AT_linkage_name field - this 322 // is only slightly different than the lookup of non-standard ObjC names. 323 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) { 324 if (!SP.isDefinition()) 325 return; 326 TheU->addAccelName(SP.getName(), Die); 327 328 // If the linkage name is different than the name, go ahead and output 329 // that as well into the name table. 330 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName()) 331 TheU->addAccelName(SP.getLinkageName(), Die); 332 333 // If this is an Objective-C selector name add it to the ObjC accelerator 334 // too. 335 if (isObjCClass(SP.getName())) { 336 StringRef Class, Category; 337 getObjCClassCategory(SP.getName(), Class, Category); 338 TheU->addAccelObjC(Class, Die); 339 if (Category != "") 340 TheU->addAccelObjC(Category, Die); 341 // Also add the base method name to the name table. 342 TheU->addAccelName(getObjCMethodName(SP.getName()), Die); 343 } 344 } 345 346 /// isSubprogramContext - Return true if Context is either a subprogram 347 /// or another context nested inside a subprogram. 348 bool DwarfDebug::isSubprogramContext(const MDNode *Context) { 349 if (!Context) 350 return false; 351 DIDescriptor D(Context); 352 if (D.isSubprogram()) 353 return true; 354 if (D.isType()) 355 return isSubprogramContext(resolve(DIType(Context).getContext())); 356 return false; 357 } 358 359 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc 360 // and DW_AT_high_pc attributes. If there are global variables in this 361 // scope then create and insert DIEs for these variables. 362 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU, 363 DISubprogram SP) { 364 DIE *SPDie = SPCU->getDIE(SP); 365 366 assert(SPDie && "Unable to find subprogram DIE!"); 367 368 // If we're updating an abstract DIE, then we will be adding the children and 369 // object pointer later on. But what we don't want to do is process the 370 // concrete DIE twice. 371 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) { 372 // Pick up abstract subprogram DIE. 373 SPDie = 374 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie()); 375 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE); 376 } else { 377 DISubprogram SPDecl = SP.getFunctionDeclaration(); 378 if (!SPDecl.isSubprogram()) { 379 // There is not any need to generate specification DIE for a function 380 // defined at compile unit level. If a function is defined inside another 381 // function then gdb prefers the definition at top level and but does not 382 // expect specification DIE in parent function. So avoid creating 383 // specification DIE for a function defined inside a function. 384 DIScope SPContext = resolve(SP.getContext()); 385 if (SP.isDefinition() && !SPContext.isCompileUnit() && 386 !SPContext.isFile() && !isSubprogramContext(SPContext)) { 387 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration); 388 389 // Add arguments. 390 DICompositeType SPTy = SP.getType(); 391 DIArray Args = SPTy.getTypeArray(); 392 uint16_t SPTag = SPTy.getTag(); 393 if (SPTag == dwarf::DW_TAG_subroutine_type) 394 SPCU->constructSubprogramArguments(*SPDie, Args); 395 DIE *SPDeclDie = SPDie; 396 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, 397 *SPCU->getUnitDie()); 398 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie); 399 } 400 } 401 } 402 403 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym); 404 405 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo(); 406 MachineLocation Location(RI->getFrameRegister(*Asm->MF)); 407 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location); 408 409 // Add name to the name table, we do this here because we're guaranteed 410 // to have concrete versions of our DW_TAG_subprogram nodes. 411 addSubprogramNames(SPCU, SP, SPDie); 412 413 return SPDie; 414 } 415 416 /// Check whether we should create a DIE for the given Scope, return true 417 /// if we don't create a DIE (the corresponding DIE is null). 418 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) { 419 if (Scope->isAbstractScope()) 420 return false; 421 422 // We don't create a DIE if there is no Range. 423 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges(); 424 if (Ranges.empty()) 425 return true; 426 427 if (Ranges.size() > 1) 428 return false; 429 430 // We don't create a DIE if we have a single Range and the end label 431 // is null. 432 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(); 433 MCSymbol *End = getLabelAfterInsn(RI->second); 434 return !End; 435 } 436 437 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D, 438 dwarf::Attribute A, const MCSymbol *L, 439 const MCSymbol *Sec) { 440 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) 441 U->addSectionLabel(D, A, L); 442 else 443 U->addSectionDelta(D, A, L, Sec); 444 } 445 446 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE, 447 const SmallVectorImpl<InsnRange> &Range) { 448 // Emit offset in .debug_range as a relocatable label. emitDIE will handle 449 // emitting it appropriately. 450 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++); 451 452 // Under fission, ranges are specified by constant offsets relative to the 453 // CU's DW_AT_GNU_ranges_base. 454 if (useSplitDwarf()) 455 TheCU->addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym, 456 DwarfDebugRangeSectionSym); 457 else 458 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym, 459 DwarfDebugRangeSectionSym); 460 461 RangeSpanList List(RangeSym); 462 for (const InsnRange &R : Range) { 463 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second)); 464 List.addRange(std::move(Span)); 465 } 466 467 // Add the range list to the set of ranges to be emitted. 468 TheCU->addRangeList(std::move(List)); 469 } 470 471 // Construct new DW_TAG_lexical_block for this scope and attach 472 // DW_AT_low_pc/DW_AT_high_pc labels. 473 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU, 474 LexicalScope *Scope) { 475 if (isLexicalScopeDIENull(Scope)) 476 return 0; 477 478 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block); 479 if (Scope->isAbstractScope()) 480 return ScopeDIE; 481 482 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges(); 483 484 // If we have multiple ranges, emit them into the range section. 485 if (ScopeRanges.size() > 1) { 486 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges); 487 return ScopeDIE; 488 } 489 490 // Construct the address range for this DIE. 491 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin(); 492 MCSymbol *Start = getLabelBeforeInsn(RI->first); 493 MCSymbol *End = getLabelAfterInsn(RI->second); 494 assert(End && "End label should not be null!"); 495 496 assert(Start->isDefined() && "Invalid starting label for an inlined scope!"); 497 assert(End->isDefined() && "Invalid end label for an inlined scope!"); 498 499 attachLowHighPC(TheCU, ScopeDIE, Start, End); 500 501 return ScopeDIE; 502 } 503 504 // This scope represents inlined body of a function. Construct DIE to 505 // represent this concrete inlined copy of the function. 506 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU, 507 LexicalScope *Scope) { 508 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges(); 509 assert(!ScopeRanges.empty() && 510 "LexicalScope does not have instruction markers!"); 511 512 if (!Scope->getScopeNode()) 513 return NULL; 514 DIScope DS(Scope->getScopeNode()); 515 DISubprogram InlinedSP = getDISubprogram(DS); 516 DIE *OriginDIE = TheCU->getDIE(InlinedSP); 517 if (!OriginDIE) { 518 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram."); 519 return NULL; 520 } 521 522 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine); 523 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE); 524 525 // If we have multiple ranges, emit them into the range section. 526 if (ScopeRanges.size() > 1) 527 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges); 528 else { 529 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin(); 530 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first); 531 MCSymbol *EndLabel = getLabelAfterInsn(RI->second); 532 533 if (StartLabel == 0 || EndLabel == 0) 534 llvm_unreachable("Unexpected Start and End labels for an inlined scope!"); 535 536 assert(StartLabel->isDefined() && 537 "Invalid starting label for an inlined scope!"); 538 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!"); 539 540 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel); 541 } 542 543 InlinedSubprogramDIEs.insert(OriginDIE); 544 545 // Add the call site information to the DIE. 546 DILocation DL(Scope->getInlinedAt()); 547 TheCU->addUInt( 548 ScopeDIE, dwarf::DW_AT_call_file, None, 549 TheCU->getOrCreateSourceID(DL.getFilename(), DL.getDirectory())); 550 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber()); 551 552 // Add name to the name table, we do this here because we're guaranteed 553 // to have concrete versions of our DW_TAG_inlined_subprogram nodes. 554 addSubprogramNames(TheCU, InlinedSP, ScopeDIE); 555 556 return ScopeDIE; 557 } 558 559 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU, 560 LexicalScope *Scope, 561 SmallVectorImpl<DIE *> &Children) { 562 DIE *ObjectPointer = NULL; 563 564 // Collect arguments for current function. 565 if (LScopes.isCurrentFunctionScope(Scope)) { 566 for (DbgVariable *ArgDV : CurrentFnArguments) 567 if (ArgDV) 568 if (DIE *Arg = 569 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) { 570 Children.push_back(Arg); 571 if (ArgDV->isObjectPointer()) 572 ObjectPointer = Arg; 573 } 574 575 // If this is a variadic function, add an unspecified parameter. 576 DISubprogram SP(Scope->getScopeNode()); 577 DIArray FnArgs = SP.getType().getTypeArray(); 578 if (FnArgs.getElement(FnArgs.getNumElements() - 1) 579 .isUnspecifiedParameter()) { 580 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters); 581 Children.push_back(Ellipsis); 582 } 583 } 584 585 // Collect lexical scope children first. 586 for (DbgVariable *DV : ScopeVariables.lookup(Scope)) 587 if (DIE *Variable = TheCU->constructVariableDIE(*DV, 588 Scope->isAbstractScope())) { 589 Children.push_back(Variable); 590 if (DV->isObjectPointer()) 591 ObjectPointer = Variable; 592 } 593 for (LexicalScope *LS : Scope->getChildren()) 594 if (DIE *Nested = constructScopeDIE(TheCU, LS)) 595 Children.push_back(Nested); 596 return ObjectPointer; 597 } 598 599 // Construct a DIE for this scope. 600 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU, 601 LexicalScope *Scope) { 602 if (!Scope || !Scope->getScopeNode()) 603 return NULL; 604 605 DIScope DS(Scope->getScopeNode()); 606 607 SmallVector<DIE *, 8> Children; 608 DIE *ObjectPointer = NULL; 609 bool ChildrenCreated = false; 610 611 // We try to create the scope DIE first, then the children DIEs. This will 612 // avoid creating un-used children then removing them later when we find out 613 // the scope DIE is null. 614 DIE *ScopeDIE = NULL; 615 if (Scope->getInlinedAt()) 616 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope); 617 else if (DS.isSubprogram()) { 618 ProcessedSPNodes.insert(DS); 619 if (Scope->isAbstractScope()) { 620 ScopeDIE = TheCU->getDIE(DS); 621 // Note down abstract DIE. 622 if (ScopeDIE) 623 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE)); 624 } else 625 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS)); 626 } else { 627 // Early exit when we know the scope DIE is going to be null. 628 if (isLexicalScopeDIENull(Scope)) 629 return NULL; 630 631 // We create children here when we know the scope DIE is not going to be 632 // null and the children will be added to the scope DIE. 633 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children); 634 ChildrenCreated = true; 635 636 // There is no need to emit empty lexical block DIE. 637 std::pair<ImportedEntityMap::const_iterator, 638 ImportedEntityMap::const_iterator> Range = 639 std::equal_range( 640 ScopesWithImportedEntities.begin(), 641 ScopesWithImportedEntities.end(), 642 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0), 643 less_first()); 644 if (Children.empty() && Range.first == Range.second) 645 return NULL; 646 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope); 647 assert(ScopeDIE && "Scope DIE should not be null."); 648 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second; 649 ++i) 650 constructImportedEntityDIE(TheCU, i->second, ScopeDIE); 651 } 652 653 if (!ScopeDIE) { 654 assert(Children.empty() && 655 "We create children only when the scope DIE is not null."); 656 return NULL; 657 } 658 if (!ChildrenCreated) 659 // We create children when the scope DIE is not null. 660 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children); 661 662 // Add children 663 for (DIE *I : Children) 664 ScopeDIE->addChild(I); 665 666 if (DS.isSubprogram() && ObjectPointer != NULL) 667 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer); 668 669 return ScopeDIE; 670 } 671 672 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const { 673 if (!GenerateGnuPubSections) 674 return; 675 676 U->addFlag(D, dwarf::DW_AT_GNU_pubnames); 677 } 678 679 // Create new DwarfCompileUnit for the given metadata node with tag 680 // DW_TAG_compile_unit. 681 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) { 682 StringRef FN = DIUnit.getFilename(); 683 CompilationDir = DIUnit.getDirectory(); 684 685 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit); 686 DwarfCompileUnit *NewCU = new DwarfCompileUnit( 687 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder); 688 InfoHolder.addUnit(NewCU); 689 690 // LTO with assembly output shares a single line table amongst multiple CUs. 691 // To avoid the compilation directory being ambiguous, let the line table 692 // explicitly describe the directory of all files, never relying on the 693 // compilation directory. 694 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU) 695 Asm->OutStreamer.getContext().setMCLineTableCompilationDir( 696 NewCU->getUniqueID(), CompilationDir); 697 698 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer()); 699 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 700 DIUnit.getLanguage()); 701 NewCU->addString(Die, dwarf::DW_AT_name, FN); 702 703 if (!useSplitDwarf()) { 704 NewCU->initStmtList(DwarfLineSectionSym); 705 706 // If we're using split dwarf the compilation dir is going to be in the 707 // skeleton CU and so we don't need to duplicate it here. 708 if (!CompilationDir.empty()) 709 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 710 711 addGnuPubAttributes(NewCU, Die); 712 } 713 714 if (DIUnit.isOptimized()) 715 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized); 716 717 StringRef Flags = DIUnit.getFlags(); 718 if (!Flags.empty()) 719 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 720 721 if (unsigned RVer = DIUnit.getRunTimeVersion()) 722 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 723 dwarf::DW_FORM_data1, RVer); 724 725 if (!FirstCU) 726 FirstCU = NewCU; 727 728 if (useSplitDwarf()) { 729 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(), 730 DwarfInfoDWOSectionSym); 731 NewCU->setSkeleton(constructSkeletonCU(NewCU)); 732 } else 733 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(), 734 DwarfInfoSectionSym); 735 736 CUMap.insert(std::make_pair(DIUnit, NewCU)); 737 CUDieMap.insert(std::make_pair(Die, NewCU)); 738 return NewCU; 739 } 740 741 // Construct subprogram DIE. 742 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU, 743 const MDNode *N) { 744 // FIXME: We should only call this routine once, however, during LTO if a 745 // program is defined in multiple CUs we could end up calling it out of 746 // beginModule as we walk the CUs. 747 748 DwarfCompileUnit *&CURef = SPMap[N]; 749 if (CURef) 750 return; 751 CURef = TheCU; 752 753 DISubprogram SP(N); 754 if (!SP.isDefinition()) 755 // This is a method declaration which will be handled while constructing 756 // class type. 757 return; 758 759 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP); 760 761 // Expose as a global name. 762 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext())); 763 } 764 765 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU, 766 const MDNode *N) { 767 DIImportedEntity Module(N); 768 assert(Module.Verify()); 769 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext())) 770 constructImportedEntityDIE(TheCU, Module, D); 771 } 772 773 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU, 774 const MDNode *N, DIE *Context) { 775 DIImportedEntity Module(N); 776 assert(Module.Verify()); 777 return constructImportedEntityDIE(TheCU, Module, Context); 778 } 779 780 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU, 781 const DIImportedEntity &Module, 782 DIE *Context) { 783 assert(Module.Verify() && 784 "Use one of the MDNode * overloads to handle invalid metadata"); 785 assert(Context && "Should always have a context for an imported_module"); 786 DIE *IMDie = TheCU->createAndAddDIE(Module.getTag(), *Context, Module); 787 DIE *EntityDie; 788 DIDescriptor Entity = resolve(Module.getEntity()); 789 if (Entity.isNameSpace()) 790 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity)); 791 else if (Entity.isSubprogram()) 792 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity)); 793 else if (Entity.isType()) 794 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity)); 795 else 796 EntityDie = TheCU->getDIE(Entity); 797 TheCU->addSourceLine(IMDie, Module.getLineNumber(), 798 Module.getContext().getFilename(), 799 Module.getContext().getDirectory()); 800 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie); 801 StringRef Name = Module.getName(); 802 if (!Name.empty()) 803 TheCU->addString(IMDie, dwarf::DW_AT_name, Name); 804 } 805 806 // Emit all Dwarf sections that should come prior to the content. Create 807 // global DIEs and emit initial debug info sections. This is invoked by 808 // the target AsmPrinter. 809 void DwarfDebug::beginModule() { 810 if (DisableDebugInfoPrinting) 811 return; 812 813 const Module *M = MMI->getModule(); 814 815 // If module has named metadata anchors then use them, otherwise scan the 816 // module using debug info finder to collect debug info. 817 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu"); 818 if (!CU_Nodes) 819 return; 820 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes); 821 822 // Emit initial sections so we can reference labels later. 823 emitSectionLabels(); 824 825 SingleCU = CU_Nodes->getNumOperands() == 1; 826 827 for (MDNode *N : CU_Nodes->operands()) { 828 DICompileUnit CUNode(N); 829 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode); 830 DIArray ImportedEntities = CUNode.getImportedEntities(); 831 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i) 832 ScopesWithImportedEntities.push_back(std::make_pair( 833 DIImportedEntity(ImportedEntities.getElement(i)).getContext(), 834 ImportedEntities.getElement(i))); 835 std::sort(ScopesWithImportedEntities.begin(), 836 ScopesWithImportedEntities.end(), less_first()); 837 DIArray GVs = CUNode.getGlobalVariables(); 838 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) 839 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i))); 840 DIArray SPs = CUNode.getSubprograms(); 841 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) 842 constructSubprogramDIE(CU, SPs.getElement(i)); 843 DIArray EnumTypes = CUNode.getEnumTypes(); 844 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) 845 CU->getOrCreateTypeDIE(EnumTypes.getElement(i)); 846 DIArray RetainedTypes = CUNode.getRetainedTypes(); 847 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) { 848 DIType Ty(RetainedTypes.getElement(i)); 849 // The retained types array by design contains pointers to 850 // MDNodes rather than DIRefs. Unique them here. 851 DIType UniqueTy(resolve(Ty.getRef())); 852 CU->getOrCreateTypeDIE(UniqueTy); 853 } 854 // Emit imported_modules last so that the relevant context is already 855 // available. 856 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i) 857 constructImportedEntityDIE(CU, ImportedEntities.getElement(i)); 858 } 859 860 // Tell MMI that we have debug info. 861 MMI->setDebugInfoAvailability(true); 862 863 // Prime section data. 864 SectionMap[Asm->getObjFileLowering().getTextSection()]; 865 } 866 867 // Attach DW_AT_inline attribute with inlined subprogram DIEs. 868 void DwarfDebug::computeInlinedDIEs() { 869 // Attach DW_AT_inline attribute with inlined subprogram DIEs. 870 for (DIE *ISP : InlinedSubprogramDIEs) 871 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined); 872 873 for (const auto &AI : AbstractSPDies) { 874 DIE *ISP = AI.second; 875 if (InlinedSubprogramDIEs.count(ISP)) 876 continue; 877 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined); 878 } 879 } 880 881 // Collect info for variables that were optimized out. 882 void DwarfDebug::collectDeadVariables() { 883 const Module *M = MMI->getModule(); 884 885 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) { 886 for (MDNode *N : CU_Nodes->operands()) { 887 DICompileUnit TheCU(N); 888 DIArray Subprograms = TheCU.getSubprograms(); 889 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) { 890 DISubprogram SP(Subprograms.getElement(i)); 891 if (ProcessedSPNodes.count(SP) != 0) 892 continue; 893 if (!SP.isSubprogram()) 894 continue; 895 if (!SP.isDefinition()) 896 continue; 897 DIArray Variables = SP.getVariables(); 898 if (Variables.getNumElements() == 0) 899 continue; 900 901 // Construct subprogram DIE and add variables DIEs. 902 DwarfCompileUnit *SPCU = 903 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU)); 904 assert(SPCU && "Unable to find Compile Unit!"); 905 // FIXME: See the comment in constructSubprogramDIE about duplicate 906 // subprogram DIEs. 907 constructSubprogramDIE(SPCU, SP); 908 DIE *SPDIE = SPCU->getDIE(SP); 909 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) { 910 DIVariable DV(Variables.getElement(vi)); 911 if (!DV.isVariable()) 912 continue; 913 DbgVariable NewVar(DV, NULL, this); 914 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false)) 915 SPDIE->addChild(VariableDIE); 916 } 917 } 918 } 919 } 920 } 921 922 void DwarfDebug::finalizeModuleInfo() { 923 // Collect info for variables that were optimized out. 924 collectDeadVariables(); 925 926 // Attach DW_AT_inline attribute with inlined subprogram DIEs. 927 computeInlinedDIEs(); 928 929 // Handle anything that needs to be done on a per-unit basis after 930 // all other generation. 931 for (DwarfUnit *TheU : getUnits()) { 932 // Emit DW_AT_containing_type attribute to connect types with their 933 // vtable holding type. 934 TheU->constructContainingTypeDIEs(); 935 936 // Add CU specific attributes if we need to add any. 937 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) { 938 // If we're splitting the dwarf out now that we've got the entire 939 // CU then add the dwo id to it. 940 DwarfCompileUnit *SkCU = 941 static_cast<DwarfCompileUnit *>(TheU->getSkeleton()); 942 if (useSplitDwarf()) { 943 // Emit a unique identifier for this CU. 944 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie()); 945 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 946 dwarf::DW_FORM_data8, ID); 947 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id, 948 dwarf::DW_FORM_data8, ID); 949 950 // We don't keep track of which addresses are used in which CU so this 951 // is a bit pessimistic under LTO. 952 if (!InfoHolder.getAddrPool()->empty()) 953 addSectionLabel(Asm, SkCU, SkCU->getUnitDie(), 954 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym, 955 DwarfAddrSectionSym); 956 if (!TheU->getRangeLists().empty()) 957 addSectionLabel(Asm, SkCU, SkCU->getUnitDie(), 958 dwarf::DW_AT_GNU_ranges_base, 959 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym); 960 } 961 962 // If we have code split among multiple sections or non-contiguous 963 // ranges of code then emit a DW_AT_ranges attribute on the unit that will 964 // remain in the .o file, otherwise add a DW_AT_low_pc. 965 // FIXME: We should use ranges allow reordering of code ala 966 // .subsections_via_symbols in mach-o. This would mean turning on 967 // ranges for all subprogram DIEs for mach-o. 968 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU); 969 unsigned NumRanges = TheU->getRanges().size(); 970 if (NumRanges) { 971 if (NumRanges > 1) { 972 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges, 973 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()), 974 DwarfDebugRangeSectionSym); 975 976 // A DW_AT_low_pc attribute may also be specified in combination with 977 // DW_AT_ranges to specify the default base address for use in 978 // location lists (see Section 2.6.2) and range lists (see Section 979 // 2.17.3). 980 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 981 0); 982 } else { 983 RangeSpan &Range = TheU->getRanges().back(); 984 U->addLocalLabelAddress(U->getUnitDie(), dwarf::DW_AT_low_pc, 985 Range.getStart()); 986 U->addLabelDelta(U->getUnitDie(), dwarf::DW_AT_high_pc, 987 Range.getEnd(), Range.getStart()); 988 } 989 } 990 } 991 } 992 993 // Compute DIE offsets and sizes. 994 InfoHolder.computeSizeAndOffsets(); 995 if (useSplitDwarf()) 996 SkeletonHolder.computeSizeAndOffsets(); 997 } 998 999 void DwarfDebug::endSections() { 1000 // Filter labels by section. 1001 for (const SymbolCU &SCU : ArangeLabels) { 1002 if (SCU.Sym->isInSection()) { 1003 // Make a note of this symbol and it's section. 1004 const MCSection *Section = &SCU.Sym->getSection(); 1005 if (!Section->getKind().isMetadata()) 1006 SectionMap[Section].push_back(SCU); 1007 } else { 1008 // Some symbols (e.g. common/bss on mach-o) can have no section but still 1009 // appear in the output. This sucks as we rely on sections to build 1010 // arange spans. We can do it without, but it's icky. 1011 SectionMap[NULL].push_back(SCU); 1012 } 1013 } 1014 1015 // Build a list of sections used. 1016 std::vector<const MCSection *> Sections; 1017 for (const auto &it : SectionMap) { 1018 const MCSection *Section = it.first; 1019 Sections.push_back(Section); 1020 } 1021 1022 // Sort the sections into order. 1023 // This is only done to ensure consistent output order across different runs. 1024 std::sort(Sections.begin(), Sections.end(), SectionSort); 1025 1026 // Add terminating symbols for each section. 1027 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) { 1028 const MCSection *Section = Sections[ID]; 1029 MCSymbol *Sym = NULL; 1030 1031 if (Section) { 1032 // We can't call MCSection::getLabelEndName, as it's only safe to do so 1033 // if we know the section name up-front. For user-created sections, the 1034 // resulting label may not be valid to use as a label. (section names can 1035 // use a greater set of characters on some systems) 1036 Sym = Asm->GetTempSymbol("debug_end", ID); 1037 Asm->OutStreamer.SwitchSection(Section); 1038 Asm->OutStreamer.EmitLabel(Sym); 1039 } 1040 1041 // Insert a final terminator. 1042 SectionMap[Section].push_back(SymbolCU(NULL, Sym)); 1043 } 1044 } 1045 1046 // Emit all Dwarf sections that should come after the content. 1047 void DwarfDebug::endModule() { 1048 assert(CurFn == 0); 1049 assert(CurMI == 0); 1050 1051 if (!FirstCU) 1052 return; 1053 1054 // End any existing sections. 1055 // TODO: Does this need to happen? 1056 endSections(); 1057 1058 // Finalize the debug info for the module. 1059 finalizeModuleInfo(); 1060 1061 emitDebugStr(); 1062 1063 // Emit all the DIEs into a debug info section. 1064 emitDebugInfo(); 1065 1066 // Corresponding abbreviations into a abbrev section. 1067 emitAbbreviations(); 1068 1069 // Emit info into a debug aranges section. 1070 if (GenerateARangeSection) 1071 emitDebugARanges(); 1072 1073 // Emit info into a debug ranges section. 1074 emitDebugRanges(); 1075 1076 if (useSplitDwarf()) { 1077 emitDebugStrDWO(); 1078 emitDebugInfoDWO(); 1079 emitDebugAbbrevDWO(); 1080 emitDebugLineDWO(); 1081 // Emit DWO addresses. 1082 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection()); 1083 emitDebugLocDWO(); 1084 } else 1085 // Emit info into a debug loc section. 1086 emitDebugLoc(); 1087 1088 // Emit info into the dwarf accelerator table sections. 1089 if (useDwarfAccelTables()) { 1090 emitAccelNames(); 1091 emitAccelObjC(); 1092 emitAccelNamespaces(); 1093 emitAccelTypes(); 1094 } 1095 1096 // Emit the pubnames and pubtypes sections if requested. 1097 if (HasDwarfPubSections) { 1098 emitDebugPubNames(GenerateGnuPubSections); 1099 emitDebugPubTypes(GenerateGnuPubSections); 1100 } 1101 1102 // clean up. 1103 SPMap.clear(); 1104 1105 // Reset these for the next Module if we have one. 1106 FirstCU = NULL; 1107 } 1108 1109 // Find abstract variable, if any, associated with Var. 1110 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV, 1111 DebugLoc ScopeLoc) { 1112 LLVMContext &Ctx = DV->getContext(); 1113 // More then one inlined variable corresponds to one abstract variable. 1114 DIVariable Var = cleanseInlinedVariable(DV, Ctx); 1115 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var); 1116 if (AbsDbgVariable) 1117 return AbsDbgVariable; 1118 1119 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx)); 1120 if (!Scope) 1121 return NULL; 1122 1123 AbsDbgVariable = new DbgVariable(Var, NULL, this); 1124 addScopeVariable(Scope, AbsDbgVariable); 1125 AbstractVariables[Var] = AbsDbgVariable; 1126 return AbsDbgVariable; 1127 } 1128 1129 // If Var is a current function argument then add it to CurrentFnArguments list. 1130 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) { 1131 if (!LScopes.isCurrentFunctionScope(Scope)) 1132 return false; 1133 DIVariable DV = Var->getVariable(); 1134 if (DV.getTag() != dwarf::DW_TAG_arg_variable) 1135 return false; 1136 unsigned ArgNo = DV.getArgNumber(); 1137 if (ArgNo == 0) 1138 return false; 1139 1140 size_t Size = CurrentFnArguments.size(); 1141 if (Size == 0) 1142 CurrentFnArguments.resize(CurFn->getFunction()->arg_size()); 1143 // llvm::Function argument size is not good indicator of how many 1144 // arguments does the function have at source level. 1145 if (ArgNo > Size) 1146 CurrentFnArguments.resize(ArgNo * 2); 1147 CurrentFnArguments[ArgNo - 1] = Var; 1148 return true; 1149 } 1150 1151 // Collect variable information from side table maintained by MMI. 1152 void DwarfDebug::collectVariableInfoFromMMITable( 1153 SmallPtrSet<const MDNode *, 16> &Processed) { 1154 for (const auto &VI : MMI->getVariableDbgInfo()) { 1155 if (!VI.Var) 1156 continue; 1157 Processed.insert(VI.Var); 1158 DIVariable DV(VI.Var); 1159 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); 1160 1161 // If variable scope is not found then skip this variable. 1162 if (Scope == 0) 1163 continue; 1164 1165 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc); 1166 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this); 1167 RegVar->setFrameIndex(VI.Slot); 1168 if (!addCurrentFnArgument(RegVar, Scope)) 1169 addScopeVariable(Scope, RegVar); 1170 if (AbsDbgVariable) 1171 AbsDbgVariable->setFrameIndex(VI.Slot); 1172 } 1173 } 1174 1175 // Return true if debug value, encoded by DBG_VALUE instruction, is in a 1176 // defined reg. 1177 static bool isDbgValueInDefinedReg(const MachineInstr *MI) { 1178 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!"); 1179 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() && 1180 MI->getOperand(0).getReg() && 1181 (MI->getOperand(1).isImm() || 1182 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U)); 1183 } 1184 1185 // Get .debug_loc entry for the instruction range starting at MI. 1186 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm, 1187 const MCSymbol *FLabel, 1188 const MCSymbol *SLabel, 1189 const MachineInstr *MI, 1190 DwarfCompileUnit *Unit) { 1191 const MDNode *Var = MI->getDebugVariable(); 1192 1193 assert(MI->getNumOperands() == 3); 1194 if (MI->getOperand(0).isReg()) { 1195 MachineLocation MLoc; 1196 // If the second operand is an immediate, this is a 1197 // register-indirect address. 1198 if (!MI->getOperand(1).isImm()) 1199 MLoc.set(MI->getOperand(0).getReg()); 1200 else 1201 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm()); 1202 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit); 1203 } 1204 if (MI->getOperand(0).isImm()) 1205 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit); 1206 if (MI->getOperand(0).isFPImm()) 1207 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(), 1208 Var, Unit); 1209 if (MI->getOperand(0).isCImm()) 1210 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(), 1211 Var, Unit); 1212 1213 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!"); 1214 } 1215 1216 // Find variables for each lexical scope. 1217 void 1218 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) { 1219 1220 // Grab the variable info that was squirreled away in the MMI side-table. 1221 collectVariableInfoFromMMITable(Processed); 1222 1223 for (const MDNode *Var : UserVariables) { 1224 if (Processed.count(Var)) 1225 continue; 1226 1227 // History contains relevant DBG_VALUE instructions for Var and instructions 1228 // clobbering it. 1229 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var]; 1230 if (History.empty()) 1231 continue; 1232 const MachineInstr *MInsn = History.front(); 1233 1234 DIVariable DV(Var); 1235 LexicalScope *Scope = NULL; 1236 if (DV.getTag() == dwarf::DW_TAG_arg_variable && 1237 DISubprogram(DV.getContext()).describes(CurFn->getFunction())) 1238 Scope = LScopes.getCurrentFunctionScope(); 1239 else if (MDNode *IA = DV.getInlinedAt()) 1240 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA)); 1241 else 1242 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1))); 1243 // If variable scope is not found then skip this variable. 1244 if (!Scope) 1245 continue; 1246 1247 Processed.insert(DV); 1248 assert(MInsn->isDebugValue() && "History must begin with debug value"); 1249 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc()); 1250 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this); 1251 if (!addCurrentFnArgument(RegVar, Scope)) 1252 addScopeVariable(Scope, RegVar); 1253 if (AbsVar) 1254 AbsVar->setMInsn(MInsn); 1255 1256 // Simplify ranges that are fully coalesced. 1257 if (History.size() <= 1 || 1258 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) { 1259 RegVar->setMInsn(MInsn); 1260 continue; 1261 } 1262 1263 // Handle multiple DBG_VALUE instructions describing one variable. 1264 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size()); 1265 1266 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1); 1267 DebugLocList &LocList = DotDebugLocEntries.back(); 1268 LocList.Label = 1269 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1); 1270 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List; 1271 for (SmallVectorImpl<const MachineInstr *>::const_iterator 1272 HI = History.begin(), 1273 HE = History.end(); 1274 HI != HE; ++HI) { 1275 const MachineInstr *Begin = *HI; 1276 assert(Begin->isDebugValue() && "Invalid History entry"); 1277 1278 // Check if DBG_VALUE is truncating a range. 1279 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() && 1280 !Begin->getOperand(0).getReg()) 1281 continue; 1282 1283 // Compute the range for a register location. 1284 const MCSymbol *FLabel = getLabelBeforeInsn(Begin); 1285 const MCSymbol *SLabel = 0; 1286 1287 if (HI + 1 == HE) 1288 // If Begin is the last instruction in History then its value is valid 1289 // until the end of the function. 1290 SLabel = FunctionEndSym; 1291 else { 1292 const MachineInstr *End = HI[1]; 1293 DEBUG(dbgs() << "DotDebugLoc Pair:\n" 1294 << "\t" << *Begin << "\t" << *End << "\n"); 1295 if (End->isDebugValue()) 1296 SLabel = getLabelBeforeInsn(End); 1297 else { 1298 // End is a normal instruction clobbering the range. 1299 SLabel = getLabelAfterInsn(End); 1300 assert(SLabel && "Forgot label after clobber instruction"); 1301 ++HI; 1302 } 1303 } 1304 1305 // The value is valid until the next DBG_VALUE or clobber. 1306 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1307 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode()); 1308 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU); 1309 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc)) 1310 DebugLoc.push_back(std::move(Loc)); 1311 } 1312 } 1313 1314 // Collect info for variables that were optimized out. 1315 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1316 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables(); 1317 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) { 1318 DIVariable DV(Variables.getElement(i)); 1319 if (!DV || !DV.isVariable() || !Processed.insert(DV)) 1320 continue; 1321 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) 1322 addScopeVariable(Scope, new DbgVariable(DV, NULL, this)); 1323 } 1324 } 1325 1326 // Return Label preceding the instruction. 1327 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) { 1328 MCSymbol *Label = LabelsBeforeInsn.lookup(MI); 1329 assert(Label && "Didn't insert label before instruction"); 1330 return Label; 1331 } 1332 1333 // Return Label immediately following the instruction. 1334 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) { 1335 return LabelsAfterInsn.lookup(MI); 1336 } 1337 1338 // Process beginning of an instruction. 1339 void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1340 assert(CurMI == 0); 1341 CurMI = MI; 1342 // Check if source location changes, but ignore DBG_VALUE locations. 1343 if (!MI->isDebugValue()) { 1344 DebugLoc DL = MI->getDebugLoc(); 1345 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) { 1346 unsigned Flags = 0; 1347 PrevInstLoc = DL; 1348 if (DL == PrologEndLoc) { 1349 Flags |= DWARF2_FLAG_PROLOGUE_END; 1350 PrologEndLoc = DebugLoc(); 1351 } 1352 if (PrologEndLoc.isUnknown()) 1353 Flags |= DWARF2_FLAG_IS_STMT; 1354 1355 if (!DL.isUnknown()) { 1356 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext()); 1357 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1358 } else 1359 recordSourceLine(0, 0, 0, 0); 1360 } 1361 } 1362 1363 // Insert labels where requested. 1364 DenseMap<const MachineInstr *, MCSymbol *>::iterator I = 1365 LabelsBeforeInsn.find(MI); 1366 1367 // No label needed. 1368 if (I == LabelsBeforeInsn.end()) 1369 return; 1370 1371 // Label already assigned. 1372 if (I->second) 1373 return; 1374 1375 if (!PrevLabel) { 1376 PrevLabel = MMI->getContext().CreateTempSymbol(); 1377 Asm->OutStreamer.EmitLabel(PrevLabel); 1378 } 1379 I->second = PrevLabel; 1380 } 1381 1382 // Process end of an instruction. 1383 void DwarfDebug::endInstruction() { 1384 assert(CurMI != 0); 1385 // Don't create a new label after DBG_VALUE instructions. 1386 // They don't generate code. 1387 if (!CurMI->isDebugValue()) 1388 PrevLabel = 0; 1389 1390 DenseMap<const MachineInstr *, MCSymbol *>::iterator I = 1391 LabelsAfterInsn.find(CurMI); 1392 CurMI = 0; 1393 1394 // No label needed. 1395 if (I == LabelsAfterInsn.end()) 1396 return; 1397 1398 // Label already assigned. 1399 if (I->second) 1400 return; 1401 1402 // We need a label after this instruction. 1403 if (!PrevLabel) { 1404 PrevLabel = MMI->getContext().CreateTempSymbol(); 1405 Asm->OutStreamer.EmitLabel(PrevLabel); 1406 } 1407 I->second = PrevLabel; 1408 } 1409 1410 // Each LexicalScope has first instruction and last instruction to mark 1411 // beginning and end of a scope respectively. Create an inverse map that list 1412 // scopes starts (and ends) with an instruction. One instruction may start (or 1413 // end) multiple scopes. Ignore scopes that are not reachable. 1414 void DwarfDebug::identifyScopeMarkers() { 1415 SmallVector<LexicalScope *, 4> WorkList; 1416 WorkList.push_back(LScopes.getCurrentFunctionScope()); 1417 while (!WorkList.empty()) { 1418 LexicalScope *S = WorkList.pop_back_val(); 1419 1420 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren(); 1421 if (!Children.empty()) 1422 WorkList.append(Children.begin(), Children.end()); 1423 1424 if (S->isAbstractScope()) 1425 continue; 1426 1427 for (const InsnRange &R : S->getRanges()) { 1428 assert(R.first && "InsnRange does not have first instruction!"); 1429 assert(R.second && "InsnRange does not have second instruction!"); 1430 requestLabelBeforeInsn(R.first); 1431 requestLabelAfterInsn(R.second); 1432 } 1433 } 1434 } 1435 1436 // Gather pre-function debug information. Assumes being called immediately 1437 // after the function entry point has been emitted. 1438 void DwarfDebug::beginFunction(const MachineFunction *MF) { 1439 CurFn = MF; 1440 1441 // If there's no debug info for the function we're not going to do anything. 1442 if (!MMI->hasDebugInfo()) 1443 return; 1444 1445 // Grab the lexical scopes for the function, if we don't have any of those 1446 // then we're not going to be able to do anything. 1447 LScopes.initialize(*MF); 1448 if (LScopes.empty()) 1449 return; 1450 1451 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned"); 1452 1453 // Make sure that each lexical scope will have a begin/end label. 1454 identifyScopeMarkers(); 1455 1456 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function 1457 // belongs to so that we add to the correct per-cu line table in the 1458 // non-asm case. 1459 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1460 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode()); 1461 assert(TheCU && "Unable to find compile unit!"); 1462 if (Asm->OutStreamer.hasRawTextSupport()) 1463 // Use a single line table if we are generating assembly. 1464 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0); 1465 else 1466 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID()); 1467 1468 // Emit a label for the function so that we have a beginning address. 1469 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()); 1470 // Assumes in correct section after the entry point. 1471 Asm->OutStreamer.EmitLabel(FunctionBeginSym); 1472 1473 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo(); 1474 // LiveUserVar - Map physreg numbers to the MDNode they contain. 1475 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs()); 1476 1477 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E; 1478 ++I) { 1479 bool AtBlockEntry = true; 1480 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 1481 II != IE; ++II) { 1482 const MachineInstr *MI = II; 1483 1484 if (MI->isDebugValue()) { 1485 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!"); 1486 1487 // Keep track of user variables. 1488 const MDNode *Var = MI->getDebugVariable(); 1489 1490 // Variable is in a register, we need to check for clobbers. 1491 if (isDbgValueInDefinedReg(MI)) 1492 LiveUserVar[MI->getOperand(0).getReg()] = Var; 1493 1494 // Check the history of this variable. 1495 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var]; 1496 if (History.empty()) { 1497 UserVariables.push_back(Var); 1498 // The first mention of a function argument gets the FunctionBeginSym 1499 // label, so arguments are visible when breaking at function entry. 1500 DIVariable DV(Var); 1501 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable && 1502 getDISubprogram(DV.getContext()).describes(MF->getFunction())) 1503 LabelsBeforeInsn[MI] = FunctionBeginSym; 1504 } else { 1505 // We have seen this variable before. Try to coalesce DBG_VALUEs. 1506 const MachineInstr *Prev = History.back(); 1507 if (Prev->isDebugValue()) { 1508 // Coalesce identical entries at the end of History. 1509 if (History.size() >= 2 && 1510 Prev->isIdenticalTo(History[History.size() - 2])) { 1511 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n" 1512 << "\t" << *Prev << "\t" 1513 << *History[History.size() - 2] << "\n"); 1514 History.pop_back(); 1515 } 1516 1517 // Terminate old register assignments that don't reach MI; 1518 MachineFunction::const_iterator PrevMBB = Prev->getParent(); 1519 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) && 1520 isDbgValueInDefinedReg(Prev)) { 1521 // Previous register assignment needs to terminate at the end of 1522 // its basic block. 1523 MachineBasicBlock::const_iterator LastMI = 1524 PrevMBB->getLastNonDebugInstr(); 1525 if (LastMI == PrevMBB->end()) { 1526 // Drop DBG_VALUE for empty range. 1527 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n" 1528 << "\t" << *Prev << "\n"); 1529 History.pop_back(); 1530 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end()) 1531 // Terminate after LastMI. 1532 History.push_back(LastMI); 1533 } 1534 } 1535 } 1536 History.push_back(MI); 1537 } else { 1538 // Not a DBG_VALUE instruction. 1539 if (!MI->isPosition()) 1540 AtBlockEntry = false; 1541 1542 // First known non-DBG_VALUE and non-frame setup location marks 1543 // the beginning of the function body. 1544 if (!MI->getFlag(MachineInstr::FrameSetup) && 1545 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())) 1546 PrologEndLoc = MI->getDebugLoc(); 1547 1548 // Check if the instruction clobbers any registers with debug vars. 1549 for (const MachineOperand &MO : MI->operands()) { 1550 if (!MO.isReg() || !MO.isDef() || !MO.getReg()) 1551 continue; 1552 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); 1553 ++AI) { 1554 unsigned Reg = *AI; 1555 const MDNode *Var = LiveUserVar[Reg]; 1556 if (!Var) 1557 continue; 1558 // Reg is now clobbered. 1559 LiveUserVar[Reg] = 0; 1560 1561 // Was MD last defined by a DBG_VALUE referring to Reg? 1562 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var); 1563 if (HistI == DbgValues.end()) 1564 continue; 1565 SmallVectorImpl<const MachineInstr *> &History = HistI->second; 1566 if (History.empty()) 1567 continue; 1568 const MachineInstr *Prev = History.back(); 1569 // Sanity-check: Register assignments are terminated at the end of 1570 // their block. 1571 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent()) 1572 continue; 1573 // Is the variable still in Reg? 1574 if (!isDbgValueInDefinedReg(Prev) || 1575 Prev->getOperand(0).getReg() != Reg) 1576 continue; 1577 // Var is clobbered. Make sure the next instruction gets a label. 1578 History.push_back(MI); 1579 } 1580 } 1581 } 1582 } 1583 } 1584 1585 for (auto &I : DbgValues) { 1586 SmallVectorImpl<const MachineInstr *> &History = I.second; 1587 if (History.empty()) 1588 continue; 1589 1590 // Make sure the final register assignments are terminated. 1591 const MachineInstr *Prev = History.back(); 1592 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) { 1593 const MachineBasicBlock *PrevMBB = Prev->getParent(); 1594 MachineBasicBlock::const_iterator LastMI = 1595 PrevMBB->getLastNonDebugInstr(); 1596 if (LastMI == PrevMBB->end()) 1597 // Drop DBG_VALUE for empty range. 1598 History.pop_back(); 1599 else if (PrevMBB != &PrevMBB->getParent()->back()) { 1600 // Terminate after LastMI. 1601 History.push_back(LastMI); 1602 } 1603 } 1604 // Request labels for the full history. 1605 for (const MachineInstr *MI : History) { 1606 if (MI->isDebugValue()) 1607 requestLabelBeforeInsn(MI); 1608 else 1609 requestLabelAfterInsn(MI); 1610 } 1611 } 1612 1613 PrevInstLoc = DebugLoc(); 1614 PrevLabel = FunctionBeginSym; 1615 1616 // Record beginning of function. 1617 if (!PrologEndLoc.isUnknown()) { 1618 DebugLoc FnStartDL = 1619 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext()); 1620 recordSourceLine( 1621 FnStartDL.getLine(), FnStartDL.getCol(), 1622 FnStartDL.getScope(MF->getFunction()->getContext()), 1623 // We'd like to list the prologue as "not statements" but GDB behaves 1624 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing. 1625 DWARF2_FLAG_IS_STMT); 1626 } 1627 } 1628 1629 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) { 1630 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS]; 1631 DIVariable DV = Var->getVariable(); 1632 // Variables with positive arg numbers are parameters. 1633 if (unsigned ArgNum = DV.getArgNumber()) { 1634 // Keep all parameters in order at the start of the variable list to ensure 1635 // function types are correct (no out-of-order parameters) 1636 // 1637 // This could be improved by only doing it for optimized builds (unoptimized 1638 // builds have the right order to begin with), searching from the back (this 1639 // would catch the unoptimized case quickly), or doing a binary search 1640 // rather than linear search. 1641 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin(); 1642 while (I != Vars.end()) { 1643 unsigned CurNum = (*I)->getVariable().getArgNumber(); 1644 // A local (non-parameter) variable has been found, insert immediately 1645 // before it. 1646 if (CurNum == 0) 1647 break; 1648 // A later indexed parameter has been found, insert immediately before it. 1649 if (CurNum > ArgNum) 1650 break; 1651 ++I; 1652 } 1653 Vars.insert(I, Var); 1654 return; 1655 } 1656 1657 Vars.push_back(Var); 1658 } 1659 1660 // Gather and emit post-function debug information. 1661 void DwarfDebug::endFunction(const MachineFunction *MF) { 1662 // Every beginFunction(MF) call should be followed by an endFunction(MF) call, 1663 // though the beginFunction may not be called at all. 1664 // We should handle both cases. 1665 if (CurFn == 0) 1666 CurFn = MF; 1667 else 1668 assert(CurFn == MF); 1669 assert(CurFn != 0); 1670 1671 if (!MMI->hasDebugInfo() || LScopes.empty()) { 1672 // If we don't have a lexical scope for this function then there will 1673 // be a hole in the range information. Keep note of this by setting the 1674 // previously used section to nullptr. 1675 PrevSection = nullptr; 1676 PrevCU = nullptr; 1677 CurFn = 0; 1678 return; 1679 } 1680 1681 // Define end label for subprogram. 1682 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()); 1683 // Assumes in correct section after the entry point. 1684 Asm->OutStreamer.EmitLabel(FunctionEndSym); 1685 1686 // Set DwarfDwarfCompileUnitID in MCContext to default value. 1687 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0); 1688 1689 SmallPtrSet<const MDNode *, 16> ProcessedVars; 1690 collectVariableInfo(ProcessedVars); 1691 1692 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1693 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode()); 1694 assert(TheCU && "Unable to find compile unit!"); 1695 1696 // Construct abstract scopes. 1697 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) { 1698 DISubprogram SP(AScope->getScopeNode()); 1699 if (SP.isSubprogram()) { 1700 // Collect info for variables that were optimized out. 1701 DIArray Variables = SP.getVariables(); 1702 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) { 1703 DIVariable DV(Variables.getElement(i)); 1704 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV)) 1705 continue; 1706 // Check that DbgVariable for DV wasn't created earlier, when 1707 // findAbstractVariable() was called for inlined instance of DV. 1708 LLVMContext &Ctx = DV->getContext(); 1709 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx); 1710 if (AbstractVariables.lookup(CleanDV)) 1711 continue; 1712 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext())) 1713 addScopeVariable(Scope, new DbgVariable(DV, NULL, this)); 1714 } 1715 } 1716 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0) 1717 constructScopeDIE(TheCU, AScope); 1718 } 1719 1720 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope); 1721 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn)) 1722 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr); 1723 1724 // Add the range of this function to the list of ranges for the CU. 1725 RangeSpan Span(FunctionBeginSym, FunctionEndSym); 1726 TheCU->addRange(std::move(Span)); 1727 PrevSection = Asm->getCurrentSection(); 1728 PrevCU = TheCU; 1729 1730 // Clear debug info 1731 for (auto &I : ScopeVariables) 1732 DeleteContainerPointers(I.second); 1733 ScopeVariables.clear(); 1734 DeleteContainerPointers(CurrentFnArguments); 1735 UserVariables.clear(); 1736 DbgValues.clear(); 1737 AbstractVariables.clear(); 1738 LabelsBeforeInsn.clear(); 1739 LabelsAfterInsn.clear(); 1740 PrevLabel = NULL; 1741 CurFn = 0; 1742 } 1743 1744 // Register a source line with debug info. Returns the unique label that was 1745 // emitted and which provides correspondence to the source line list. 1746 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1747 unsigned Flags) { 1748 StringRef Fn; 1749 StringRef Dir; 1750 unsigned Src = 1; 1751 unsigned Discriminator = 0; 1752 if (S) { 1753 DIDescriptor Scope(S); 1754 1755 if (Scope.isCompileUnit()) { 1756 DICompileUnit CU(S); 1757 Fn = CU.getFilename(); 1758 Dir = CU.getDirectory(); 1759 } else if (Scope.isFile()) { 1760 DIFile F(S); 1761 Fn = F.getFilename(); 1762 Dir = F.getDirectory(); 1763 } else if (Scope.isSubprogram()) { 1764 DISubprogram SP(S); 1765 Fn = SP.getFilename(); 1766 Dir = SP.getDirectory(); 1767 } else if (Scope.isLexicalBlockFile()) { 1768 DILexicalBlockFile DBF(S); 1769 Fn = DBF.getFilename(); 1770 Dir = DBF.getDirectory(); 1771 } else if (Scope.isLexicalBlock()) { 1772 DILexicalBlock DB(S); 1773 Fn = DB.getFilename(); 1774 Dir = DB.getDirectory(); 1775 Discriminator = DB.getDiscriminator(); 1776 } else 1777 llvm_unreachable("Unexpected scope info"); 1778 1779 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID(); 1780 Src = static_cast<DwarfCompileUnit *>(InfoHolder.getUnits()[CUID]) 1781 ->getOrCreateSourceID(Fn, Dir); 1782 } 1783 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 1784 Discriminator, Fn); 1785 } 1786 1787 //===----------------------------------------------------------------------===// 1788 // Emit Methods 1789 //===----------------------------------------------------------------------===// 1790 1791 // Compute the size and offset of a DIE. The offset is relative to start of the 1792 // CU. It returns the offset after laying out the DIE. 1793 unsigned DwarfFile::computeSizeAndOffset(DIE &Die, unsigned Offset) { 1794 // Record the abbreviation. 1795 assignAbbrevNumber(Die.getAbbrev()); 1796 1797 // Get the abbreviation for this DIE. 1798 const DIEAbbrev &Abbrev = Die.getAbbrev(); 1799 1800 // Set DIE offset 1801 Die.setOffset(Offset); 1802 1803 // Start the size with the size of abbreviation code. 1804 Offset += getULEB128Size(Die.getAbbrevNumber()); 1805 1806 const SmallVectorImpl<DIEValue *> &Values = Die.getValues(); 1807 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData(); 1808 1809 // Size the DIE attribute values. 1810 for (unsigned i = 0, N = Values.size(); i < N; ++i) 1811 // Size attribute value. 1812 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm()); 1813 1814 // Get the children. 1815 const auto &Children = Die.getChildren(); 1816 1817 // Size the DIE children if any. 1818 if (!Children.empty()) { 1819 assert(Abbrev.hasChildren() && "Children flag not set"); 1820 1821 for (auto &Child : Children) 1822 Offset = computeSizeAndOffset(*Child, Offset); 1823 1824 // End of children marker. 1825 Offset += sizeof(int8_t); 1826 } 1827 1828 Die.setSize(Offset - Die.getOffset()); 1829 return Offset; 1830 } 1831 1832 // Compute the size and offset for each DIE. 1833 void DwarfFile::computeSizeAndOffsets() { 1834 // Offset from the first CU in the debug info section is 0 initially. 1835 unsigned SecOffset = 0; 1836 1837 // Iterate over each compile unit and set the size and offsets for each 1838 // DIE within each compile unit. All offsets are CU relative. 1839 for (DwarfUnit *TheU : CUs) { 1840 TheU->setDebugInfoOffset(SecOffset); 1841 1842 // CU-relative offset is reset to 0 here. 1843 unsigned Offset = sizeof(int32_t) + // Length of Unit Info 1844 TheU->getHeaderSize(); // Unit-specific headers 1845 1846 // EndOffset here is CU-relative, after laying out 1847 // all of the CU DIE. 1848 unsigned EndOffset = computeSizeAndOffset(*TheU->getUnitDie(), Offset); 1849 SecOffset += EndOffset; 1850 } 1851 } 1852 1853 // Emit initial Dwarf sections with a label at the start of each one. 1854 void DwarfDebug::emitSectionLabels() { 1855 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1856 1857 // Dwarf sections base addresses. 1858 DwarfInfoSectionSym = 1859 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info"); 1860 if (useSplitDwarf()) 1861 DwarfInfoDWOSectionSym = 1862 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo"); 1863 DwarfAbbrevSectionSym = 1864 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev"); 1865 if (useSplitDwarf()) 1866 DwarfAbbrevDWOSectionSym = emitSectionSym( 1867 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo"); 1868 if (GenerateARangeSection) 1869 emitSectionSym(Asm, TLOF.getDwarfARangesSection()); 1870 1871 DwarfLineSectionSym = 1872 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line"); 1873 if (GenerateGnuPubSections) { 1874 DwarfGnuPubNamesSectionSym = 1875 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection()); 1876 DwarfGnuPubTypesSectionSym = 1877 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection()); 1878 } else if (HasDwarfPubSections) { 1879 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection()); 1880 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection()); 1881 } 1882 1883 DwarfStrSectionSym = 1884 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string"); 1885 if (useSplitDwarf()) { 1886 DwarfStrDWOSectionSym = 1887 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string"); 1888 DwarfAddrSectionSym = 1889 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec"); 1890 DwarfDebugLocSectionSym = 1891 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc"); 1892 } else 1893 DwarfDebugLocSectionSym = 1894 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc"); 1895 DwarfDebugRangeSectionSym = 1896 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range"); 1897 } 1898 1899 // Recursively emits a debug information entry. 1900 void DwarfDebug::emitDIE(DIE &Die) { 1901 // Get the abbreviation for this DIE. 1902 const DIEAbbrev &Abbrev = Die.getAbbrev(); 1903 1904 // Emit the code (index) for the abbreviation. 1905 if (Asm->isVerbose()) 1906 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) + 1907 "] 0x" + Twine::utohexstr(Die.getOffset()) + 1908 ":0x" + Twine::utohexstr(Die.getSize()) + " " + 1909 dwarf::TagString(Abbrev.getTag())); 1910 Asm->EmitULEB128(Abbrev.getNumber()); 1911 1912 const SmallVectorImpl<DIEValue *> &Values = Die.getValues(); 1913 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData(); 1914 1915 // Emit the DIE attribute values. 1916 for (unsigned i = 0, N = Values.size(); i < N; ++i) { 1917 dwarf::Attribute Attr = AbbrevData[i].getAttribute(); 1918 dwarf::Form Form = AbbrevData[i].getForm(); 1919 assert(Form && "Too many attributes for DIE (check abbreviation)"); 1920 1921 if (Asm->isVerbose()) { 1922 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr)); 1923 if (Attr == dwarf::DW_AT_accessibility) 1924 Asm->OutStreamer.AddComment(dwarf::AccessibilityString( 1925 cast<DIEInteger>(Values[i])->getValue())); 1926 } 1927 1928 // Emit an attribute using the defined form. 1929 Values[i]->EmitValue(Asm, Form); 1930 } 1931 1932 // Emit the DIE children if any. 1933 if (Abbrev.hasChildren()) { 1934 for (auto &Child : Die.getChildren()) 1935 emitDIE(*Child); 1936 1937 Asm->OutStreamer.AddComment("End Of Children Mark"); 1938 Asm->EmitInt8(0); 1939 } 1940 } 1941 1942 // Emit the various dwarf units to the unit section USection with 1943 // the abbreviations going into ASection. 1944 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSymbol *ASectionSym) { 1945 for (DwarfUnit *TheU : CUs) { 1946 DIE *Die = TheU->getUnitDie(); 1947 const MCSection *USection = TheU->getSection(); 1948 Asm->OutStreamer.SwitchSection(USection); 1949 1950 // Emit the compile units header. 1951 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin()); 1952 1953 // Emit size of content not including length itself 1954 Asm->OutStreamer.AddComment("Length of Unit"); 1955 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize()); 1956 1957 TheU->emitHeader(ASectionSym); 1958 1959 DD->emitDIE(*Die); 1960 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd()); 1961 } 1962 } 1963 1964 // Emit the debug info section. 1965 void DwarfDebug::emitDebugInfo() { 1966 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1967 1968 Holder.emitUnits(this, DwarfAbbrevSectionSym); 1969 } 1970 1971 // Emit the abbreviation section. 1972 void DwarfDebug::emitAbbreviations() { 1973 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 1974 1975 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection()); 1976 } 1977 1978 void DwarfFile::emitAbbrevs(const MCSection *Section) { 1979 // Check to see if it is worth the effort. 1980 if (!Abbreviations.empty()) { 1981 // Start the debug abbrev section. 1982 Asm->OutStreamer.SwitchSection(Section); 1983 1984 // For each abbrevation. 1985 for (const DIEAbbrev *Abbrev : Abbreviations) { 1986 // Emit the abbrevations code (base 1 index.) 1987 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code"); 1988 1989 // Emit the abbreviations data. 1990 Abbrev->Emit(Asm); 1991 } 1992 1993 // Mark end of abbreviations. 1994 Asm->EmitULEB128(0, "EOM(3)"); 1995 } 1996 } 1997 1998 // Emit the last address of the section and the end of the line matrix. 1999 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) { 2000 // Define last address of section. 2001 Asm->OutStreamer.AddComment("Extended Op"); 2002 Asm->EmitInt8(0); 2003 2004 Asm->OutStreamer.AddComment("Op size"); 2005 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1); 2006 Asm->OutStreamer.AddComment("DW_LNE_set_address"); 2007 Asm->EmitInt8(dwarf::DW_LNE_set_address); 2008 2009 Asm->OutStreamer.AddComment("Section end label"); 2010 2011 Asm->OutStreamer.EmitSymbolValue( 2012 Asm->GetTempSymbol("section_end", SectionEnd), 2013 Asm->getDataLayout().getPointerSize()); 2014 2015 // Mark end of matrix. 2016 Asm->OutStreamer.AddComment("DW_LNE_end_sequence"); 2017 Asm->EmitInt8(0); 2018 Asm->EmitInt8(1); 2019 Asm->EmitInt8(1); 2020 } 2021 2022 // Emit visible names into a hashed accelerator table section. 2023 void DwarfDebug::emitAccelNames() { 2024 DwarfAccelTable AT( 2025 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4)); 2026 for (DwarfUnit *TheU : getUnits()) { 2027 for (const auto &GI : TheU->getAccelNames()) { 2028 StringRef Name = GI.getKey(); 2029 for (const DIE *D : GI.second) 2030 AT.AddName(Name, D); 2031 } 2032 } 2033 2034 AT.FinalizeTable(Asm, "Names"); 2035 Asm->OutStreamer.SwitchSection( 2036 Asm->getObjFileLowering().getDwarfAccelNamesSection()); 2037 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin"); 2038 Asm->OutStreamer.EmitLabel(SectionBegin); 2039 2040 // Emit the full data. 2041 AT.Emit(Asm, SectionBegin, &InfoHolder); 2042 } 2043 2044 // Emit objective C classes and categories into a hashed accelerator table 2045 // section. 2046 void DwarfDebug::emitAccelObjC() { 2047 DwarfAccelTable AT( 2048 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4)); 2049 for (DwarfUnit *TheU : getUnits()) { 2050 for (const auto &GI : TheU->getAccelObjC()) { 2051 StringRef Name = GI.getKey(); 2052 for (const DIE *D : GI.second) 2053 AT.AddName(Name, D); 2054 } 2055 } 2056 2057 AT.FinalizeTable(Asm, "ObjC"); 2058 Asm->OutStreamer.SwitchSection( 2059 Asm->getObjFileLowering().getDwarfAccelObjCSection()); 2060 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin"); 2061 Asm->OutStreamer.EmitLabel(SectionBegin); 2062 2063 // Emit the full data. 2064 AT.Emit(Asm, SectionBegin, &InfoHolder); 2065 } 2066 2067 // Emit namespace dies into a hashed accelerator table. 2068 void DwarfDebug::emitAccelNamespaces() { 2069 DwarfAccelTable AT( 2070 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4)); 2071 for (DwarfUnit *TheU : getUnits()) { 2072 for (const auto &GI : TheU->getAccelNamespace()) { 2073 StringRef Name = GI.getKey(); 2074 for (const DIE *D : GI.second) 2075 AT.AddName(Name, D); 2076 } 2077 } 2078 2079 AT.FinalizeTable(Asm, "namespac"); 2080 Asm->OutStreamer.SwitchSection( 2081 Asm->getObjFileLowering().getDwarfAccelNamespaceSection()); 2082 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin"); 2083 Asm->OutStreamer.EmitLabel(SectionBegin); 2084 2085 // Emit the full data. 2086 AT.Emit(Asm, SectionBegin, &InfoHolder); 2087 } 2088 2089 // Emit type dies into a hashed accelerator table. 2090 void DwarfDebug::emitAccelTypes() { 2091 std::vector<DwarfAccelTable::Atom> Atoms; 2092 Atoms.push_back( 2093 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4)); 2094 Atoms.push_back( 2095 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2)); 2096 Atoms.push_back( 2097 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)); 2098 DwarfAccelTable AT(Atoms); 2099 for (DwarfUnit *TheU : getUnits()) { 2100 for (const auto &GI : TheU->getAccelTypes()) { 2101 StringRef Name = GI.getKey(); 2102 for (const auto &DI : GI.second) 2103 AT.AddName(Name, DI.first, DI.second); 2104 } 2105 } 2106 2107 AT.FinalizeTable(Asm, "types"); 2108 Asm->OutStreamer.SwitchSection( 2109 Asm->getObjFileLowering().getDwarfAccelTypesSection()); 2110 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin"); 2111 Asm->OutStreamer.EmitLabel(SectionBegin); 2112 2113 // Emit the full data. 2114 AT.Emit(Asm, SectionBegin, &InfoHolder); 2115 } 2116 2117 // Public name handling. 2118 // The format for the various pubnames: 2119 // 2120 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU 2121 // for the DIE that is named. 2122 // 2123 // gnu pubnames - offset/index value/name tuples where the offset is the offset 2124 // into the CU and the index value is computed according to the type of value 2125 // for the DIE that is named. 2126 // 2127 // For type units the offset is the offset of the skeleton DIE. For split dwarf 2128 // it's the offset within the debug_info/debug_types dwo section, however, the 2129 // reference in the pubname header doesn't change. 2130 2131 /// computeIndexValue - Compute the gdb index value for the DIE and CU. 2132 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, 2133 const DIE *Die) { 2134 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC; 2135 2136 // We could have a specification DIE that has our most of our knowledge, 2137 // look for that now. 2138 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification); 2139 if (SpecVal) { 2140 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry(); 2141 if (SpecDIE->findAttribute(dwarf::DW_AT_external)) 2142 Linkage = dwarf::GIEL_EXTERNAL; 2143 } else if (Die->findAttribute(dwarf::DW_AT_external)) 2144 Linkage = dwarf::GIEL_EXTERNAL; 2145 2146 switch (Die->getTag()) { 2147 case dwarf::DW_TAG_class_type: 2148 case dwarf::DW_TAG_structure_type: 2149 case dwarf::DW_TAG_union_type: 2150 case dwarf::DW_TAG_enumeration_type: 2151 return dwarf::PubIndexEntryDescriptor( 2152 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus 2153 ? dwarf::GIEL_STATIC 2154 : dwarf::GIEL_EXTERNAL); 2155 case dwarf::DW_TAG_typedef: 2156 case dwarf::DW_TAG_base_type: 2157 case dwarf::DW_TAG_subrange_type: 2158 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC); 2159 case dwarf::DW_TAG_namespace: 2160 return dwarf::GIEK_TYPE; 2161 case dwarf::DW_TAG_subprogram: 2162 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage); 2163 case dwarf::DW_TAG_constant: 2164 case dwarf::DW_TAG_variable: 2165 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage); 2166 case dwarf::DW_TAG_enumerator: 2167 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, 2168 dwarf::GIEL_STATIC); 2169 default: 2170 return dwarf::GIEK_NONE; 2171 } 2172 } 2173 2174 /// emitDebugPubNames - Emit visible names into a debug pubnames section. 2175 /// 2176 void DwarfDebug::emitDebugPubNames(bool GnuStyle) { 2177 const MCSection *PSec = 2178 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection() 2179 : Asm->getObjFileLowering().getDwarfPubNamesSection(); 2180 2181 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames); 2182 } 2183 2184 void DwarfDebug::emitDebugPubSection( 2185 bool GnuStyle, const MCSection *PSec, StringRef Name, 2186 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) { 2187 for (const auto &NU : CUMap) { 2188 DwarfCompileUnit *TheU = NU.second; 2189 2190 const auto &Globals = (TheU->*Accessor)(); 2191 2192 if (Globals.empty()) 2193 continue; 2194 2195 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton())) 2196 TheU = Skeleton; 2197 unsigned ID = TheU->getUniqueID(); 2198 2199 // Start the dwarf pubnames section. 2200 Asm->OutStreamer.SwitchSection(PSec); 2201 2202 // Emit the header. 2203 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info"); 2204 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID); 2205 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID); 2206 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); 2207 2208 Asm->OutStreamer.EmitLabel(BeginLabel); 2209 2210 Asm->OutStreamer.AddComment("DWARF Version"); 2211 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); 2212 2213 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info"); 2214 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym()); 2215 2216 Asm->OutStreamer.AddComment("Compilation Unit Length"); 2217 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4); 2218 2219 // Emit the pubnames for this compilation unit. 2220 for (const auto &GI : Globals) { 2221 const char *Name = GI.getKeyData(); 2222 const DIE *Entity = GI.second; 2223 2224 Asm->OutStreamer.AddComment("DIE offset"); 2225 Asm->EmitInt32(Entity->getOffset()); 2226 2227 if (GnuStyle) { 2228 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity); 2229 Asm->OutStreamer.AddComment( 2230 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " + 2231 dwarf::GDBIndexEntryLinkageString(Desc.Linkage)); 2232 Asm->EmitInt8(Desc.toBits()); 2233 } 2234 2235 Asm->OutStreamer.AddComment("External Name"); 2236 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1)); 2237 } 2238 2239 Asm->OutStreamer.AddComment("End Mark"); 2240 Asm->EmitInt32(0); 2241 Asm->OutStreamer.EmitLabel(EndLabel); 2242 } 2243 } 2244 2245 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) { 2246 const MCSection *PSec = 2247 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection() 2248 : Asm->getObjFileLowering().getDwarfPubTypesSection(); 2249 2250 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes); 2251 } 2252 2253 // Emit strings into a string section. 2254 void DwarfFile::emitStrings(const MCSection *StrSection, 2255 const MCSection *OffsetSection = NULL, 2256 const MCSymbol *StrSecSym = NULL) { 2257 2258 if (StringPool.empty()) 2259 return; 2260 2261 // Start the dwarf str section. 2262 Asm->OutStreamer.SwitchSection(StrSection); 2263 2264 // Get all of the string pool entries and put them in an array by their ID so 2265 // we can sort them. 2266 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries; 2267 2268 for (const auto &I : StringPool) 2269 Entries.push_back(std::make_pair(I.second.second, &I)); 2270 2271 array_pod_sort(Entries.begin(), Entries.end()); 2272 2273 for (const auto &Entry : Entries) { 2274 // Emit a label for reference from debug information entries. 2275 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first); 2276 2277 // Emit the string itself with a terminating null byte. 2278 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(), 2279 Entry.second->getKeyLength() + 1)); 2280 } 2281 2282 // If we've got an offset section go ahead and emit that now as well. 2283 if (OffsetSection) { 2284 Asm->OutStreamer.SwitchSection(OffsetSection); 2285 unsigned offset = 0; 2286 unsigned size = 4; // FIXME: DWARF64 is 8. 2287 for (const auto &Entry : Entries) { 2288 Asm->OutStreamer.EmitIntValue(offset, size); 2289 offset += Entry.second->getKeyLength() + 1; 2290 } 2291 } 2292 } 2293 2294 // Emit addresses into the section given. 2295 void DwarfFile::emitAddresses(const MCSection *AddrSection) { 2296 2297 if (AddressPool.empty()) 2298 return; 2299 2300 // Start the dwarf addr section. 2301 Asm->OutStreamer.SwitchSection(AddrSection); 2302 2303 // Order the address pool entries by ID 2304 SmallVector<const MCExpr *, 64> Entries(AddressPool.size()); 2305 2306 for (const auto &I : AddressPool) 2307 Entries[I.second.Number] = 2308 I.second.TLS 2309 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first) 2310 : MCSymbolRefExpr::Create(I.first, Asm->OutContext); 2311 2312 for (const MCExpr *Entry : Entries) 2313 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize()); 2314 } 2315 2316 // Emit visible names into a debug str section. 2317 void DwarfDebug::emitDebugStr() { 2318 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder; 2319 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection()); 2320 } 2321 2322 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer, 2323 const DebugLocEntry &Entry) { 2324 DIVariable DV(Entry.getVariable()); 2325 if (Entry.isInt()) { 2326 DIBasicType BTy(resolve(DV.getType())); 2327 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed || 2328 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) { 2329 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts"); 2330 Streamer.EmitSLEB128(Entry.getInt()); 2331 } else { 2332 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu"); 2333 Streamer.EmitULEB128(Entry.getInt()); 2334 } 2335 } else if (Entry.isLocation()) { 2336 MachineLocation Loc = Entry.getLoc(); 2337 if (!DV.hasComplexAddress()) 2338 // Regular entry. 2339 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect()); 2340 else { 2341 // Complex address entry. 2342 unsigned N = DV.getNumAddrElements(); 2343 unsigned i = 0; 2344 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) { 2345 if (Loc.getOffset()) { 2346 i = 2; 2347 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect()); 2348 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref"); 2349 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst"); 2350 Streamer.EmitSLEB128(DV.getAddrElement(1)); 2351 } else { 2352 // If first address element is OpPlus then emit 2353 // DW_OP_breg + Offset instead of DW_OP_reg + Offset. 2354 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1)); 2355 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect()); 2356 i = 2; 2357 } 2358 } else { 2359 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect()); 2360 } 2361 2362 // Emit remaining complex address elements. 2363 for (; i < N; ++i) { 2364 uint64_t Element = DV.getAddrElement(i); 2365 if (Element == DIBuilder::OpPlus) { 2366 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst"); 2367 Streamer.EmitULEB128(DV.getAddrElement(++i)); 2368 } else if (Element == DIBuilder::OpDeref) { 2369 if (!Loc.isReg()) 2370 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref"); 2371 } else 2372 llvm_unreachable("unknown Opcode found in complex address"); 2373 } 2374 } 2375 } 2376 // else ... ignore constant fp. There is not any good way to 2377 // to represent them here in dwarf. 2378 // FIXME: ^ 2379 } 2380 2381 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) { 2382 Asm->OutStreamer.AddComment("Loc expr size"); 2383 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol(); 2384 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol(); 2385 Asm->EmitLabelDifference(end, begin, 2); 2386 Asm->OutStreamer.EmitLabel(begin); 2387 // Emit the entry. 2388 APByteStreamer Streamer(*Asm); 2389 emitDebugLocEntry(Streamer, Entry); 2390 // Close the range. 2391 Asm->OutStreamer.EmitLabel(end); 2392 } 2393 2394 // Emit locations into the debug loc section. 2395 void DwarfDebug::emitDebugLoc() { 2396 // Start the dwarf loc section. 2397 Asm->OutStreamer.SwitchSection( 2398 Asm->getObjFileLowering().getDwarfLocSection()); 2399 unsigned char Size = Asm->getDataLayout().getPointerSize(); 2400 for (const auto &DebugLoc : DotDebugLocEntries) { 2401 Asm->OutStreamer.EmitLabel(DebugLoc.Label); 2402 for (const auto &Entry : DebugLoc.List) { 2403 // Set up the range. This range is relative to the entry point of the 2404 // compile unit. This is a hard coded 0 for low_pc when we're emitting 2405 // ranges, or the DW_AT_low_pc on the compile unit otherwise. 2406 const DwarfCompileUnit *CU = Entry.getCU(); 2407 if (CU->getRanges().size() == 1) { 2408 // Grab the begin symbol from the first range as our base. 2409 const MCSymbol *Base = CU->getRanges()[0].getStart(); 2410 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size); 2411 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size); 2412 } else { 2413 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size); 2414 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size); 2415 } 2416 2417 emitDebugLocEntryLocation(Entry); 2418 } 2419 Asm->OutStreamer.EmitIntValue(0, Size); 2420 Asm->OutStreamer.EmitIntValue(0, Size); 2421 } 2422 } 2423 2424 void DwarfDebug::emitDebugLocDWO() { 2425 Asm->OutStreamer.SwitchSection( 2426 Asm->getObjFileLowering().getDwarfLocDWOSection()); 2427 for (const auto &DebugLoc : DotDebugLocEntries) { 2428 Asm->OutStreamer.EmitLabel(DebugLoc.Label); 2429 for (const auto &Entry : DebugLoc.List) { 2430 // Just always use start_length for now - at least that's one address 2431 // rather than two. We could get fancier and try to, say, reuse an 2432 // address we know we've emitted elsewhere (the start of the function? 2433 // The start of the CU or CU subrange that encloses this range?) 2434 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry); 2435 unsigned idx = InfoHolder.getAddrPoolIndex(Entry.getBeginSym()); 2436 Asm->EmitULEB128(idx); 2437 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4); 2438 2439 emitDebugLocEntryLocation(Entry); 2440 } 2441 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry); 2442 } 2443 } 2444 2445 struct ArangeSpan { 2446 const MCSymbol *Start, *End; 2447 }; 2448 2449 // Emit a debug aranges section, containing a CU lookup for any 2450 // address we can tie back to a CU. 2451 void DwarfDebug::emitDebugARanges() { 2452 // Start the dwarf aranges section. 2453 Asm->OutStreamer.SwitchSection( 2454 Asm->getObjFileLowering().getDwarfARangesSection()); 2455 2456 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType; 2457 2458 SpansType Spans; 2459 2460 // Build a list of sections used. 2461 std::vector<const MCSection *> Sections; 2462 for (const auto &it : SectionMap) { 2463 const MCSection *Section = it.first; 2464 Sections.push_back(Section); 2465 } 2466 2467 // Sort the sections into order. 2468 // This is only done to ensure consistent output order across different runs. 2469 std::sort(Sections.begin(), Sections.end(), SectionSort); 2470 2471 // Build a set of address spans, sorted by CU. 2472 for (const MCSection *Section : Sections) { 2473 SmallVector<SymbolCU, 8> &List = SectionMap[Section]; 2474 if (List.size() < 2) 2475 continue; 2476 2477 // Sort the symbols by offset within the section. 2478 std::sort(List.begin(), List.end(), 2479 [&](const SymbolCU &A, const SymbolCU &B) { 2480 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0; 2481 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0; 2482 2483 // Symbols with no order assigned should be placed at the end. 2484 // (e.g. section end labels) 2485 if (IA == 0) 2486 return false; 2487 if (IB == 0) 2488 return true; 2489 return IA < IB; 2490 }); 2491 2492 // If we have no section (e.g. common), just write out 2493 // individual spans for each symbol. 2494 if (Section == NULL) { 2495 for (const SymbolCU &Cur : List) { 2496 ArangeSpan Span; 2497 Span.Start = Cur.Sym; 2498 Span.End = NULL; 2499 if (Cur.CU) 2500 Spans[Cur.CU].push_back(Span); 2501 } 2502 } else { 2503 // Build spans between each label. 2504 const MCSymbol *StartSym = List[0].Sym; 2505 for (size_t n = 1, e = List.size(); n < e; n++) { 2506 const SymbolCU &Prev = List[n - 1]; 2507 const SymbolCU &Cur = List[n]; 2508 2509 // Try and build the longest span we can within the same CU. 2510 if (Cur.CU != Prev.CU) { 2511 ArangeSpan Span; 2512 Span.Start = StartSym; 2513 Span.End = Cur.Sym; 2514 Spans[Prev.CU].push_back(Span); 2515 StartSym = Cur.Sym; 2516 } 2517 } 2518 } 2519 } 2520 2521 unsigned PtrSize = Asm->getDataLayout().getPointerSize(); 2522 2523 // Build a list of CUs used. 2524 std::vector<DwarfCompileUnit *> CUs; 2525 for (const auto &it : Spans) { 2526 DwarfCompileUnit *CU = it.first; 2527 CUs.push_back(CU); 2528 } 2529 2530 // Sort the CU list (again, to ensure consistent output order). 2531 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) { 2532 return A->getUniqueID() < B->getUniqueID(); 2533 }); 2534 2535 // Emit an arange table for each CU we used. 2536 for (DwarfCompileUnit *CU : CUs) { 2537 std::vector<ArangeSpan> &List = Spans[CU]; 2538 2539 // Emit size of content not including length itself. 2540 unsigned ContentSize = 2541 sizeof(int16_t) + // DWARF ARange version number 2542 sizeof(int32_t) + // Offset of CU in the .debug_info section 2543 sizeof(int8_t) + // Pointer Size (in bytes) 2544 sizeof(int8_t); // Segment Size (in bytes) 2545 2546 unsigned TupleSize = PtrSize * 2; 2547 2548 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple. 2549 unsigned Padding = 2550 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize); 2551 2552 ContentSize += Padding; 2553 ContentSize += (List.size() + 1) * TupleSize; 2554 2555 // For each compile unit, write the list of spans it covers. 2556 Asm->OutStreamer.AddComment("Length of ARange Set"); 2557 Asm->EmitInt32(ContentSize); 2558 Asm->OutStreamer.AddComment("DWARF Arange version number"); 2559 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); 2560 Asm->OutStreamer.AddComment("Offset Into Debug Info Section"); 2561 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym()); 2562 Asm->OutStreamer.AddComment("Address Size (in bytes)"); 2563 Asm->EmitInt8(PtrSize); 2564 Asm->OutStreamer.AddComment("Segment Size (in bytes)"); 2565 Asm->EmitInt8(0); 2566 2567 Asm->OutStreamer.EmitFill(Padding, 0xff); 2568 2569 for (const ArangeSpan &Span : List) { 2570 Asm->EmitLabelReference(Span.Start, PtrSize); 2571 2572 // Calculate the size as being from the span start to it's end. 2573 if (Span.End) { 2574 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize); 2575 } else { 2576 // For symbols without an end marker (e.g. common), we 2577 // write a single arange entry containing just that one symbol. 2578 uint64_t Size = SymSize[Span.Start]; 2579 if (Size == 0) 2580 Size = 1; 2581 2582 Asm->OutStreamer.EmitIntValue(Size, PtrSize); 2583 } 2584 } 2585 2586 Asm->OutStreamer.AddComment("ARange terminator"); 2587 Asm->OutStreamer.EmitIntValue(0, PtrSize); 2588 Asm->OutStreamer.EmitIntValue(0, PtrSize); 2589 } 2590 } 2591 2592 // Emit visible names into a debug ranges section. 2593 void DwarfDebug::emitDebugRanges() { 2594 // Start the dwarf ranges section. 2595 Asm->OutStreamer.SwitchSection( 2596 Asm->getObjFileLowering().getDwarfRangesSection()); 2597 2598 // Size for our labels. 2599 unsigned char Size = Asm->getDataLayout().getPointerSize(); 2600 2601 // Grab the specific ranges for the compile units in the module. 2602 for (const auto &I : CUMap) { 2603 DwarfCompileUnit *TheCU = I.second; 2604 2605 // Emit a symbol so we can find the beginning of our ranges. 2606 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange()); 2607 2608 // Iterate over the misc ranges for the compile units in the module. 2609 for (const RangeSpanList &List : TheCU->getRangeLists()) { 2610 // Emit our symbol so we can find the beginning of the range. 2611 Asm->OutStreamer.EmitLabel(List.getSym()); 2612 2613 for (const RangeSpan &Range : List.getRanges()) { 2614 const MCSymbol *Begin = Range.getStart(); 2615 const MCSymbol *End = Range.getEnd(); 2616 assert(Begin && "Range without a begin symbol?"); 2617 assert(End && "Range without an end symbol?"); 2618 Asm->OutStreamer.EmitSymbolValue(Begin, Size); 2619 Asm->OutStreamer.EmitSymbolValue(End, Size); 2620 } 2621 2622 // And terminate the list with two 0 values. 2623 Asm->OutStreamer.EmitIntValue(0, Size); 2624 Asm->OutStreamer.EmitIntValue(0, Size); 2625 } 2626 2627 // Now emit a range for the CU itself. 2628 if (TheCU->getRanges().size() > 1) { 2629 Asm->OutStreamer.EmitLabel( 2630 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID())); 2631 for (const RangeSpan &Range : TheCU->getRanges()) { 2632 const MCSymbol *Begin = Range.getStart(); 2633 const MCSymbol *End = Range.getEnd(); 2634 assert(Begin && "Range without a begin symbol?"); 2635 assert(End && "Range without an end symbol?"); 2636 Asm->OutStreamer.EmitSymbolValue(Begin, Size); 2637 Asm->OutStreamer.EmitSymbolValue(End, Size); 2638 } 2639 // And terminate the list with two 0 values. 2640 Asm->OutStreamer.EmitIntValue(0, Size); 2641 Asm->OutStreamer.EmitIntValue(0, Size); 2642 } 2643 } 2644 } 2645 2646 // DWARF5 Experimental Separate Dwarf emitters. 2647 2648 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die, 2649 DwarfUnit *NewU) { 2650 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name, 2651 U->getCUNode().getSplitDebugFilename()); 2652 2653 if (!CompilationDir.empty()) 2654 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 2655 2656 addGnuPubAttributes(NewU, Die); 2657 2658 SkeletonHolder.addUnit(NewU); 2659 } 2660 2661 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list, 2662 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id, 2663 // DW_AT_addr_base, DW_AT_ranges_base. 2664 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) { 2665 2666 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit); 2667 DwarfCompileUnit *NewCU = new DwarfCompileUnit( 2668 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder); 2669 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(), 2670 DwarfInfoSectionSym); 2671 2672 NewCU->initStmtList(DwarfLineSectionSym); 2673 2674 initSkeletonUnit(CU, Die, NewCU); 2675 2676 return NewCU; 2677 } 2678 2679 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name, 2680 // DW_AT_addr_base. 2681 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) { 2682 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>( 2683 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]); 2684 2685 DIE *Die = new DIE(dwarf::DW_TAG_type_unit); 2686 DwarfTypeUnit *NewTU = 2687 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder); 2688 NewTU->setTypeSignature(TU->getTypeSignature()); 2689 NewTU->setType(NULL); 2690 NewTU->initSection( 2691 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature())); 2692 2693 initSkeletonUnit(TU, Die, NewTU); 2694 return NewTU; 2695 } 2696 2697 // Emit the .debug_info.dwo section for separated dwarf. This contains the 2698 // compile units that would normally be in debug_info. 2699 void DwarfDebug::emitDebugInfoDWO() { 2700 assert(useSplitDwarf() && "No split dwarf debug info?"); 2701 // Don't pass an abbrev symbol, using a constant zero instead so as not to 2702 // emit relocations into the dwo file. 2703 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr); 2704 } 2705 2706 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the 2707 // abbreviations for the .debug_info.dwo section. 2708 void DwarfDebug::emitDebugAbbrevDWO() { 2709 assert(useSplitDwarf() && "No split dwarf?"); 2710 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection()); 2711 } 2712 2713 void DwarfDebug::emitDebugLineDWO() { 2714 assert(useSplitDwarf() && "No split dwarf?"); 2715 Asm->OutStreamer.SwitchSection( 2716 Asm->getObjFileLowering().getDwarfLineDWOSection()); 2717 SplitTypeUnitFileTable.Emit(Asm->OutStreamer); 2718 } 2719 2720 // Emit the .debug_str.dwo section for separated dwarf. This contains the 2721 // string section and is identical in format to traditional .debug_str 2722 // sections. 2723 void DwarfDebug::emitDebugStrDWO() { 2724 assert(useSplitDwarf() && "No split dwarf?"); 2725 const MCSection *OffSec = 2726 Asm->getObjFileLowering().getDwarfStrOffDWOSection(); 2727 const MCSymbol *StrSym = DwarfStrSectionSym; 2728 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(), 2729 OffSec, StrSym); 2730 } 2731 2732 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) { 2733 if (!useSplitDwarf()) 2734 return nullptr; 2735 if (SingleCU) 2736 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory()); 2737 return &SplitTypeUnitFileTable; 2738 } 2739 2740 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU, 2741 StringRef Identifier, DIE *RefDie, 2742 DICompositeType CTy) { 2743 // Flag the type unit reference as a declaration so that if it contains 2744 // members (implicit special members, static data member definitions, member 2745 // declarations for definitions in this CU, etc) consumers don't get confused 2746 // and think this is a full definition. 2747 CU.addFlag(RefDie, dwarf::DW_AT_declaration); 2748 2749 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy]; 2750 if (TU) { 2751 CU.addDIETypeSignature(RefDie, *TU); 2752 return; 2753 } 2754 2755 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit); 2756 DwarfTypeUnit *NewTU = 2757 new DwarfTypeUnit(InfoHolder.getUnits().size(), UnitDie, CU, Asm, this, 2758 &InfoHolder, getDwoLineTable(CU)); 2759 TU = NewTU; 2760 InfoHolder.addUnit(NewTU); 2761 2762 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 2763 CU.getLanguage()); 2764 2765 MD5 Hash; 2766 Hash.update(Identifier); 2767 // ... take the least significant 8 bytes and return those. Our MD5 2768 // implementation always returns its results in little endian, swap bytes 2769 // appropriately. 2770 MD5::MD5Result Result; 2771 Hash.final(Result); 2772 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8); 2773 NewTU->setTypeSignature(Signature); 2774 if (useSplitDwarf()) 2775 NewTU->setSkeleton(constructSkeletonTU(NewTU)); 2776 else 2777 CU.applyStmtList(*UnitDie); 2778 2779 NewTU->setType(NewTU->createTypeDIE(CTy)); 2780 2781 NewTU->initSection( 2782 useSplitDwarf() 2783 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature) 2784 : Asm->getObjFileLowering().getDwarfTypesSection(Signature)); 2785 2786 CU.addDIETypeSignature(RefDie, *NewTU); 2787 } 2788 2789 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D, 2790 MCSymbol *Begin, MCSymbol *End) { 2791 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin); 2792 if (DwarfVersion < 4) 2793 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End); 2794 else 2795 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin); 2796 } 2797