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