DwarfDebug.cpp revision e56902effc5e67c0a1c53a712f8d67b55aa9ce97
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 "DwarfCompileUnit.h" 18#include "llvm/Constants.h" 19#include "llvm/Module.h" 20#include "llvm/Instructions.h" 21#include "llvm/CodeGen/MachineFunction.h" 22#include "llvm/CodeGen/MachineModuleInfo.h" 23#include "llvm/MC/MCAsmInfo.h" 24#include "llvm/MC/MCSection.h" 25#include "llvm/MC/MCStreamer.h" 26#include "llvm/MC/MCSymbol.h" 27#include "llvm/Target/TargetData.h" 28#include "llvm/Target/TargetFrameLowering.h" 29#include "llvm/Target/TargetLoweringObjectFile.h" 30#include "llvm/Target/TargetMachine.h" 31#include "llvm/Target/TargetRegisterInfo.h" 32#include "llvm/Target/TargetOptions.h" 33#include "llvm/Analysis/DebugInfo.h" 34#include "llvm/Analysis/DIBuilder.h" 35#include "llvm/ADT/Statistic.h" 36#include "llvm/ADT/STLExtras.h" 37#include "llvm/ADT/StringExtras.h" 38#include "llvm/Support/CommandLine.h" 39#include "llvm/Support/Debug.h" 40#include "llvm/Support/ErrorHandling.h" 41#include "llvm/Support/ValueHandle.h" 42#include "llvm/Support/FormattedStream.h" 43#include "llvm/Support/Timer.h" 44#include "llvm/Support/Path.h" 45using namespace llvm; 46 47static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print", 48 cl::Hidden, 49 cl::desc("Disable debug info printing")); 50 51static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden, 52 cl::desc("Make an absence of debug location information explicit."), 53 cl::init(false)); 54 55namespace { 56 const char *DWARFGroupName = "DWARF Emission"; 57 const char *DbgTimerName = "DWARF Debug Writer"; 58} // end anonymous namespace 59 60//===----------------------------------------------------------------------===// 61 62/// Configuration values for initial hash set sizes (log2). 63/// 64static const unsigned InitAbbreviationsSetSize = 9; // log2(512) 65 66namespace llvm { 67 68DIType DbgVariable::getType() const { 69 DIType Ty = Var.getType(); 70 // FIXME: isBlockByrefVariable should be reformulated in terms of complex 71 // addresses instead. 72 if (Var.isBlockByrefVariable()) { 73 /* Byref variables, in Blocks, are declared by the programmer as 74 "SomeType VarName;", but the compiler creates a 75 __Block_byref_x_VarName struct, and gives the variable VarName 76 either the struct, or a pointer to the struct, as its type. This 77 is necessary for various behind-the-scenes things the compiler 78 needs to do with by-reference variables in blocks. 79 80 However, as far as the original *programmer* is concerned, the 81 variable should still have type 'SomeType', as originally declared. 82 83 The following function dives into the __Block_byref_x_VarName 84 struct to find the original type of the variable. This will be 85 passed back to the code generating the type for the Debug 86 Information Entry for the variable 'VarName'. 'VarName' will then 87 have the original type 'SomeType' in its debug information. 88 89 The original type 'SomeType' will be the type of the field named 90 'VarName' inside the __Block_byref_x_VarName struct. 91 92 NOTE: In order for this to not completely fail on the debugger 93 side, the Debug Information Entry for the variable VarName needs to 94 have a DW_AT_location that tells the debugger how to unwind through 95 the pointers and __Block_byref_x_VarName struct to find the actual 96 value of the variable. The function addBlockByrefType does this. */ 97 DIType subType = Ty; 98 unsigned tag = Ty.getTag(); 99 100 if (tag == dwarf::DW_TAG_pointer_type) { 101 DIDerivedType DTy = DIDerivedType(Ty); 102 subType = DTy.getTypeDerivedFrom(); 103 } 104 105 DICompositeType blockStruct = DICompositeType(subType); 106 DIArray Elements = blockStruct.getTypeArray(); 107 108 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) { 109 DIDescriptor Element = Elements.getElement(i); 110 DIDerivedType DT = DIDerivedType(Element); 111 if (getName() == DT.getName()) 112 return (DT.getTypeDerivedFrom()); 113 } 114 return Ty; 115 } 116 return Ty; 117} 118 119} // end llvm namespace 120 121DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M) 122 : Asm(A), MMI(Asm->MMI), FirstCU(0), 123 AbbreviationsSet(InitAbbreviationsSetSize), 124 PrevLabel(NULL) { 125 NextStringPoolNumber = 0; 126 127 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0; 128 DwarfStrSectionSym = TextSectionSym = 0; 129 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0; 130 FunctionBeginSym = FunctionEndSym = 0; 131 { 132 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled); 133 beginModule(M); 134 } 135} 136DwarfDebug::~DwarfDebug() { 137} 138 139MCSymbol *DwarfDebug::getStringPool() { 140 return Asm->GetTempSymbol("section_str"); 141} 142 143MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) { 144 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str]; 145 if (Entry.first) return Entry.first; 146 147 Entry.second = NextStringPoolNumber++; 148 return Entry.first = Asm->GetTempSymbol("string", Entry.second); 149} 150 151 152/// assignAbbrevNumber - Define a unique number for the abbreviation. 153/// 154void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) { 155 // Profile the node so that we can make it unique. 156 FoldingSetNodeID ID; 157 Abbrev.Profile(ID); 158 159 // Check the set for priors. 160 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev); 161 162 // If it's newly added. 163 if (InSet == &Abbrev) { 164 // Add to abbreviation list. 165 Abbreviations.push_back(&Abbrev); 166 167 // Assign the vector position + 1 as its number. 168 Abbrev.setNumber(Abbreviations.size()); 169 } else { 170 // Assign existing abbreviation number. 171 Abbrev.setNumber(InSet->getNumber()); 172 } 173} 174 175/// getRealLinkageName - If special LLVM prefix that is used to inform the asm 176/// printer to not emit usual symbol prefix before the symbol name is used then 177/// return linkage name after skipping this special LLVM prefix. 178static StringRef getRealLinkageName(StringRef LinkageName) { 179 char One = '\1'; 180 if (LinkageName.startswith(StringRef(&One, 1))) 181 return LinkageName.substr(1); 182 return LinkageName; 183} 184 185/// updateSubprogramScopeDIE - Find DIE for the given subprogram and 186/// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes. 187/// If there are global variables in this scope then create and insert 188/// DIEs for these variables. 189DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU, 190 const MDNode *SPNode) { 191 DIE *SPDie = SPCU->getDIE(SPNode); 192 193 assert(SPDie && "Unable to find subprogram DIE!"); 194 DISubprogram SP(SPNode); 195 196 DISubprogram SPDecl = SP.getFunctionDeclaration(); 197 if (!SPDecl.isSubprogram()) { 198 // There is not any need to generate specification DIE for a function 199 // defined at compile unit level. If a function is defined inside another 200 // function then gdb prefers the definition at top level and but does not 201 // expect specification DIE in parent function. So avoid creating 202 // specification DIE for a function defined inside a function. 203 if (SP.isDefinition() && !SP.getContext().isCompileUnit() && 204 !SP.getContext().isFile() && 205 !isSubprogramContext(SP.getContext())) { 206 SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1); 207 208 // Add arguments. 209 DICompositeType SPTy = SP.getType(); 210 DIArray Args = SPTy.getTypeArray(); 211 unsigned SPTag = SPTy.getTag(); 212 if (SPTag == dwarf::DW_TAG_subroutine_type) 213 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) { 214 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter); 215 DIType ATy = DIType(DIType(Args.getElement(i))); 216 SPCU->addType(Arg, ATy); 217 if (ATy.isArtificial()) 218 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); 219 SPDie->addChild(Arg); 220 } 221 DIE *SPDeclDie = SPDie; 222 SPDie = new DIE(dwarf::DW_TAG_subprogram); 223 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4, 224 SPDeclDie); 225 SPCU->addDie(SPDie); 226 } 227 } 228 // Pick up abstract subprogram DIE. 229 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) { 230 SPDie = new DIE(dwarf::DW_TAG_subprogram); 231 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, 232 dwarf::DW_FORM_ref4, AbsSPDIE); 233 SPCU->addDie(SPDie); 234 } 235 236 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 237 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber())); 238 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, 239 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber())); 240 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo(); 241 MachineLocation Location(RI->getFrameRegister(*Asm->MF)); 242 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location); 243 244 return SPDie; 245} 246 247/// constructLexicalScope - Construct new DW_TAG_lexical_block 248/// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels. 249DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU, 250 LexicalScope *Scope) { 251 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block); 252 if (Scope->isAbstractScope()) 253 return ScopeDIE; 254 255 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges(); 256 if (Ranges.empty()) 257 return 0; 258 259 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(); 260 if (Ranges.size() > 1) { 261 // .debug_range section has not been laid out yet. Emit offset in 262 // .debug_range as a uint, size 4, for now. emitDIE will handle 263 // DW_AT_ranges appropriately. 264 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4, 265 DebugRangeSymbols.size() 266 * Asm->getTargetData().getPointerSize()); 267 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(), 268 RE = Ranges.end(); RI != RE; ++RI) { 269 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first)); 270 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second)); 271 } 272 DebugRangeSymbols.push_back(NULL); 273 DebugRangeSymbols.push_back(NULL); 274 return ScopeDIE; 275 } 276 277 const MCSymbol *Start = getLabelBeforeInsn(RI->first); 278 const MCSymbol *End = getLabelAfterInsn(RI->second); 279 280 if (End == 0) return 0; 281 282 assert(Start->isDefined() && "Invalid starting label for an inlined scope!"); 283 assert(End->isDefined() && "Invalid end label for an inlined scope!"); 284 285 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start); 286 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End); 287 288 return ScopeDIE; 289} 290 291/// constructInlinedScopeDIE - This scope represents inlined body of 292/// a function. Construct DIE to represent this concrete inlined copy 293/// of the function. 294DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU, 295 LexicalScope *Scope) { 296 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges(); 297 assert(Ranges.empty() == false && 298 "LexicalScope does not have instruction markers!"); 299 300 if (!Scope->getScopeNode()) 301 return NULL; 302 DIScope DS(Scope->getScopeNode()); 303 DISubprogram InlinedSP = getDISubprogram(DS); 304 DIE *OriginDIE = TheCU->getDIE(InlinedSP); 305 if (!OriginDIE) { 306 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram."); 307 return NULL; 308 } 309 310 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(); 311 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first); 312 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second); 313 314 if (StartLabel == 0 || EndLabel == 0) { 315 assert(0 && "Unexpected Start and End labels for a inlined scope!"); 316 return 0; 317 } 318 assert(StartLabel->isDefined() && 319 "Invalid starting label for an inlined scope!"); 320 assert(EndLabel->isDefined() && 321 "Invalid end label for an inlined scope!"); 322 323 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine); 324 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, 325 dwarf::DW_FORM_ref4, OriginDIE); 326 327 if (Ranges.size() > 1) { 328 // .debug_range section has not been laid out yet. Emit offset in 329 // .debug_range as a uint, size 4, for now. emitDIE will handle 330 // DW_AT_ranges appropriately. 331 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4, 332 DebugRangeSymbols.size() 333 * Asm->getTargetData().getPointerSize()); 334 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(), 335 RE = Ranges.end(); RI != RE; ++RI) { 336 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first)); 337 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second)); 338 } 339 DebugRangeSymbols.push_back(NULL); 340 DebugRangeSymbols.push_back(NULL); 341 } else { 342 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 343 StartLabel); 344 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, 345 EndLabel); 346 } 347 348 InlinedSubprogramDIEs.insert(OriginDIE); 349 350 // Track the start label for this inlined function. 351 //.debug_inlined section specification does not clearly state how 352 // to emit inlined scope that is split into multiple instruction ranges. 353 // For now, use first instruction range and emit low_pc/high_pc pair and 354 // corresponding .debug_inlined section entry for this pair. 355 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator 356 I = InlineInfo.find(InlinedSP); 357 358 if (I == InlineInfo.end()) { 359 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE)); 360 InlinedSPNodes.push_back(InlinedSP); 361 } else 362 I->second.push_back(std::make_pair(StartLabel, ScopeDIE)); 363 364 DILocation DL(Scope->getInlinedAt()); 365 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID()); 366 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber()); 367 368 return ScopeDIE; 369} 370 371/// constructScopeDIE - Construct a DIE for this scope. 372DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) { 373 if (!Scope || !Scope->getScopeNode()) 374 return NULL; 375 376 SmallVector<DIE *, 8> Children; 377 378 // Collect arguments for current function. 379 if (LScopes.isCurrentFunctionScope(Scope)) 380 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i) 381 if (DbgVariable *ArgDV = CurrentFnArguments[i]) 382 if (DIE *Arg = 383 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) 384 Children.push_back(Arg); 385 386 // Collect lexical scope children first. 387 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope); 388 for (unsigned i = 0, N = Variables.size(); i < N; ++i) 389 if (DIE *Variable = 390 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) 391 Children.push_back(Variable); 392 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren(); 393 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) 394 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j])) 395 Children.push_back(Nested); 396 DIScope DS(Scope->getScopeNode()); 397 DIE *ScopeDIE = NULL; 398 if (Scope->getInlinedAt()) 399 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope); 400 else if (DS.isSubprogram()) { 401 ProcessedSPNodes.insert(DS); 402 if (Scope->isAbstractScope()) { 403 ScopeDIE = TheCU->getDIE(DS); 404 // Note down abstract DIE. 405 if (ScopeDIE) 406 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE)); 407 } 408 else 409 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS); 410 } 411 else { 412 // There is no need to emit empty lexical block DIE. 413 if (Children.empty()) 414 return NULL; 415 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope); 416 } 417 418 if (!ScopeDIE) return NULL; 419 420 // Add children 421 for (SmallVector<DIE *, 8>::iterator I = Children.begin(), 422 E = Children.end(); I != E; ++I) 423 ScopeDIE->addChild(*I); 424 425 if (DS.isSubprogram()) 426 TheCU->addPubTypes(DISubprogram(DS)); 427 428 return ScopeDIE; 429} 430 431/// GetOrCreateSourceID - Look up the source id with the given directory and 432/// source file names. If none currently exists, create a new id and insert it 433/// in the SourceIds map. This can update DirectoryNames and SourceFileNames 434/// maps as well. 435unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName, 436 StringRef DirName) { 437 // If FE did not provide a file name, then assume stdin. 438 if (FileName.empty()) 439 return GetOrCreateSourceID("<stdin>", StringRef()); 440 441 // TODO: this might not belong here. See if we can factor this better. 442 if (DirName == CompilationDir) 443 DirName = ""; 444 445 unsigned SrcId = SourceIdMap.size()+1; 446 std::pair<std::string, std::string> SourceName = 447 std::make_pair(FileName, DirName); 448 std::pair<std::pair<std::string, std::string>, unsigned> Entry = 449 make_pair(SourceName, SrcId); 450 451 std::map<std::pair<std::string, std::string>, unsigned>::iterator I; 452 bool NewlyInserted; 453 tie(I, NewlyInserted) = SourceIdMap.insert(Entry); 454 if (!NewlyInserted) 455 return I->second; 456 457 // Print out a .file directive to specify files for .loc directives. 458 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.first.second, 459 Entry.first.first); 460 461 return SrcId; 462} 463 464/// constructCompileUnit - Create new CompileUnit for the given 465/// metadata node with tag DW_TAG_compile_unit. 466CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) { 467 DICompileUnit DIUnit(N); 468 StringRef FN = DIUnit.getFilename(); 469 CompilationDir = DIUnit.getDirectory(); 470 unsigned ID = GetOrCreateSourceID(FN, CompilationDir); 471 472 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit); 473 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this); 474 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer()); 475 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2, 476 DIUnit.getLanguage()); 477 NewCU->addString(Die, dwarf::DW_AT_name, FN); 478 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This 479 // simplifies debug range entries. 480 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0); 481 // DW_AT_stmt_list is a offset of line number information for this 482 // compile unit in debug_line section. 483 if (Asm->MAI->doesDwarfRequireRelocationForSectionOffset()) 484 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 485 Asm->GetTempSymbol("section_line")); 486 else 487 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0); 488 489 if (!CompilationDir.empty()) 490 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir); 491 if (DIUnit.isOptimized()) 492 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1); 493 494 StringRef Flags = DIUnit.getFlags(); 495 if (!Flags.empty()) 496 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags); 497 498 if (unsigned RVer = DIUnit.getRunTimeVersion()) 499 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers, 500 dwarf::DW_FORM_data1, RVer); 501 502 if (!FirstCU) 503 FirstCU = NewCU; 504 CUMap.insert(std::make_pair(N, NewCU)); 505 return NewCU; 506} 507 508/// construct SubprogramDIE - Construct subprogram DIE. 509void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU, 510 const MDNode *N) { 511 CompileUnit *&CURef = SPMap[N]; 512 if (CURef) 513 return; 514 CURef = TheCU; 515 516 DISubprogram SP(N); 517 if (!SP.isDefinition()) 518 // This is a method declaration which will be handled while constructing 519 // class type. 520 return; 521 522 DISubprogram SPDecl = SP.getFunctionDeclaration(); 523 DIE *DeclDie = NULL; 524 if (SPDecl.isSubprogram()) { 525 DeclDie = TheCU->getOrCreateSubprogramDIE(SPDecl); 526 } 527 528 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP); 529 530 if (DeclDie) { 531 // Refer function declaration directly. 532 TheCU->addDIEEntry(SubprogramDie, dwarf::DW_AT_specification, 533 dwarf::DW_FORM_ref4, DeclDie); 534 } 535 536 // Add to map. 537 TheCU->insertDIE(N, SubprogramDie); 538 539 // Add to context owner. 540 TheCU->addToContextOwner(SubprogramDie, SP.getContext()); 541 542 // Expose as global. 543 TheCU->addGlobal(SP.getName(), SubprogramDie); 544 545 return; 546} 547 548/// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such 549/// as llvm.dbg.enum and llvm.dbg.ty 550void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) { 551 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp")) 552 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 553 const MDNode *N = NMD->getOperand(i); 554 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit())) 555 constructSubprogramDIE(CU, N); 556 } 557 558 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv")) 559 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 560 const MDNode *N = NMD->getOperand(i); 561 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit())) 562 CU->createGlobalVariableDIE(N); 563 } 564 565 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum")) 566 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 567 DIType Ty(NMD->getOperand(i)); 568 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit())) 569 CU->getOrCreateTypeDIE(Ty); 570 } 571 572 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty")) 573 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 574 DIType Ty(NMD->getOperand(i)); 575 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit())) 576 CU->getOrCreateTypeDIE(Ty); 577 } 578} 579 580/// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder. 581/// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder. 582bool DwarfDebug::collectLegacyDebugInfo(Module *M) { 583 DebugInfoFinder DbgFinder; 584 DbgFinder.processModule(*M); 585 586 bool HasDebugInfo = false; 587 // Scan all the compile-units to see if there are any marked as the main 588 // unit. If not, we do not generate debug info. 589 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(), 590 E = DbgFinder.compile_unit_end(); I != E; ++I) { 591 if (DICompileUnit(*I).isMain()) { 592 HasDebugInfo = true; 593 break; 594 } 595 } 596 if (!HasDebugInfo) return false; 597 598 // Create all the compile unit DIEs. 599 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(), 600 E = DbgFinder.compile_unit_end(); I != E; ++I) 601 constructCompileUnit(*I); 602 603 // Create DIEs for each global variable. 604 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(), 605 E = DbgFinder.global_variable_end(); I != E; ++I) { 606 const MDNode *N = *I; 607 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit())) 608 CU->createGlobalVariableDIE(N); 609 } 610 611 // Create DIEs for each subprogram. 612 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(), 613 E = DbgFinder.subprogram_end(); I != E; ++I) { 614 const MDNode *N = *I; 615 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit())) 616 constructSubprogramDIE(CU, N); 617 } 618 619 return HasDebugInfo; 620} 621 622/// beginModule - Emit all Dwarf sections that should come prior to the 623/// content. Create global DIEs and emit initial debug info sections. 624/// This is invoked by the target AsmPrinter. 625void DwarfDebug::beginModule(Module *M) { 626 if (DisableDebugInfoPrinting) 627 return; 628 629 // If module has named metadata anchors then use them, otherwise scan the 630 // module using debug info finder to collect debug info. 631 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu"); 632 if (CU_Nodes) { 633 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) { 634 DICompileUnit CUNode(CU_Nodes->getOperand(i)); 635 CompileUnit *CU = constructCompileUnit(CUNode); 636 DIArray GVs = CUNode.getGlobalVariables(); 637 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) 638 CU->createGlobalVariableDIE(GVs.getElement(i)); 639 DIArray SPs = CUNode.getSubprograms(); 640 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) 641 constructSubprogramDIE(CU, SPs.getElement(i)); 642 DIArray EnumTypes = CUNode.getEnumTypes(); 643 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) 644 CU->getOrCreateTypeDIE(EnumTypes.getElement(i)); 645 DIArray RetainedTypes = CUNode.getRetainedTypes(); 646 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) 647 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i)); 648 } 649 } else if (!collectLegacyDebugInfo(M)) 650 return; 651 652 collectInfoFromNamedMDNodes(M); 653 654 // Tell MMI that we have debug info. 655 MMI->setDebugInfoAvailability(true); 656 657 // Emit initial sections. 658 EmitSectionLabels(); 659 660 // Prime section data. 661 SectionMap.insert(Asm->getObjFileLowering().getTextSection()); 662} 663 664/// endModule - Emit all Dwarf sections that should come after the content. 665/// 666void DwarfDebug::endModule() { 667 if (!FirstCU) return; 668 const Module *M = MMI->getModule(); 669 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap; 670 671 // Collect info for variables that were optimized out. 672 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) { 673 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) { 674 DICompileUnit TheCU(CU_Nodes->getOperand(i)); 675 DIArray Subprograms = TheCU.getSubprograms(); 676 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) { 677 DISubprogram SP(Subprograms.getElement(i)); 678 if (ProcessedSPNodes.count(SP) != 0) continue; 679 if (!SP.Verify()) continue; 680 if (!SP.isDefinition()) continue; 681 DIArray Variables = SP.getVariables(); 682 if (Variables.getNumElements() == 0) continue; 683 684 LexicalScope *Scope = 685 new LexicalScope(NULL, DIDescriptor(SP), NULL, false); 686 DeadFnScopeMap[SP] = Scope; 687 688 // Construct subprogram DIE and add variables DIEs. 689 CompileUnit *SPCU = CUMap.lookup(TheCU); 690 assert(SPCU && "Unable to find Compile Unit!"); 691 constructSubprogramDIE(SPCU, SP); 692 DIE *ScopeDIE = SPCU->getDIE(SP); 693 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) { 694 DIVariable DV(Variables.getElement(vi)); 695 if (!DV.Verify()) continue; 696 DbgVariable *NewVar = new DbgVariable(DV, NULL); 697 if (DIE *VariableDIE = 698 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope())) 699 ScopeDIE->addChild(VariableDIE); 700 } 701 } 702 } 703 } 704 705 // Attach DW_AT_inline attribute with inlined subprogram DIEs. 706 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(), 707 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) { 708 DIE *ISP = *AI; 709 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined); 710 } 711 712 // Emit DW_AT_containing_type attribute to connect types with their 713 // vtable holding type. 714 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(), 715 CUE = CUMap.end(); CUI != CUE; ++CUI) { 716 CompileUnit *TheCU = CUI->second; 717 TheCU->constructContainingTypeDIEs(); 718 } 719 720 // Standard sections final addresses. 721 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection()); 722 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end")); 723 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection()); 724 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end")); 725 726 // End text sections. 727 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) { 728 Asm->OutStreamer.SwitchSection(SectionMap[i]); 729 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i)); 730 } 731 732 // Compute DIE offsets and sizes. 733 computeSizeAndOffsets(); 734 735 // Emit all the DIEs into a debug info section 736 emitDebugInfo(); 737 738 // Corresponding abbreviations into a abbrev section. 739 emitAbbreviations(); 740 741 // Emit info into a debug pubnames section. 742 emitDebugPubNames(); 743 744 // Emit info into a debug pubtypes section. 745 emitDebugPubTypes(); 746 747 // Emit info into a debug loc section. 748 emitDebugLoc(); 749 750 // Emit info into a debug aranges section. 751 EmitDebugARanges(); 752 753 // Emit info into a debug ranges section. 754 emitDebugRanges(); 755 756 // Emit info into a debug macinfo section. 757 emitDebugMacInfo(); 758 759 // Emit inline info. 760 emitDebugInlineInfo(); 761 762 // Emit info into a debug str section. 763 emitDebugStr(); 764 765 // clean up. 766 DeleteContainerSeconds(DeadFnScopeMap); 767 SPMap.clear(); 768 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(), 769 E = CUMap.end(); I != E; ++I) 770 delete I->second; 771 FirstCU = NULL; // Reset for the next Module, if any. 772} 773 774/// findAbstractVariable - Find abstract variable, if any, associated with Var. 775DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV, 776 DebugLoc ScopeLoc) { 777 LLVMContext &Ctx = DV->getContext(); 778 // More then one inlined variable corresponds to one abstract variable. 779 DIVariable Var = cleanseInlinedVariable(DV, Ctx); 780 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var); 781 if (AbsDbgVariable) 782 return AbsDbgVariable; 783 784 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx)); 785 if (!Scope) 786 return NULL; 787 788 AbsDbgVariable = new DbgVariable(Var, NULL); 789 addScopeVariable(Scope, AbsDbgVariable); 790 AbstractVariables[Var] = AbsDbgVariable; 791 return AbsDbgVariable; 792} 793 794/// addCurrentFnArgument - If Var is a current function argument then add 795/// it to CurrentFnArguments list. 796bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF, 797 DbgVariable *Var, LexicalScope *Scope) { 798 if (!LScopes.isCurrentFunctionScope(Scope)) 799 return false; 800 DIVariable DV = Var->getVariable(); 801 if (DV.getTag() != dwarf::DW_TAG_arg_variable) 802 return false; 803 unsigned ArgNo = DV.getArgNumber(); 804 if (ArgNo == 0) 805 return false; 806 807 size_t Size = CurrentFnArguments.size(); 808 if (Size == 0) 809 CurrentFnArguments.resize(MF->getFunction()->arg_size()); 810 // llvm::Function argument size is not good indicator of how many 811 // arguments does the function have at source level. 812 if (ArgNo > Size) 813 CurrentFnArguments.resize(ArgNo * 2); 814 CurrentFnArguments[ArgNo - 1] = Var; 815 return true; 816} 817 818/// collectVariableInfoFromMMITable - Collect variable information from 819/// side table maintained by MMI. 820void 821DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF, 822 SmallPtrSet<const MDNode *, 16> &Processed) { 823 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo(); 824 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(), 825 VE = VMap.end(); VI != VE; ++VI) { 826 const MDNode *Var = VI->first; 827 if (!Var) continue; 828 Processed.insert(Var); 829 DIVariable DV(Var); 830 const std::pair<unsigned, DebugLoc> &VP = VI->second; 831 832 LexicalScope *Scope = LScopes.findLexicalScope(VP.second); 833 834 // If variable scope is not found then skip this variable. 835 if (Scope == 0) 836 continue; 837 838 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second); 839 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable); 840 RegVar->setFrameIndex(VP.first); 841 if (!addCurrentFnArgument(MF, RegVar, Scope)) 842 addScopeVariable(Scope, RegVar); 843 if (AbsDbgVariable) 844 AbsDbgVariable->setFrameIndex(VP.first); 845 } 846} 847 848/// isDbgValueInDefinedReg - Return true if debug value, encoded by 849/// DBG_VALUE instruction, is in a defined reg. 850static bool isDbgValueInDefinedReg(const MachineInstr *MI) { 851 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!"); 852 return MI->getNumOperands() == 3 && 853 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() && 854 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0; 855} 856 857/// getDebugLocEntry - Get .debug_loc entry for the instruction range starting 858/// at MI. 859static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm, 860 const MCSymbol *FLabel, 861 const MCSymbol *SLabel, 862 const MachineInstr *MI) { 863 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata(); 864 865 if (MI->getNumOperands() != 3) { 866 MachineLocation MLoc = Asm->getDebugValueLocation(MI); 867 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var); 868 } 869 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) { 870 MachineLocation MLoc; 871 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm()); 872 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var); 873 } 874 if (MI->getOperand(0).isImm()) 875 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm()); 876 if (MI->getOperand(0).isFPImm()) 877 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm()); 878 if (MI->getOperand(0).isCImm()) 879 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm()); 880 881 assert(0 && "Unexpected 3 operand DBG_VALUE instruction!"); 882 return DotDebugLocEntry(); 883} 884 885/// collectVariableInfo - Find variables for each lexical scope. 886void 887DwarfDebug::collectVariableInfo(const MachineFunction *MF, 888 SmallPtrSet<const MDNode *, 16> &Processed) { 889 890 /// collection info from MMI table. 891 collectVariableInfoFromMMITable(MF, Processed); 892 893 for (SmallVectorImpl<const MDNode*>::const_iterator 894 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE; 895 ++UVI) { 896 const MDNode *Var = *UVI; 897 if (Processed.count(Var)) 898 continue; 899 900 // History contains relevant DBG_VALUE instructions for Var and instructions 901 // clobbering it. 902 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var]; 903 if (History.empty()) 904 continue; 905 const MachineInstr *MInsn = History.front(); 906 907 DIVariable DV(Var); 908 LexicalScope *Scope = NULL; 909 if (DV.getTag() == dwarf::DW_TAG_arg_variable && 910 DISubprogram(DV.getContext()).describes(MF->getFunction())) 911 Scope = LScopes.getCurrentFunctionScope(); 912 else { 913 if (DV.getVersion() <= LLVMDebugVersion9) 914 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc()); 915 else { 916 if (MDNode *IA = DV.getInlinedAt()) 917 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA)); 918 else 919 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1))); 920 } 921 } 922 // If variable scope is not found then skip this variable. 923 if (!Scope) 924 continue; 925 926 Processed.insert(DV); 927 assert(MInsn->isDebugValue() && "History must begin with debug value"); 928 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc()); 929 DbgVariable *RegVar = new DbgVariable(DV, AbsVar); 930 if (!addCurrentFnArgument(MF, RegVar, Scope)) 931 addScopeVariable(Scope, RegVar); 932 if (AbsVar) 933 AbsVar->setMInsn(MInsn); 934 935 // Simple ranges that are fully coalesced. 936 if (History.size() <= 1 || (History.size() == 2 && 937 MInsn->isIdenticalTo(History.back()))) { 938 RegVar->setMInsn(MInsn); 939 continue; 940 } 941 942 // handle multiple DBG_VALUE instructions describing one variable. 943 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size()); 944 945 for (SmallVectorImpl<const MachineInstr*>::const_iterator 946 HI = History.begin(), HE = History.end(); HI != HE; ++HI) { 947 const MachineInstr *Begin = *HI; 948 assert(Begin->isDebugValue() && "Invalid History entry"); 949 950 // Check if DBG_VALUE is truncating a range. 951 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() 952 && !Begin->getOperand(0).getReg()) 953 continue; 954 955 // Compute the range for a register location. 956 const MCSymbol *FLabel = getLabelBeforeInsn(Begin); 957 const MCSymbol *SLabel = 0; 958 959 if (HI + 1 == HE) 960 // If Begin is the last instruction in History then its value is valid 961 // until the end of the function. 962 SLabel = FunctionEndSym; 963 else { 964 const MachineInstr *End = HI[1]; 965 DEBUG(dbgs() << "DotDebugLoc Pair:\n" 966 << "\t" << *Begin << "\t" << *End << "\n"); 967 if (End->isDebugValue()) 968 SLabel = getLabelBeforeInsn(End); 969 else { 970 // End is a normal instruction clobbering the range. 971 SLabel = getLabelAfterInsn(End); 972 assert(SLabel && "Forgot label after clobber instruction"); 973 ++HI; 974 } 975 } 976 977 // The value is valid until the next DBG_VALUE or clobber. 978 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin)); 979 } 980 DotDebugLocEntries.push_back(DotDebugLocEntry()); 981 } 982 983 // Collect info for variables that were optimized out. 984 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 985 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables(); 986 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) { 987 DIVariable DV(Variables.getElement(i)); 988 if (!DV || !DV.Verify() || !Processed.insert(DV)) 989 continue; 990 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) 991 addScopeVariable(Scope, new DbgVariable(DV, NULL)); 992 } 993} 994 995/// getLabelBeforeInsn - Return Label preceding the instruction. 996const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) { 997 MCSymbol *Label = LabelsBeforeInsn.lookup(MI); 998 assert(Label && "Didn't insert label before instruction"); 999 return Label; 1000} 1001 1002/// getLabelAfterInsn - Return Label immediately following the instruction. 1003const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) { 1004 return LabelsAfterInsn.lookup(MI); 1005} 1006 1007/// beginInstruction - Process beginning of an instruction. 1008void DwarfDebug::beginInstruction(const MachineInstr *MI) { 1009 // Check if source location changes, but ignore DBG_VALUE locations. 1010 if (!MI->isDebugValue()) { 1011 DebugLoc DL = MI->getDebugLoc(); 1012 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) { 1013 unsigned Flags = DWARF2_FLAG_IS_STMT; 1014 PrevInstLoc = DL; 1015 if (DL == PrologEndLoc) { 1016 Flags |= DWARF2_FLAG_PROLOGUE_END; 1017 PrologEndLoc = DebugLoc(); 1018 } 1019 if (!DL.isUnknown()) { 1020 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext()); 1021 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags); 1022 } else 1023 recordSourceLine(0, 0, 0, 0); 1024 } 1025 } 1026 1027 // Insert labels where requested. 1028 DenseMap<const MachineInstr*, MCSymbol*>::iterator I = 1029 LabelsBeforeInsn.find(MI); 1030 1031 // No label needed. 1032 if (I == LabelsBeforeInsn.end()) 1033 return; 1034 1035 // Label already assigned. 1036 if (I->second) 1037 return; 1038 1039 if (!PrevLabel) { 1040 PrevLabel = MMI->getContext().CreateTempSymbol(); 1041 Asm->OutStreamer.EmitLabel(PrevLabel); 1042 } 1043 I->second = PrevLabel; 1044} 1045 1046/// endInstruction - Process end of an instruction. 1047void DwarfDebug::endInstruction(const MachineInstr *MI) { 1048 // Don't create a new label after DBG_VALUE instructions. 1049 // They don't generate code. 1050 if (!MI->isDebugValue()) 1051 PrevLabel = 0; 1052 1053 DenseMap<const MachineInstr*, MCSymbol*>::iterator I = 1054 LabelsAfterInsn.find(MI); 1055 1056 // No label needed. 1057 if (I == LabelsAfterInsn.end()) 1058 return; 1059 1060 // Label already assigned. 1061 if (I->second) 1062 return; 1063 1064 // We need a label after this instruction. 1065 if (!PrevLabel) { 1066 PrevLabel = MMI->getContext().CreateTempSymbol(); 1067 Asm->OutStreamer.EmitLabel(PrevLabel); 1068 } 1069 I->second = PrevLabel; 1070} 1071 1072/// identifyScopeMarkers() - 1073/// Each LexicalScope has first instruction and last instruction to mark 1074/// beginning and end of a scope respectively. Create an inverse map that list 1075/// scopes starts (and ends) with an instruction. One instruction may start (or 1076/// end) multiple scopes. Ignore scopes that are not reachable. 1077void DwarfDebug::identifyScopeMarkers() { 1078 SmallVector<LexicalScope *, 4> WorkList; 1079 WorkList.push_back(LScopes.getCurrentFunctionScope()); 1080 while (!WorkList.empty()) { 1081 LexicalScope *S = WorkList.pop_back_val(); 1082 1083 const SmallVector<LexicalScope *, 4> &Children = S->getChildren(); 1084 if (!Children.empty()) 1085 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(), 1086 SE = Children.end(); SI != SE; ++SI) 1087 WorkList.push_back(*SI); 1088 1089 if (S->isAbstractScope()) 1090 continue; 1091 1092 const SmallVector<InsnRange, 4> &Ranges = S->getRanges(); 1093 if (Ranges.empty()) 1094 continue; 1095 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(), 1096 RE = Ranges.end(); RI != RE; ++RI) { 1097 assert(RI->first && "InsnRange does not have first instruction!"); 1098 assert(RI->second && "InsnRange does not have second instruction!"); 1099 requestLabelBeforeInsn(RI->first); 1100 requestLabelAfterInsn(RI->second); 1101 } 1102 } 1103} 1104 1105/// getScopeNode - Get MDNode for DebugLoc's scope. 1106static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) { 1107 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx)) 1108 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx); 1109 return DL.getScope(Ctx); 1110} 1111 1112/// getFnDebugLoc - Walk up the scope chain of given debug loc and find 1113/// line number info for the function. 1114static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) { 1115 const MDNode *Scope = getScopeNode(DL, Ctx); 1116 DISubprogram SP = getDISubprogram(Scope); 1117 if (SP.Verify()) 1118 return DebugLoc::get(SP.getLineNumber(), 0, SP); 1119 return DebugLoc(); 1120} 1121 1122/// beginFunction - Gather pre-function debug information. Assumes being 1123/// emitted immediately after the function entry point. 1124void DwarfDebug::beginFunction(const MachineFunction *MF) { 1125 if (!MMI->hasDebugInfo()) return; 1126 LScopes.initialize(*MF); 1127 if (LScopes.empty()) return; 1128 identifyScopeMarkers(); 1129 1130 FunctionBeginSym = Asm->GetTempSymbol("func_begin", 1131 Asm->getFunctionNumber()); 1132 // Assumes in correct section after the entry point. 1133 Asm->OutStreamer.EmitLabel(FunctionBeginSym); 1134 1135 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned"); 1136 1137 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo(); 1138 /// LiveUserVar - Map physreg numbers to the MDNode they contain. 1139 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs()); 1140 1141 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); 1142 I != E; ++I) { 1143 bool AtBlockEntry = true; 1144 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 1145 II != IE; ++II) { 1146 const MachineInstr *MI = II; 1147 1148 if (MI->isDebugValue()) { 1149 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!"); 1150 1151 // Keep track of user variables. 1152 const MDNode *Var = 1153 MI->getOperand(MI->getNumOperands() - 1).getMetadata(); 1154 1155 // Variable is in a register, we need to check for clobbers. 1156 if (isDbgValueInDefinedReg(MI)) 1157 LiveUserVar[MI->getOperand(0).getReg()] = Var; 1158 1159 // Check the history of this variable. 1160 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var]; 1161 if (History.empty()) { 1162 UserVariables.push_back(Var); 1163 // The first mention of a function argument gets the FunctionBeginSym 1164 // label, so arguments are visible when breaking at function entry. 1165 DIVariable DV(Var); 1166 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable && 1167 DISubprogram(getDISubprogram(DV.getContext())) 1168 .describes(MF->getFunction())) 1169 LabelsBeforeInsn[MI] = FunctionBeginSym; 1170 } else { 1171 // We have seen this variable before. Try to coalesce DBG_VALUEs. 1172 const MachineInstr *Prev = History.back(); 1173 if (Prev->isDebugValue()) { 1174 // Coalesce identical entries at the end of History. 1175 if (History.size() >= 2 && 1176 Prev->isIdenticalTo(History[History.size() - 2])) { 1177 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n" 1178 << "\t" << *Prev 1179 << "\t" << *History[History.size() - 2] << "\n"); 1180 History.pop_back(); 1181 } 1182 1183 // Terminate old register assignments that don't reach MI; 1184 MachineFunction::const_iterator PrevMBB = Prev->getParent(); 1185 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) && 1186 isDbgValueInDefinedReg(Prev)) { 1187 // Previous register assignment needs to terminate at the end of 1188 // its basic block. 1189 MachineBasicBlock::const_iterator LastMI = 1190 PrevMBB->getLastNonDebugInstr(); 1191 if (LastMI == PrevMBB->end()) { 1192 // Drop DBG_VALUE for empty range. 1193 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n" 1194 << "\t" << *Prev << "\n"); 1195 History.pop_back(); 1196 } 1197 else { 1198 // Terminate after LastMI. 1199 History.push_back(LastMI); 1200 } 1201 } 1202 } 1203 } 1204 History.push_back(MI); 1205 } else { 1206 // Not a DBG_VALUE instruction. 1207 if (!MI->isLabel()) 1208 AtBlockEntry = false; 1209 1210 // First known non DBG_VALUE location marks beginning of function 1211 // body. 1212 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()) 1213 PrologEndLoc = MI->getDebugLoc(); 1214 1215 // Check if the instruction clobbers any registers with debug vars. 1216 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(), 1217 MOE = MI->operands_end(); MOI != MOE; ++MOI) { 1218 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg()) 1219 continue; 1220 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg()); 1221 unsigned Reg = *AI; ++AI) { 1222 const MDNode *Var = LiveUserVar[Reg]; 1223 if (!Var) 1224 continue; 1225 // Reg is now clobbered. 1226 LiveUserVar[Reg] = 0; 1227 1228 // Was MD last defined by a DBG_VALUE referring to Reg? 1229 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var); 1230 if (HistI == DbgValues.end()) 1231 continue; 1232 SmallVectorImpl<const MachineInstr*> &History = HistI->second; 1233 if (History.empty()) 1234 continue; 1235 const MachineInstr *Prev = History.back(); 1236 // Sanity-check: Register assignments are terminated at the end of 1237 // their block. 1238 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent()) 1239 continue; 1240 // Is the variable still in Reg? 1241 if (!isDbgValueInDefinedReg(Prev) || 1242 Prev->getOperand(0).getReg() != Reg) 1243 continue; 1244 // Var is clobbered. Make sure the next instruction gets a label. 1245 History.push_back(MI); 1246 } 1247 } 1248 } 1249 } 1250 } 1251 1252 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end(); 1253 I != E; ++I) { 1254 SmallVectorImpl<const MachineInstr*> &History = I->second; 1255 if (History.empty()) 1256 continue; 1257 1258 // Make sure the final register assignments are terminated. 1259 const MachineInstr *Prev = History.back(); 1260 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) { 1261 const MachineBasicBlock *PrevMBB = Prev->getParent(); 1262 MachineBasicBlock::const_iterator LastMI = 1263 PrevMBB->getLastNonDebugInstr(); 1264 if (LastMI == PrevMBB->end()) 1265 // Drop DBG_VALUE for empty range. 1266 History.pop_back(); 1267 else { 1268 // Terminate after LastMI. 1269 History.push_back(LastMI); 1270 } 1271 } 1272 // Request labels for the full history. 1273 for (unsigned i = 0, e = History.size(); i != e; ++i) { 1274 const MachineInstr *MI = History[i]; 1275 if (MI->isDebugValue()) 1276 requestLabelBeforeInsn(MI); 1277 else 1278 requestLabelAfterInsn(MI); 1279 } 1280 } 1281 1282 PrevInstLoc = DebugLoc(); 1283 PrevLabel = FunctionBeginSym; 1284 1285 // Record beginning of function. 1286 if (!PrologEndLoc.isUnknown()) { 1287 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc, 1288 MF->getFunction()->getContext()); 1289 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(), 1290 FnStartDL.getScope(MF->getFunction()->getContext()), 1291 DWARF2_FLAG_IS_STMT); 1292 } 1293} 1294 1295void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) { 1296// SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS); 1297 ScopeVariables[LS].push_back(Var); 1298// Vars.push_back(Var); 1299} 1300 1301/// endFunction - Gather and emit post-function debug information. 1302/// 1303void DwarfDebug::endFunction(const MachineFunction *MF) { 1304 if (!MMI->hasDebugInfo() || LScopes.empty()) return; 1305 1306 // Define end label for subprogram. 1307 FunctionEndSym = Asm->GetTempSymbol("func_end", 1308 Asm->getFunctionNumber()); 1309 // Assumes in correct section after the entry point. 1310 Asm->OutStreamer.EmitLabel(FunctionEndSym); 1311 1312 SmallPtrSet<const MDNode *, 16> ProcessedVars; 1313 collectVariableInfo(MF, ProcessedVars); 1314 1315 LexicalScope *FnScope = LScopes.getCurrentFunctionScope(); 1316 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode()); 1317 assert(TheCU && "Unable to find compile unit!"); 1318 1319 // Construct abstract scopes. 1320 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList(); 1321 for (unsigned i = 0, e = AList.size(); i != e; ++i) { 1322 LexicalScope *AScope = AList[i]; 1323 DISubprogram SP(AScope->getScopeNode()); 1324 if (SP.Verify()) { 1325 // Collect info for variables that were optimized out. 1326 DIArray Variables = SP.getVariables(); 1327 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) { 1328 DIVariable DV(Variables.getElement(i)); 1329 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV)) 1330 continue; 1331 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext())) 1332 addScopeVariable(Scope, new DbgVariable(DV, NULL)); 1333 } 1334 } 1335 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0) 1336 constructScopeDIE(TheCU, AScope); 1337 } 1338 1339 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope); 1340 1341 if (!DisableFramePointerElim(*MF)) 1342 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr, 1343 dwarf::DW_FORM_flag, 1); 1344 1345 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(), 1346 MMI->getFrameMoves())); 1347 1348 // Clear debug info 1349 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator 1350 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I) 1351 DeleteContainerPointers(I->second); 1352 ScopeVariables.clear(); 1353 DeleteContainerPointers(CurrentFnArguments); 1354 UserVariables.clear(); 1355 DbgValues.clear(); 1356 AbstractVariables.clear(); 1357 LabelsBeforeInsn.clear(); 1358 LabelsAfterInsn.clear(); 1359 PrevLabel = NULL; 1360} 1361 1362/// recordSourceLine - Register a source line with debug info. Returns the 1363/// unique label that was emitted and which provides correspondence to 1364/// the source line list. 1365void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S, 1366 unsigned Flags) { 1367 StringRef Fn; 1368 StringRef Dir; 1369 unsigned Src = 1; 1370 if (S) { 1371 DIDescriptor Scope(S); 1372 1373 if (Scope.isCompileUnit()) { 1374 DICompileUnit CU(S); 1375 Fn = CU.getFilename(); 1376 Dir = CU.getDirectory(); 1377 } else if (Scope.isFile()) { 1378 DIFile F(S); 1379 Fn = F.getFilename(); 1380 Dir = F.getDirectory(); 1381 } else if (Scope.isSubprogram()) { 1382 DISubprogram SP(S); 1383 Fn = SP.getFilename(); 1384 Dir = SP.getDirectory(); 1385 } else if (Scope.isLexicalBlockFile()) { 1386 DILexicalBlockFile DBF(S); 1387 Fn = DBF.getFilename(); 1388 Dir = DBF.getDirectory(); 1389 } else if (Scope.isLexicalBlock()) { 1390 DILexicalBlock DB(S); 1391 Fn = DB.getFilename(); 1392 Dir = DB.getDirectory(); 1393 } else 1394 assert(0 && "Unexpected scope info"); 1395 1396 Src = GetOrCreateSourceID(Fn, Dir); 1397 } 1398 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn); 1399} 1400 1401//===----------------------------------------------------------------------===// 1402// Emit Methods 1403//===----------------------------------------------------------------------===// 1404 1405/// computeSizeAndOffset - Compute the size and offset of a DIE. 1406/// 1407unsigned 1408DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) { 1409 // Get the children. 1410 const std::vector<DIE *> &Children = Die->getChildren(); 1411 1412 // If not last sibling and has children then add sibling offset attribute. 1413 if (!Last && !Children.empty()) 1414 Die->addSiblingOffset(DIEValueAllocator); 1415 1416 // Record the abbreviation. 1417 assignAbbrevNumber(Die->getAbbrev()); 1418 1419 // Get the abbreviation for this DIE. 1420 unsigned AbbrevNumber = Die->getAbbrevNumber(); 1421 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1]; 1422 1423 // Set DIE offset 1424 Die->setOffset(Offset); 1425 1426 // Start the size with the size of abbreviation code. 1427 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber); 1428 1429 const SmallVector<DIEValue*, 32> &Values = Die->getValues(); 1430 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData(); 1431 1432 // Size the DIE attribute values. 1433 for (unsigned i = 0, N = Values.size(); i < N; ++i) 1434 // Size attribute value. 1435 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm()); 1436 1437 // Size the DIE children if any. 1438 if (!Children.empty()) { 1439 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes && 1440 "Children flag not set"); 1441 1442 for (unsigned j = 0, M = Children.size(); j < M; ++j) 1443 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M); 1444 1445 // End of children marker. 1446 Offset += sizeof(int8_t); 1447 } 1448 1449 Die->setSize(Offset - Die->getOffset()); 1450 return Offset; 1451} 1452 1453/// computeSizeAndOffsets - Compute the size and offset of all the DIEs. 1454/// 1455void DwarfDebug::computeSizeAndOffsets() { 1456 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(), 1457 E = CUMap.end(); I != E; ++I) { 1458 // Compute size of compile unit header. 1459 unsigned Offset = 1460 sizeof(int32_t) + // Length of Compilation Unit Info 1461 sizeof(int16_t) + // DWARF version number 1462 sizeof(int32_t) + // Offset Into Abbrev. Section 1463 sizeof(int8_t); // Pointer Size (in bytes) 1464 computeSizeAndOffset(I->second->getCUDie(), Offset, true); 1465 } 1466} 1467 1468/// EmitSectionSym - Switch to the specified MCSection and emit an assembler 1469/// temporary label to it if SymbolStem is specified. 1470static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section, 1471 const char *SymbolStem = 0) { 1472 Asm->OutStreamer.SwitchSection(Section); 1473 if (!SymbolStem) return 0; 1474 1475 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem); 1476 Asm->OutStreamer.EmitLabel(TmpSym); 1477 return TmpSym; 1478} 1479 1480/// EmitSectionLabels - Emit initial Dwarf sections with a label at 1481/// the start of each one. 1482void DwarfDebug::EmitSectionLabels() { 1483 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); 1484 1485 // Dwarf sections base addresses. 1486 DwarfInfoSectionSym = 1487 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info"); 1488 DwarfAbbrevSectionSym = 1489 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev"); 1490 EmitSectionSym(Asm, TLOF.getDwarfARangesSection()); 1491 1492 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection()) 1493 EmitSectionSym(Asm, MacroInfo); 1494 1495 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line"); 1496 EmitSectionSym(Asm, TLOF.getDwarfLocSection()); 1497 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection()); 1498 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection()); 1499 DwarfStrSectionSym = 1500 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str"); 1501 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(), 1502 "debug_range"); 1503 1504 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(), 1505 "section_debug_loc"); 1506 1507 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin"); 1508 EmitSectionSym(Asm, TLOF.getDataSection()); 1509} 1510 1511/// emitDIE - Recursively emits a debug information entry. 1512/// 1513void DwarfDebug::emitDIE(DIE *Die) { 1514 // Get the abbreviation for this DIE. 1515 unsigned AbbrevNumber = Die->getAbbrevNumber(); 1516 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1]; 1517 1518 // Emit the code (index) for the abbreviation. 1519 if (Asm->isVerbose()) 1520 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" + 1521 Twine::utohexstr(Die->getOffset()) + ":0x" + 1522 Twine::utohexstr(Die->getSize()) + " " + 1523 dwarf::TagString(Abbrev->getTag())); 1524 Asm->EmitULEB128(AbbrevNumber); 1525 1526 const SmallVector<DIEValue*, 32> &Values = Die->getValues(); 1527 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData(); 1528 1529 // Emit the DIE attribute values. 1530 for (unsigned i = 0, N = Values.size(); i < N; ++i) { 1531 unsigned Attr = AbbrevData[i].getAttribute(); 1532 unsigned Form = AbbrevData[i].getForm(); 1533 assert(Form && "Too many attributes for DIE (check abbreviation)"); 1534 1535 if (Asm->isVerbose()) 1536 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr)); 1537 1538 switch (Attr) { 1539 case dwarf::DW_AT_sibling: 1540 Asm->EmitInt32(Die->getSiblingOffset()); 1541 break; 1542 case dwarf::DW_AT_abstract_origin: { 1543 DIEEntry *E = cast<DIEEntry>(Values[i]); 1544 DIE *Origin = E->getEntry(); 1545 unsigned Addr = Origin->getOffset(); 1546 Asm->EmitInt32(Addr); 1547 break; 1548 } 1549 case dwarf::DW_AT_ranges: { 1550 // DW_AT_range Value encodes offset in debug_range section. 1551 DIEInteger *V = cast<DIEInteger>(Values[i]); 1552 1553 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) { 1554 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym, 1555 V->getValue(), 1556 4); 1557 } else { 1558 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym, 1559 V->getValue(), 1560 DwarfDebugRangeSectionSym, 1561 4); 1562 } 1563 break; 1564 } 1565 case dwarf::DW_AT_location: { 1566 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) 1567 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4); 1568 else 1569 Values[i]->EmitValue(Asm, Form); 1570 break; 1571 } 1572 case dwarf::DW_AT_accessibility: { 1573 if (Asm->isVerbose()) { 1574 DIEInteger *V = cast<DIEInteger>(Values[i]); 1575 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue())); 1576 } 1577 Values[i]->EmitValue(Asm, Form); 1578 break; 1579 } 1580 default: 1581 // Emit an attribute using the defined form. 1582 Values[i]->EmitValue(Asm, Form); 1583 break; 1584 } 1585 } 1586 1587 // Emit the DIE children if any. 1588 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) { 1589 const std::vector<DIE *> &Children = Die->getChildren(); 1590 1591 for (unsigned j = 0, M = Children.size(); j < M; ++j) 1592 emitDIE(Children[j]); 1593 1594 if (Asm->isVerbose()) 1595 Asm->OutStreamer.AddComment("End Of Children Mark"); 1596 Asm->EmitInt8(0); 1597 } 1598} 1599 1600/// emitDebugInfo - Emit the debug info section. 1601/// 1602void DwarfDebug::emitDebugInfo() { 1603 // Start debug info section. 1604 Asm->OutStreamer.SwitchSection( 1605 Asm->getObjFileLowering().getDwarfInfoSection()); 1606 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(), 1607 E = CUMap.end(); I != E; ++I) { 1608 CompileUnit *TheCU = I->second; 1609 DIE *Die = TheCU->getCUDie(); 1610 1611 // Emit the compile units header. 1612 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin", 1613 TheCU->getID())); 1614 1615 // Emit size of content not including length itself 1616 unsigned ContentSize = Die->getSize() + 1617 sizeof(int16_t) + // DWARF version number 1618 sizeof(int32_t) + // Offset Into Abbrev. Section 1619 sizeof(int8_t); // Pointer Size (in bytes) 1620 1621 Asm->OutStreamer.AddComment("Length of Compilation Unit Info"); 1622 Asm->EmitInt32(ContentSize); 1623 Asm->OutStreamer.AddComment("DWARF version number"); 1624 Asm->EmitInt16(dwarf::DWARF_VERSION); 1625 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section"); 1626 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"), 1627 DwarfAbbrevSectionSym); 1628 Asm->OutStreamer.AddComment("Address Size (in bytes)"); 1629 Asm->EmitInt8(Asm->getTargetData().getPointerSize()); 1630 1631 emitDIE(Die); 1632 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID())); 1633 } 1634} 1635 1636/// emitAbbreviations - Emit the abbreviation section. 1637/// 1638void DwarfDebug::emitAbbreviations() const { 1639 // Check to see if it is worth the effort. 1640 if (!Abbreviations.empty()) { 1641 // Start the debug abbrev section. 1642 Asm->OutStreamer.SwitchSection( 1643 Asm->getObjFileLowering().getDwarfAbbrevSection()); 1644 1645 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin")); 1646 1647 // For each abbrevation. 1648 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) { 1649 // Get abbreviation data 1650 const DIEAbbrev *Abbrev = Abbreviations[i]; 1651 1652 // Emit the abbrevations code (base 1 index.) 1653 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code"); 1654 1655 // Emit the abbreviations data. 1656 Abbrev->Emit(Asm); 1657 } 1658 1659 // Mark end of abbreviations. 1660 Asm->EmitULEB128(0, "EOM(3)"); 1661 1662 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end")); 1663 } 1664} 1665 1666/// emitEndOfLineMatrix - Emit the last address of the section and the end of 1667/// the line matrix. 1668/// 1669void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) { 1670 // Define last address of section. 1671 Asm->OutStreamer.AddComment("Extended Op"); 1672 Asm->EmitInt8(0); 1673 1674 Asm->OutStreamer.AddComment("Op size"); 1675 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1); 1676 Asm->OutStreamer.AddComment("DW_LNE_set_address"); 1677 Asm->EmitInt8(dwarf::DW_LNE_set_address); 1678 1679 Asm->OutStreamer.AddComment("Section end label"); 1680 1681 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd), 1682 Asm->getTargetData().getPointerSize(), 1683 0/*AddrSpace*/); 1684 1685 // Mark end of matrix. 1686 Asm->OutStreamer.AddComment("DW_LNE_end_sequence"); 1687 Asm->EmitInt8(0); 1688 Asm->EmitInt8(1); 1689 Asm->EmitInt8(1); 1690} 1691 1692/// emitDebugPubNames - Emit visible names into a debug pubnames section. 1693/// 1694void DwarfDebug::emitDebugPubNames() { 1695 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(), 1696 E = CUMap.end(); I != E; ++I) { 1697 CompileUnit *TheCU = I->second; 1698 // Start the dwarf pubnames section. 1699 Asm->OutStreamer.SwitchSection( 1700 Asm->getObjFileLowering().getDwarfPubNamesSection()); 1701 1702 Asm->OutStreamer.AddComment("Length of Public Names Info"); 1703 Asm->EmitLabelDifference( 1704 Asm->GetTempSymbol("pubnames_end", TheCU->getID()), 1705 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4); 1706 1707 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", 1708 TheCU->getID())); 1709 1710 Asm->OutStreamer.AddComment("DWARF Version"); 1711 Asm->EmitInt16(dwarf::DWARF_VERSION); 1712 1713 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info"); 1714 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()), 1715 DwarfInfoSectionSym); 1716 1717 Asm->OutStreamer.AddComment("Compilation Unit Length"); 1718 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()), 1719 Asm->GetTempSymbol("info_begin", TheCU->getID()), 1720 4); 1721 1722 const StringMap<DIE*> &Globals = TheCU->getGlobals(); 1723 for (StringMap<DIE*>::const_iterator 1724 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) { 1725 const char *Name = GI->getKeyData(); 1726 DIE *Entity = GI->second; 1727 1728 Asm->OutStreamer.AddComment("DIE offset"); 1729 Asm->EmitInt32(Entity->getOffset()); 1730 1731 if (Asm->isVerbose()) 1732 Asm->OutStreamer.AddComment("External Name"); 1733 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0); 1734 } 1735 1736 Asm->OutStreamer.AddComment("End Mark"); 1737 Asm->EmitInt32(0); 1738 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", 1739 TheCU->getID())); 1740 } 1741} 1742 1743void DwarfDebug::emitDebugPubTypes() { 1744 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(), 1745 E = CUMap.end(); I != E; ++I) { 1746 CompileUnit *TheCU = I->second; 1747 // Start the dwarf pubtypes section. 1748 Asm->OutStreamer.SwitchSection( 1749 Asm->getObjFileLowering().getDwarfPubTypesSection()); 1750 Asm->OutStreamer.AddComment("Length of Public Types Info"); 1751 Asm->EmitLabelDifference( 1752 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()), 1753 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4); 1754 1755 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin", 1756 TheCU->getID())); 1757 1758 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version"); 1759 Asm->EmitInt16(dwarf::DWARF_VERSION); 1760 1761 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info"); 1762 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()), 1763 DwarfInfoSectionSym); 1764 1765 Asm->OutStreamer.AddComment("Compilation Unit Length"); 1766 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()), 1767 Asm->GetTempSymbol("info_begin", TheCU->getID()), 1768 4); 1769 1770 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes(); 1771 for (StringMap<DIE*>::const_iterator 1772 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) { 1773 const char *Name = GI->getKeyData(); 1774 DIE *Entity = GI->second; 1775 1776 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset"); 1777 Asm->EmitInt32(Entity->getOffset()); 1778 1779 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name"); 1780 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0); 1781 } 1782 1783 Asm->OutStreamer.AddComment("End Mark"); 1784 Asm->EmitInt32(0); 1785 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end", 1786 TheCU->getID())); 1787 } 1788} 1789 1790/// emitDebugStr - Emit visible names into a debug str section. 1791/// 1792void DwarfDebug::emitDebugStr() { 1793 // Check to see if it is worth the effort. 1794 if (StringPool.empty()) return; 1795 1796 // Start the dwarf str section. 1797 Asm->OutStreamer.SwitchSection( 1798 Asm->getObjFileLowering().getDwarfStrSection()); 1799 1800 // Get all of the string pool entries and put them in an array by their ID so 1801 // we can sort them. 1802 SmallVector<std::pair<unsigned, 1803 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries; 1804 1805 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator 1806 I = StringPool.begin(), E = StringPool.end(); I != E; ++I) 1807 Entries.push_back(std::make_pair(I->second.second, &*I)); 1808 1809 array_pod_sort(Entries.begin(), Entries.end()); 1810 1811 for (unsigned i = 0, e = Entries.size(); i != e; ++i) { 1812 // Emit a label for reference from debug information entries. 1813 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first); 1814 1815 // Emit the string itself. 1816 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/); 1817 Asm->OutStreamer.EmitZeros(1, 0); 1818 } 1819} 1820 1821/// emitDebugLoc - Emit visible names into a debug loc section. 1822/// 1823void DwarfDebug::emitDebugLoc() { 1824 if (DotDebugLocEntries.empty()) 1825 return; 1826 1827 for (SmallVector<DotDebugLocEntry, 4>::iterator 1828 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end(); 1829 I != E; ++I) { 1830 DotDebugLocEntry &Entry = *I; 1831 if (I + 1 != DotDebugLocEntries.end()) 1832 Entry.Merge(I+1); 1833 } 1834 1835 // Start the dwarf loc section. 1836 Asm->OutStreamer.SwitchSection( 1837 Asm->getObjFileLowering().getDwarfLocSection()); 1838 unsigned char Size = Asm->getTargetData().getPointerSize(); 1839 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0)); 1840 unsigned index = 1; 1841 for (SmallVector<DotDebugLocEntry, 4>::iterator 1842 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end(); 1843 I != E; ++I, ++index) { 1844 DotDebugLocEntry &Entry = *I; 1845 if (Entry.isMerged()) continue; 1846 if (Entry.isEmpty()) { 1847 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0); 1848 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0); 1849 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index)); 1850 } else { 1851 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0); 1852 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0); 1853 DIVariable DV(Entry.Variable); 1854 Asm->OutStreamer.AddComment("Loc expr size"); 1855 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol(); 1856 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol(); 1857 Asm->EmitLabelDifference(end, begin, 2); 1858 Asm->OutStreamer.EmitLabel(begin); 1859 if (Entry.isInt()) { 1860 DIBasicType BTy(DV.getType()); 1861 if (BTy.Verify() && 1862 (BTy.getEncoding() == dwarf::DW_ATE_signed 1863 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) { 1864 Asm->OutStreamer.AddComment("DW_OP_consts"); 1865 Asm->EmitInt8(dwarf::DW_OP_consts); 1866 Asm->EmitSLEB128(Entry.getInt()); 1867 } else { 1868 Asm->OutStreamer.AddComment("DW_OP_constu"); 1869 Asm->EmitInt8(dwarf::DW_OP_constu); 1870 Asm->EmitULEB128(Entry.getInt()); 1871 } 1872 } else if (Entry.isLocation()) { 1873 if (!DV.hasComplexAddress()) 1874 // Regular entry. 1875 Asm->EmitDwarfRegOp(Entry.Loc); 1876 else { 1877 // Complex address entry. 1878 unsigned N = DV.getNumAddrElements(); 1879 unsigned i = 0; 1880 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) { 1881 if (Entry.Loc.getOffset()) { 1882 i = 2; 1883 Asm->EmitDwarfRegOp(Entry.Loc); 1884 Asm->OutStreamer.AddComment("DW_OP_deref"); 1885 Asm->EmitInt8(dwarf::DW_OP_deref); 1886 Asm->OutStreamer.AddComment("DW_OP_plus_uconst"); 1887 Asm->EmitInt8(dwarf::DW_OP_plus_uconst); 1888 Asm->EmitSLEB128(DV.getAddrElement(1)); 1889 } else { 1890 // If first address element is OpPlus then emit 1891 // DW_OP_breg + Offset instead of DW_OP_reg + Offset. 1892 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1)); 1893 Asm->EmitDwarfRegOp(Loc); 1894 i = 2; 1895 } 1896 } else { 1897 Asm->EmitDwarfRegOp(Entry.Loc); 1898 } 1899 1900 // Emit remaining complex address elements. 1901 for (; i < N; ++i) { 1902 uint64_t Element = DV.getAddrElement(i); 1903 if (Element == DIBuilder::OpPlus) { 1904 Asm->EmitInt8(dwarf::DW_OP_plus_uconst); 1905 Asm->EmitULEB128(DV.getAddrElement(++i)); 1906 } else if (Element == DIBuilder::OpDeref) 1907 Asm->EmitInt8(dwarf::DW_OP_deref); 1908 else llvm_unreachable("unknown Opcode found in complex address"); 1909 } 1910 } 1911 } 1912 // else ... ignore constant fp. There is not any good way to 1913 // to represent them here in dwarf. 1914 Asm->OutStreamer.EmitLabel(end); 1915 } 1916 } 1917} 1918 1919/// EmitDebugARanges - Emit visible names into a debug aranges section. 1920/// 1921void DwarfDebug::EmitDebugARanges() { 1922 // Start the dwarf aranges section. 1923 Asm->OutStreamer.SwitchSection( 1924 Asm->getObjFileLowering().getDwarfARangesSection()); 1925} 1926 1927/// emitDebugRanges - Emit visible names into a debug ranges section. 1928/// 1929void DwarfDebug::emitDebugRanges() { 1930 // Start the dwarf ranges section. 1931 Asm->OutStreamer.SwitchSection( 1932 Asm->getObjFileLowering().getDwarfRangesSection()); 1933 unsigned char Size = Asm->getTargetData().getPointerSize(); 1934 for (SmallVector<const MCSymbol *, 8>::iterator 1935 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end(); 1936 I != E; ++I) { 1937 if (*I) 1938 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0); 1939 else 1940 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0); 1941 } 1942} 1943 1944/// emitDebugMacInfo - Emit visible names into a debug macinfo section. 1945/// 1946void DwarfDebug::emitDebugMacInfo() { 1947 if (const MCSection *LineInfo = 1948 Asm->getObjFileLowering().getDwarfMacroInfoSection()) { 1949 // Start the dwarf macinfo section. 1950 Asm->OutStreamer.SwitchSection(LineInfo); 1951 } 1952} 1953 1954/// emitDebugInlineInfo - Emit inline info using following format. 1955/// Section Header: 1956/// 1. length of section 1957/// 2. Dwarf version number 1958/// 3. address size. 1959/// 1960/// Entries (one "entry" for each function that was inlined): 1961/// 1962/// 1. offset into __debug_str section for MIPS linkage name, if exists; 1963/// otherwise offset into __debug_str for regular function name. 1964/// 2. offset into __debug_str section for regular function name. 1965/// 3. an unsigned LEB128 number indicating the number of distinct inlining 1966/// instances for the function. 1967/// 1968/// The rest of the entry consists of a {die_offset, low_pc} pair for each 1969/// inlined instance; the die_offset points to the inlined_subroutine die in the 1970/// __debug_info section, and the low_pc is the starting address for the 1971/// inlining instance. 1972void DwarfDebug::emitDebugInlineInfo() { 1973 if (!Asm->MAI->doesDwarfUsesInlineInfoSection()) 1974 return; 1975 1976 if (!FirstCU) 1977 return; 1978 1979 Asm->OutStreamer.SwitchSection( 1980 Asm->getObjFileLowering().getDwarfDebugInlineSection()); 1981 1982 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry"); 1983 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1), 1984 Asm->GetTempSymbol("debug_inlined_begin", 1), 4); 1985 1986 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1)); 1987 1988 Asm->OutStreamer.AddComment("Dwarf Version"); 1989 Asm->EmitInt16(dwarf::DWARF_VERSION); 1990 Asm->OutStreamer.AddComment("Address Size (in bytes)"); 1991 Asm->EmitInt8(Asm->getTargetData().getPointerSize()); 1992 1993 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(), 1994 E = InlinedSPNodes.end(); I != E; ++I) { 1995 1996 const MDNode *Node = *I; 1997 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II 1998 = InlineInfo.find(Node); 1999 SmallVector<InlineInfoLabels, 4> &Labels = II->second; 2000 DISubprogram SP(Node); 2001 StringRef LName = SP.getLinkageName(); 2002 StringRef Name = SP.getName(); 2003 2004 Asm->OutStreamer.AddComment("MIPS linkage name"); 2005 if (LName.empty()) { 2006 Asm->OutStreamer.EmitBytes(Name, 0); 2007 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator. 2008 } else 2009 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)), 2010 DwarfStrSectionSym); 2011 2012 Asm->OutStreamer.AddComment("Function name"); 2013 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym); 2014 Asm->EmitULEB128(Labels.size(), "Inline count"); 2015 2016 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(), 2017 LE = Labels.end(); LI != LE; ++LI) { 2018 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset"); 2019 Asm->EmitInt32(LI->second->getOffset()); 2020 2021 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc"); 2022 Asm->OutStreamer.EmitSymbolValue(LI->first, 2023 Asm->getTargetData().getPointerSize(),0); 2024 } 2025 } 2026 2027 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1)); 2028} 2029