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