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