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