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