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