1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
17 #include "DwarfCompileUnit.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Analysis/DebugInfo.h"
34 #include "llvm/Analysis/DIBuilder.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/Path.h"
47 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
49 cl::desc("Disable debug info printing"));
51 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
52 cl::desc("Make an absence of debug location information explicit."),
56 const char *DWARFGroupName = "DWARF Emission";
57 const char *DbgTimerName = "DWARF Debug Writer";
58 } // end anonymous namespace
60 //===----------------------------------------------------------------------===//
62 /// Configuration values for initial hash set sizes (log2).
64 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
68 DIType DbgVariable::getType() const {
69 DIType Ty = Var.getType();
70 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
72 if (Var.isBlockByrefVariable()) {
73 /* Byref variables, in Blocks, are declared by the programmer as
74 "SomeType VarName;", but the compiler creates a
75 __Block_byref_x_VarName struct, and gives the variable VarName
76 either the struct, or a pointer to the struct, as its type. This
77 is necessary for various behind-the-scenes things the compiler
78 needs to do with by-reference variables in blocks.
80 However, as far as the original *programmer* is concerned, the
81 variable should still have type 'SomeType', as originally declared.
83 The following function dives into the __Block_byref_x_VarName
84 struct to find the original type of the variable. This will be
85 passed back to the code generating the type for the Debug
86 Information Entry for the variable 'VarName'. 'VarName' will then
87 have the original type 'SomeType' in its debug information.
89 The original type 'SomeType' will be the type of the field named
90 'VarName' inside the __Block_byref_x_VarName struct.
92 NOTE: In order for this to not completely fail on the debugger
93 side, the Debug Information Entry for the variable VarName needs to
94 have a DW_AT_location that tells the debugger how to unwind through
95 the pointers and __Block_byref_x_VarName struct to find the actual
96 value of the variable. The function addBlockByrefType does this. */
98 unsigned tag = Ty.getTag();
100 if (tag == dwarf::DW_TAG_pointer_type) {
101 DIDerivedType DTy = DIDerivedType(Ty);
102 subType = DTy.getTypeDerivedFrom();
105 DICompositeType blockStruct = DICompositeType(subType);
106 DIArray Elements = blockStruct.getTypeArray();
108 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
109 DIDescriptor Element = Elements.getElement(i);
110 DIDerivedType DT = DIDerivedType(Element);
111 if (getName() == DT.getName())
112 return (DT.getTypeDerivedFrom());
119 } // end llvm namespace
121 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
122 : Asm(A), MMI(Asm->MMI), FirstCU(0),
123 AbbreviationsSet(InitAbbreviationsSetSize),
125 NextStringPoolNumber = 0;
127 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
128 DwarfStrSectionSym = TextSectionSym = 0;
129 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
130 FunctionBeginSym = FunctionEndSym = 0;
132 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
136 DwarfDebug::~DwarfDebug() {
139 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
140 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
141 if (Entry.first) return Entry.first;
143 Entry.second = NextStringPoolNumber++;
144 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
148 /// assignAbbrevNumber - Define a unique number for the abbreviation.
150 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
151 // Profile the node so that we can make it unique.
155 // Check the set for priors.
156 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
158 // If it's newly added.
159 if (InSet == &Abbrev) {
160 // Add to abbreviation list.
161 Abbreviations.push_back(&Abbrev);
163 // Assign the vector position + 1 as its number.
164 Abbrev.setNumber(Abbreviations.size());
166 // Assign existing abbreviation number.
167 Abbrev.setNumber(InSet->getNumber());
171 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
172 /// printer to not emit usual symbol prefix before the symbol name is used then
173 /// return linkage name after skipping this special LLVM prefix.
174 static StringRef getRealLinkageName(StringRef LinkageName) {
176 if (LinkageName.startswith(StringRef(&One, 1)))
177 return LinkageName.substr(1);
181 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
182 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
183 /// If there are global variables in this scope then create and insert
184 /// DIEs for these variables.
185 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
186 CompileUnit *SPCU = getCompileUnit(SPNode);
187 DIE *SPDie = SPCU->getDIE(SPNode);
189 assert(SPDie && "Unable to find subprogram DIE!");
190 DISubprogram SP(SPNode);
192 DISubprogram SPDecl = SP.getFunctionDeclaration();
193 if (SPDecl.isSubprogram())
194 // Refer function declaration directly.
195 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
196 SPCU->getOrCreateSubprogramDIE(SPDecl));
198 // There is not any need to generate specification DIE for a function
199 // defined at compile unit level. If a function is defined inside another
200 // function then gdb prefers the definition at top level and but does not
201 // expect specification DIE in parent function. So avoid creating
202 // specification DIE for a function defined inside a function.
203 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
204 !SP.getContext().isFile() &&
205 !isSubprogramContext(SP.getContext())) {
206 SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
209 DICompositeType SPTy = SP.getType();
210 DIArray Args = SPTy.getTypeArray();
211 unsigned SPTag = SPTy.getTag();
212 if (SPTag == dwarf::DW_TAG_subroutine_type)
213 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
214 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
215 DIType ATy = DIType(DIType(Args.getElement(i)));
216 SPCU->addType(Arg, ATy);
217 if (ATy.isArtificial())
218 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
219 SPDie->addChild(Arg);
221 DIE *SPDeclDie = SPDie;
222 SPDie = new DIE(dwarf::DW_TAG_subprogram);
223 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
228 // Pick up abstract subprogram DIE.
229 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
230 SPDie = new DIE(dwarf::DW_TAG_subprogram);
231 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
232 dwarf::DW_FORM_ref4, AbsSPDIE);
236 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
237 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
238 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
239 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
240 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
241 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
242 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
247 /// constructLexicalScope - Construct new DW_TAG_lexical_block
248 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
249 DIE *DwarfDebug::constructLexicalScopeDIE(LexicalScope *Scope) {
251 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
252 if (Scope->isAbstractScope())
255 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
259 CompileUnit *TheCU = getCompileUnit(Scope->getScopeNode());
260 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
261 if (Ranges.size() > 1) {
262 // .debug_range section has not been laid out yet. Emit offset in
263 // .debug_range as a uint, size 4, for now. emitDIE will handle
264 // DW_AT_ranges appropriately.
265 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
266 DebugRangeSymbols.size()
267 * Asm->getTargetData().getPointerSize());
268 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
269 RE = Ranges.end(); RI != RE; ++RI) {
270 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
271 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
273 DebugRangeSymbols.push_back(NULL);
274 DebugRangeSymbols.push_back(NULL);
278 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
279 const MCSymbol *End = getLabelAfterInsn(RI->second);
281 if (End == 0) return 0;
283 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
284 assert(End->isDefined() && "Invalid end label for an inlined scope!");
286 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
287 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
292 /// constructInlinedScopeDIE - This scope represents inlined body of
293 /// a function. Construct DIE to represent this concrete inlined copy
295 DIE *DwarfDebug::constructInlinedScopeDIE(LexicalScope *Scope) {
297 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
298 assert (Ranges.empty() == false
299 && "LexicalScope does not have instruction markers!");
301 if (!Scope->getScopeNode())
303 DIScope DS(Scope->getScopeNode());
304 DISubprogram InlinedSP = getDISubprogram(DS);
305 CompileUnit *TheCU = getCompileUnit(InlinedSP);
306 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
308 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
312 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
313 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
314 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
316 if (StartLabel == 0 || EndLabel == 0) {
317 assert (0 && "Unexpected Start and End labels for a inlined scope!");
320 assert(StartLabel->isDefined() &&
321 "Invalid starting label for an inlined scope!");
322 assert(EndLabel->isDefined() &&
323 "Invalid end label for an inlined scope!");
325 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
326 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
327 dwarf::DW_FORM_ref4, OriginDIE);
329 if (Ranges.size() > 1) {
330 // .debug_range section has not been laid out yet. Emit offset in
331 // .debug_range as a uint, size 4, for now. emitDIE will handle
332 // DW_AT_ranges appropriately.
333 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
334 DebugRangeSymbols.size()
335 * Asm->getTargetData().getPointerSize());
336 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
337 RE = Ranges.end(); RI != RE; ++RI) {
338 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
339 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
341 DebugRangeSymbols.push_back(NULL);
342 DebugRangeSymbols.push_back(NULL);
344 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
346 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
350 InlinedSubprogramDIEs.insert(OriginDIE);
352 // Track the start label for this inlined function.
353 //.debug_inlined section specification does not clearly state how
354 // to emit inlined scope that is split into multiple instruction ranges.
355 // For now, use first instruction range and emit low_pc/high_pc pair and
356 // corresponding .debug_inlined section entry for this pair.
357 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
358 I = InlineInfo.find(InlinedSP);
360 if (I == InlineInfo.end()) {
361 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
363 InlinedSPNodes.push_back(InlinedSP);
365 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
367 DILocation DL(Scope->getInlinedAt());
368 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
369 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
374 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
375 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, LexicalScope *Scope) {
376 StringRef Name = DV->getName();
380 // Translate tag to proper Dwarf tag.
381 unsigned Tag = DV->getTag();
383 // Define variable debug information entry.
384 DIE *VariableDie = new DIE(Tag);
385 CompileUnit *VariableCU = getCompileUnit(DV->getVariable());
386 DbgVariable *AbsVar = DV->getAbstractVariable();
387 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
389 VariableCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
390 dwarf::DW_FORM_ref4, AbsDIE);
392 VariableCU->addString(VariableDie, dwarf::DW_AT_name,
393 dwarf::DW_FORM_string, Name);
394 VariableCU->addSourceLine(VariableDie, DV->getVariable());
395 VariableCU->addType(VariableDie, DV->getType());
398 if (DV->isArtificial())
399 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
400 dwarf::DW_FORM_flag, 1);
402 if (Scope->isAbstractScope()) {
403 DV->setDIE(VariableDie);
407 // Add variable address.
409 unsigned Offset = DV->getDotDebugLocOffset();
411 VariableCU->addLabel(VariableDie, dwarf::DW_AT_location,
412 dwarf::DW_FORM_data4,
413 Asm->GetTempSymbol("debug_loc", Offset));
414 DV->setDIE(VariableDie);
415 UseDotDebugLocEntry.insert(VariableDie);
419 // Check if variable is described by a DBG_VALUE instruction.
420 if (const MachineInstr *DVInsn = DV->getMInsn()) {
421 bool updated = false;
422 if (DVInsn->getNumOperands() == 3) {
423 if (DVInsn->getOperand(0).isReg()) {
424 const MachineOperand RegOp = DVInsn->getOperand(0);
425 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
426 if (DVInsn->getOperand(1).isImm() &&
427 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
428 unsigned FrameReg = 0;
429 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
431 TFI->getFrameIndexReference(*Asm->MF,
432 DVInsn->getOperand(1).getImm(),
434 MachineLocation Location(FrameReg, Offset);
435 VariableCU->addVariableAddress(DV, VariableDie, Location);
437 } else if (RegOp.getReg())
438 VariableCU->addVariableAddress(DV, VariableDie,
439 MachineLocation(RegOp.getReg()));
442 else if (DVInsn->getOperand(0).isImm())
444 VariableCU->addConstantValue(VariableDie, DVInsn->getOperand(0),
446 else if (DVInsn->getOperand(0).isFPImm())
448 VariableCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
449 else if (DVInsn->getOperand(0).isCImm())
451 VariableCU->addConstantValue(VariableDie,
452 DVInsn->getOperand(0).getCImm(),
453 DV->getType().isUnsignedDIType());
455 VariableCU->addVariableAddress(DV, VariableDie,
456 Asm->getDebugValueLocation(DVInsn));
460 // If variableDie is not updated then DBG_VALUE instruction does not
461 // have valid variable info.
465 DV->setDIE(VariableDie);
468 // .. else use frame index.
469 int FI = DV->getFrameIndex();
471 unsigned FrameReg = 0;
472 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
474 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
475 MachineLocation Location(FrameReg, Offset);
476 VariableCU->addVariableAddress(DV, VariableDie, Location);
480 DV->setDIE(VariableDie);
485 /// constructScopeDIE - Construct a DIE for this scope.
486 DIE *DwarfDebug::constructScopeDIE(LexicalScope *Scope) {
487 if (!Scope || !Scope->getScopeNode())
490 SmallVector <DIE *, 8> Children;
492 // Collect arguments for current function.
493 if (LScopes.isCurrentFunctionScope(Scope))
494 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
495 if (DbgVariable *ArgDV = CurrentFnArguments[i])
496 if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
497 Children.push_back(Arg);
499 // Collect lexical scope childrens first.
500 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
501 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
502 if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
503 Children.push_back(Variable);
504 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
505 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
506 if (DIE *Nested = constructScopeDIE(Scopes[j]))
507 Children.push_back(Nested);
508 DIScope DS(Scope->getScopeNode());
509 DIE *ScopeDIE = NULL;
510 if (Scope->getInlinedAt())
511 ScopeDIE = constructInlinedScopeDIE(Scope);
512 else if (DS.isSubprogram()) {
513 ProcessedSPNodes.insert(DS);
514 if (Scope->isAbstractScope()) {
515 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
516 // Note down abstract DIE.
518 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
521 ScopeDIE = updateSubprogramScopeDIE(DS);
524 // There is no need to emit empty lexical block DIE.
525 if (Children.empty())
527 ScopeDIE = constructLexicalScopeDIE(Scope);
530 if (!ScopeDIE) return NULL;
533 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
534 E = Children.end(); I != E; ++I)
535 ScopeDIE->addChild(*I);
537 if (DS.isSubprogram())
538 getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
543 /// GetOrCreateSourceID - Look up the source id with the given directory and
544 /// source file names. If none currently exists, create a new id and insert it
545 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
548 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
550 // If FE did not provide a file name, then assume stdin.
551 if (FileName.empty())
552 return GetOrCreateSourceID("<stdin>", StringRef());
554 // MCStream expects full path name as filename.
555 if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
556 SmallString<128> FullPathName = DirName;
557 sys::path::append(FullPathName, FileName);
558 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
559 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
562 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
563 if (Entry.getValue())
564 return Entry.getValue();
566 unsigned SrcId = SourceIdMap.size();
567 Entry.setValue(SrcId);
569 // Print out a .file directive to specify files for .loc directives.
570 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
575 /// constructCompileUnit - Create new CompileUnit for the given
576 /// metadata node with tag DW_TAG_compile_unit.
577 void DwarfDebug::constructCompileUnit(const MDNode *N) {
578 DICompileUnit DIUnit(N);
579 StringRef FN = DIUnit.getFilename();
580 StringRef Dir = DIUnit.getDirectory();
581 unsigned ID = GetOrCreateSourceID(FN, Dir);
583 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
584 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
585 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
586 DIUnit.getProducer());
587 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
588 DIUnit.getLanguage());
589 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
590 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
591 // simplifies debug range entries.
592 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
593 // DW_AT_stmt_list is a offset of line number information for this
594 // compile unit in debug_line section.
595 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
596 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
597 Asm->GetTempSymbol("section_line"));
599 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
602 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
603 if (DIUnit.isOptimized())
604 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
606 StringRef Flags = DIUnit.getFlags();
608 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,
611 unsigned RVer = DIUnit.getRunTimeVersion();
613 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
614 dwarf::DW_FORM_data1, RVer);
618 CUMap.insert(std::make_pair(N, NewCU));
621 /// getCompileUnit - Get CompileUnit DIE.
622 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
623 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
625 const MDNode *CUNode = NULL;
626 if (D.isCompileUnit())
628 else if (D.isSubprogram())
629 CUNode = DISubprogram(N).getCompileUnit();
631 CUNode = DIType(N).getCompileUnit();
632 else if (D.isGlobalVariable())
633 CUNode = DIGlobalVariable(N).getCompileUnit();
634 else if (D.isVariable())
635 CUNode = DIVariable(N).getCompileUnit();
636 else if (D.isNameSpace())
637 CUNode = DINameSpace(N).getCompileUnit();
639 CUNode = DIFile(N).getCompileUnit();
643 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
644 = CUMap.find(CUNode);
645 if (I == CUMap.end())
650 /// constructGlobalVariableDIE - Construct global variable DIE.
651 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
652 DIGlobalVariable GV(N);
654 // If debug information is malformed then ignore it.
655 if (GV.Verify() == false)
658 // Check for pre-existence.
659 CompileUnit *TheCU = getCompileUnit(N);
660 TheCU->createGlobalVariableDIE(N);
664 /// construct SubprogramDIE - Construct subprogram DIE.
665 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
668 // Check for pre-existence.
669 CompileUnit *TheCU = getCompileUnit(N);
670 if (TheCU->getDIE(N))
673 if (!SP.isDefinition())
674 // This is a method declaration which will be handled while constructing
678 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
681 TheCU->insertDIE(N, SubprogramDie);
683 // Add to context owner.
684 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
687 TheCU->addGlobal(SP.getName(), SubprogramDie);
692 /// beginModule - Emit all Dwarf sections that should come prior to the
693 /// content. Create global DIEs and emit initial debug info sections.
694 /// This is invoked by the target AsmPrinter.
695 void DwarfDebug::beginModule(Module *M) {
696 if (DisableDebugInfoPrinting)
699 // If module has named metadata anchors then use them, otherwise scan the
700 // module using debug info finder to collect debug info.
701 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
704 NamedMDNode *GV_Nodes = M->getNamedMetadata("llvm.dbg.gv");
705 NamedMDNode *SP_Nodes = M->getNamedMetadata("llvm.dbg.sp");
706 if (!GV_Nodes && !SP_Nodes)
707 // If there are not any global variables or any functions then
708 // there is not any debug info in this module.
711 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i)
712 constructCompileUnit(CU_Nodes->getOperand(i));
715 for (unsigned i = 0, e = GV_Nodes->getNumOperands(); i != e; ++i)
716 constructGlobalVariableDIE(GV_Nodes->getOperand(i));
719 for (unsigned i = 0, e = SP_Nodes->getNumOperands(); i != e; ++i)
720 constructSubprogramDIE(SP_Nodes->getOperand(i));
724 DebugInfoFinder DbgFinder;
725 DbgFinder.processModule(*M);
727 bool HasDebugInfo = false;
728 // Scan all the compile-units to see if there are any marked as the main
729 // unit. If not, we do not generate debug info.
730 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
731 E = DbgFinder.compile_unit_end(); I != E; ++I) {
732 if (DICompileUnit(*I).isMain()) {
737 if (!HasDebugInfo) return;
739 // Create all the compile unit DIEs.
740 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
741 E = DbgFinder.compile_unit_end(); I != E; ++I)
742 constructCompileUnit(*I);
744 // Create DIEs for each global variable.
745 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
746 E = DbgFinder.global_variable_end(); I != E; ++I)
747 constructGlobalVariableDIE(*I);
749 // Create DIEs for each subprogram.
750 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
751 E = DbgFinder.subprogram_end(); I != E; ++I)
752 constructSubprogramDIE(*I);
755 // Tell MMI that we have debug info.
756 MMI->setDebugInfoAvailability(true);
758 // Emit initial sections.
762 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
763 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
764 DIType Ty(NMD->getOperand(i));
765 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
768 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
769 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
770 DIType Ty(NMD->getOperand(i));
771 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
774 // Prime section data.
775 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
778 /// endModule - Emit all Dwarf sections that should come after the content.
780 void DwarfDebug::endModule() {
781 if (!FirstCU) return;
782 const Module *M = MMI->getModule();
783 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
784 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
785 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
786 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
787 DISubprogram SP(AllSPs->getOperand(SI));
788 if (!SP.Verify()) continue;
790 // Collect info for variables that were optimized out.
791 if (!SP.isDefinition()) continue;
792 StringRef FName = SP.getLinkageName();
794 FName = SP.getName();
795 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
797 unsigned E = NMD->getNumOperands();
799 LexicalScope *Scope = new LexicalScope(NULL, DIDescriptor(SP), NULL,
801 DeadFnScopeMap[SP] = Scope;
802 SmallVector<DbgVariable, 8> Variables;
803 for (unsigned I = 0; I != E; ++I) {
804 DIVariable DV(NMD->getOperand(I));
805 if (!DV.Verify()) continue;
806 Variables.push_back(DbgVariable(DV, NULL));
809 // Construct subprogram DIE and add variables DIEs.
810 constructSubprogramDIE(SP);
811 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
812 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
813 if (DIE *VariableDIE = constructVariableDIE(&Variables[i], Scope))
814 ScopeDIE->addChild(VariableDIE);
819 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
820 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
821 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
823 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
826 // Emit DW_AT_containing_type attribute to connect types with their
827 // vtable holding type.
828 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
829 CUE = CUMap.end(); CUI != CUE; ++CUI) {
830 CompileUnit *TheCU = CUI->second;
831 TheCU->constructContainingTypeDIEs();
834 // Standard sections final addresses.
835 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
836 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
837 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
838 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
840 // End text sections.
841 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
842 Asm->OutStreamer.SwitchSection(SectionMap[i]);
843 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
846 // Compute DIE offsets and sizes.
847 computeSizeAndOffsets();
849 // Emit all the DIEs into a debug info section
852 // Corresponding abbreviations into a abbrev section.
855 // Emit info into a debug pubnames section.
858 // Emit info into a debug pubtypes section.
861 // Emit info into a debug loc section.
864 // Emit info into a debug aranges section.
867 // Emit info into a debug ranges section.
870 // Emit info into a debug macinfo section.
874 emitDebugInlineInfo();
876 // Emit info into a debug str section.
880 DeleteContainerSeconds(DeadFnScopeMap);
881 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
882 E = CUMap.end(); I != E; ++I)
884 FirstCU = NULL; // Reset for the next Module, if any.
887 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
888 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
890 LLVMContext &Ctx = DV->getContext();
891 // More then one inlined variable corresponds to one abstract variable.
892 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
893 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
895 return AbsDbgVariable;
897 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
901 AbsDbgVariable = new DbgVariable(Var, NULL);
902 addScopeVariable(Scope, AbsDbgVariable);
903 AbstractVariables[Var] = AbsDbgVariable;
904 return AbsDbgVariable;
907 /// addCurrentFnArgument - If Var is a current function argument then add
908 /// it to CurrentFnArguments list.
909 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
910 DbgVariable *Var, LexicalScope *Scope) {
911 if (!LScopes.isCurrentFunctionScope(Scope))
913 DIVariable DV = Var->getVariable();
914 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
916 unsigned ArgNo = DV.getArgNumber();
920 size_t Size = CurrentFnArguments.size();
922 CurrentFnArguments.resize(MF->getFunction()->arg_size());
923 // llvm::Function argument size is not good indicator of how many
924 // arguments does the function have at source level.
926 CurrentFnArguments.resize(ArgNo * 2);
927 CurrentFnArguments[ArgNo - 1] = Var;
931 /// collectVariableInfoFromMMITable - Collect variable information from
932 /// side table maintained by MMI.
934 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
935 SmallPtrSet<const MDNode *, 16> &Processed) {
936 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
937 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
938 VE = VMap.end(); VI != VE; ++VI) {
939 const MDNode *Var = VI->first;
941 Processed.insert(Var);
943 const std::pair<unsigned, DebugLoc> &VP = VI->second;
945 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
947 // If variable scope is not found then skip this variable.
951 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
952 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
953 RegVar->setFrameIndex(VP.first);
954 if (!addCurrentFnArgument(MF, RegVar, Scope))
955 addScopeVariable(Scope, RegVar);
957 AbsDbgVariable->setFrameIndex(VP.first);
961 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
962 /// DBG_VALUE instruction, is in a defined reg.
963 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
964 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
965 return MI->getNumOperands() == 3 &&
966 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
967 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
970 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
972 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
973 const MCSymbol *FLabel,
974 const MCSymbol *SLabel,
975 const MachineInstr *MI) {
976 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
978 if (MI->getNumOperands() != 3) {
979 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
980 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
982 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
983 MachineLocation MLoc;
984 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
985 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
987 if (MI->getOperand(0).isImm())
988 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
989 if (MI->getOperand(0).isFPImm())
990 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
991 if (MI->getOperand(0).isCImm())
992 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
994 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
995 return DotDebugLocEntry();
998 /// collectVariableInfo - Find variables for each lexical scope.
1000 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1001 SmallPtrSet<const MDNode *, 16> &Processed) {
1003 /// collection info from MMI table.
1004 collectVariableInfoFromMMITable(MF, Processed);
1006 for (SmallVectorImpl<const MDNode*>::const_iterator
1007 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1009 const MDNode *Var = *UVI;
1010 if (Processed.count(Var))
1013 // History contains relevant DBG_VALUE instructions for Var and instructions
1015 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1016 if (History.empty())
1018 const MachineInstr *MInsn = History.front();
1021 LexicalScope *Scope = NULL;
1022 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1023 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1024 Scope = LScopes.getCurrentFunctionScope();
1026 if (DV.getVersion() <= LLVMDebugVersion9)
1027 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1029 if (MDNode *IA = DV.getInlinedAt())
1030 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1032 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1035 // If variable scope is not found then skip this variable.
1039 Processed.insert(DV);
1040 assert(MInsn->isDebugValue() && "History must begin with debug value");
1041 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1042 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1043 if (!addCurrentFnArgument(MF, RegVar, Scope))
1044 addScopeVariable(Scope, RegVar);
1046 AbsVar->setMInsn(MInsn);
1048 // Simple ranges that are fully coalesced.
1049 if (History.size() <= 1 || (History.size() == 2 &&
1050 MInsn->isIdenticalTo(History.back()))) {
1051 RegVar->setMInsn(MInsn);
1055 // handle multiple DBG_VALUE instructions describing one variable.
1056 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1058 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1059 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1060 const MachineInstr *Begin = *HI;
1061 assert(Begin->isDebugValue() && "Invalid History entry");
1063 // Check if DBG_VALUE is truncating a range.
1064 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1065 && !Begin->getOperand(0).getReg())
1068 // Compute the range for a register location.
1069 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1070 const MCSymbol *SLabel = 0;
1073 // If Begin is the last instruction in History then its value is valid
1074 // until the end of the function.
1075 SLabel = FunctionEndSym;
1077 const MachineInstr *End = HI[1];
1078 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1079 << "\t" << *Begin << "\t" << *End << "\n");
1080 if (End->isDebugValue())
1081 SLabel = getLabelBeforeInsn(End);
1083 // End is a normal instruction clobbering the range.
1084 SLabel = getLabelAfterInsn(End);
1085 assert(SLabel && "Forgot label after clobber instruction");
1090 // The value is valid until the next DBG_VALUE or clobber.
1091 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1093 DotDebugLocEntries.push_back(DotDebugLocEntry());
1096 // Collect info for variables that were optimized out.
1097 const Function *F = MF->getFunction();
1098 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1099 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1100 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1101 if (!DV || !Processed.insert(DV))
1103 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1104 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1109 /// getLabelBeforeInsn - Return Label preceding the instruction.
1110 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1111 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1112 assert(Label && "Didn't insert label before instruction");
1116 /// getLabelAfterInsn - Return Label immediately following the instruction.
1117 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1118 return LabelsAfterInsn.lookup(MI);
1121 /// beginInstruction - Process beginning of an instruction.
1122 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1123 // Check if source location changes, but ignore DBG_VALUE locations.
1124 if (!MI->isDebugValue()) {
1125 DebugLoc DL = MI->getDebugLoc();
1126 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1127 unsigned Flags = DWARF2_FLAG_IS_STMT;
1129 if (DL == PrologEndLoc) {
1130 Flags |= DWARF2_FLAG_PROLOGUE_END;
1131 PrologEndLoc = DebugLoc();
1133 if (!DL.isUnknown()) {
1134 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1135 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1137 recordSourceLine(0, 0, 0, 0);
1141 // Insert labels where requested.
1142 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1143 LabelsBeforeInsn.find(MI);
1146 if (I == LabelsBeforeInsn.end())
1149 // Label already assigned.
1154 PrevLabel = MMI->getContext().CreateTempSymbol();
1155 Asm->OutStreamer.EmitLabel(PrevLabel);
1157 I->second = PrevLabel;
1160 /// endInstruction - Process end of an instruction.
1161 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1162 // Don't create a new label after DBG_VALUE instructions.
1163 // They don't generate code.
1164 if (!MI->isDebugValue())
1167 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1168 LabelsAfterInsn.find(MI);
1171 if (I == LabelsAfterInsn.end())
1174 // Label already assigned.
1178 // We need a label after this instruction.
1180 PrevLabel = MMI->getContext().CreateTempSymbol();
1181 Asm->OutStreamer.EmitLabel(PrevLabel);
1183 I->second = PrevLabel;
1186 /// identifyScopeMarkers() -
1187 /// Each LexicalScope has first instruction and last instruction to mark
1188 /// beginning and end of a scope respectively. Create an inverse map that list
1189 /// scopes starts (and ends) with an instruction. One instruction may start (or
1190 /// end) multiple scopes. Ignore scopes that are not reachable.
1191 void DwarfDebug::identifyScopeMarkers() {
1192 SmallVector<LexicalScope *, 4> WorkList;
1193 WorkList.push_back(LScopes.getCurrentFunctionScope());
1194 while (!WorkList.empty()) {
1195 LexicalScope *S = WorkList.pop_back_val();
1197 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1198 if (!Children.empty())
1199 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1200 SE = Children.end(); SI != SE; ++SI)
1201 WorkList.push_back(*SI);
1203 if (S->isAbstractScope())
1206 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1209 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1210 RE = Ranges.end(); RI != RE; ++RI) {
1211 assert(RI->first && "InsnRange does not have first instruction!");
1212 assert(RI->second && "InsnRange does not have second instruction!");
1213 requestLabelBeforeInsn(RI->first);
1214 requestLabelAfterInsn(RI->second);
1219 /// getScopeNode - Get MDNode for DebugLoc's scope.
1220 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1221 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1222 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1223 return DL.getScope(Ctx);
1226 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1227 /// line number info for the function.
1228 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1229 const MDNode *Scope = getScopeNode(DL, Ctx);
1230 DISubprogram SP = getDISubprogram(Scope);
1232 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1236 /// beginFunction - Gather pre-function debug information. Assumes being
1237 /// emitted immediately after the function entry point.
1238 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1239 if (!MMI->hasDebugInfo()) return;
1240 LScopes.initialize(*MF);
1241 if (LScopes.empty()) return;
1242 identifyScopeMarkers();
1244 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1245 Asm->getFunctionNumber());
1246 // Assumes in correct section after the entry point.
1247 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1249 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1251 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1252 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1253 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1255 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1257 bool AtBlockEntry = true;
1258 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1260 const MachineInstr *MI = II;
1262 if (MI->isDebugValue()) {
1263 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1265 // Keep track of user variables.
1267 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1269 // Variable is in a register, we need to check for clobbers.
1270 if (isDbgValueInDefinedReg(MI))
1271 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1273 // Check the history of this variable.
1274 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1275 if (History.empty()) {
1276 UserVariables.push_back(Var);
1277 // The first mention of a function argument gets the FunctionBeginSym
1278 // label, so arguments are visible when breaking at function entry.
1280 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1281 DISubprogram(getDISubprogram(DV.getContext()))
1282 .describes(MF->getFunction()))
1283 LabelsBeforeInsn[MI] = FunctionBeginSym;
1285 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1286 const MachineInstr *Prev = History.back();
1287 if (Prev->isDebugValue()) {
1288 // Coalesce identical entries at the end of History.
1289 if (History.size() >= 2 &&
1290 Prev->isIdenticalTo(History[History.size() - 2])) {
1291 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1293 << "\t" << *History[History.size() - 2] << "\n");
1297 // Terminate old register assignments that don't reach MI;
1298 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1299 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1300 isDbgValueInDefinedReg(Prev)) {
1301 // Previous register assignment needs to terminate at the end of
1303 MachineBasicBlock::const_iterator LastMI =
1304 PrevMBB->getLastNonDebugInstr();
1305 if (LastMI == PrevMBB->end()) {
1306 // Drop DBG_VALUE for empty range.
1307 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1308 << "\t" << *Prev << "\n");
1312 // Terminate after LastMI.
1313 History.push_back(LastMI);
1318 History.push_back(MI);
1320 // Not a DBG_VALUE instruction.
1322 AtBlockEntry = false;
1324 // First known non DBG_VALUE location marks beginning of function
1326 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1327 PrologEndLoc = MI->getDebugLoc();
1329 // Check if the instruction clobbers any registers with debug vars.
1330 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1331 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1332 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1334 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1335 unsigned Reg = *AI; ++AI) {
1336 const MDNode *Var = LiveUserVar[Reg];
1339 // Reg is now clobbered.
1340 LiveUserVar[Reg] = 0;
1342 // Was MD last defined by a DBG_VALUE referring to Reg?
1343 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1344 if (HistI == DbgValues.end())
1346 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1347 if (History.empty())
1349 const MachineInstr *Prev = History.back();
1350 // Sanity-check: Register assignments are terminated at the end of
1352 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1354 // Is the variable still in Reg?
1355 if (!isDbgValueInDefinedReg(Prev) ||
1356 Prev->getOperand(0).getReg() != Reg)
1358 // Var is clobbered. Make sure the next instruction gets a label.
1359 History.push_back(MI);
1366 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1368 SmallVectorImpl<const MachineInstr*> &History = I->second;
1369 if (History.empty())
1372 // Make sure the final register assignments are terminated.
1373 const MachineInstr *Prev = History.back();
1374 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1375 const MachineBasicBlock *PrevMBB = Prev->getParent();
1376 MachineBasicBlock::const_iterator LastMI =
1377 PrevMBB->getLastNonDebugInstr();
1378 if (LastMI == PrevMBB->end())
1379 // Drop DBG_VALUE for empty range.
1382 // Terminate after LastMI.
1383 History.push_back(LastMI);
1386 // Request labels for the full history.
1387 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1388 const MachineInstr *MI = History[i];
1389 if (MI->isDebugValue())
1390 requestLabelBeforeInsn(MI);
1392 requestLabelAfterInsn(MI);
1396 PrevInstLoc = DebugLoc();
1397 PrevLabel = FunctionBeginSym;
1399 // Record beginning of function.
1400 if (!PrologEndLoc.isUnknown()) {
1401 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1402 MF->getFunction()->getContext());
1403 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1404 FnStartDL.getScope(MF->getFunction()->getContext()),
1405 DWARF2_FLAG_IS_STMT);
1409 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1410 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1411 ScopeVariables[LS].push_back(Var);
1412 // Vars.push_back(Var);
1415 /// endFunction - Gather and emit post-function debug information.
1417 void DwarfDebug::endFunction(const MachineFunction *MF) {
1418 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1420 // Define end label for subprogram.
1421 FunctionEndSym = Asm->GetTempSymbol("func_end",
1422 Asm->getFunctionNumber());
1423 // Assumes in correct section after the entry point.
1424 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1426 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1427 collectVariableInfo(MF, ProcessedVars);
1429 // Construct abstract scopes.
1430 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1431 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1432 LexicalScope *AScope = AList[i];
1433 DISubprogram SP(AScope->getScopeNode());
1435 // Collect info for variables that were optimized out.
1436 StringRef FName = SP.getLinkageName();
1438 FName = SP.getName();
1439 if (NamedMDNode *NMD =
1440 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
1441 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1442 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1443 if (!DV || !ProcessedVars.insert(DV))
1445 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1446 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1450 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1451 constructScopeDIE(AScope);
1454 DIE *CurFnDIE = constructScopeDIE(LScopes.getCurrentFunctionScope());
1456 if (!DisableFramePointerElim(*MF)) {
1457 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1458 CompileUnit *TheCU = getCompileUnit(FnScope->getScopeNode());
1459 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1460 dwarf::DW_FORM_flag, 1);
1462 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1463 MMI->getFrameMoves()));
1466 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1467 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1468 DeleteContainerPointers(I->second);
1469 ScopeVariables.clear();
1470 DeleteContainerPointers(CurrentFnArguments);
1471 UserVariables.clear();
1473 AbstractVariables.clear();
1474 LabelsBeforeInsn.clear();
1475 LabelsAfterInsn.clear();
1479 /// recordSourceLine - Register a source line with debug info. Returns the
1480 /// unique label that was emitted and which provides correspondence to
1481 /// the source line list.
1482 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1488 DIDescriptor Scope(S);
1490 if (Scope.isCompileUnit()) {
1491 DICompileUnit CU(S);
1492 Fn = CU.getFilename();
1493 Dir = CU.getDirectory();
1494 } else if (Scope.isFile()) {
1496 Fn = F.getFilename();
1497 Dir = F.getDirectory();
1498 } else if (Scope.isSubprogram()) {
1500 Fn = SP.getFilename();
1501 Dir = SP.getDirectory();
1502 } else if (Scope.isLexicalBlock()) {
1503 DILexicalBlock DB(S);
1504 Fn = DB.getFilename();
1505 Dir = DB.getDirectory();
1507 assert(0 && "Unexpected scope info");
1509 Src = GetOrCreateSourceID(Fn, Dir);
1511 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1514 //===----------------------------------------------------------------------===//
1516 //===----------------------------------------------------------------------===//
1518 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1521 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1522 // Get the children.
1523 const std::vector<DIE *> &Children = Die->getChildren();
1525 // If not last sibling and has children then add sibling offset attribute.
1526 if (!Last && !Children.empty())
1527 Die->addSiblingOffset(DIEValueAllocator);
1529 // Record the abbreviation.
1530 assignAbbrevNumber(Die->getAbbrev());
1532 // Get the abbreviation for this DIE.
1533 unsigned AbbrevNumber = Die->getAbbrevNumber();
1534 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1537 Die->setOffset(Offset);
1539 // Start the size with the size of abbreviation code.
1540 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1542 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1543 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1545 // Size the DIE attribute values.
1546 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1547 // Size attribute value.
1548 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1550 // Size the DIE children if any.
1551 if (!Children.empty()) {
1552 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1553 "Children flag not set");
1555 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1556 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1558 // End of children marker.
1559 Offset += sizeof(int8_t);
1562 Die->setSize(Offset - Die->getOffset());
1566 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1568 void DwarfDebug::computeSizeAndOffsets() {
1569 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1570 E = CUMap.end(); I != E; ++I) {
1571 // Compute size of compile unit header.
1573 sizeof(int32_t) + // Length of Compilation Unit Info
1574 sizeof(int16_t) + // DWARF version number
1575 sizeof(int32_t) + // Offset Into Abbrev. Section
1576 sizeof(int8_t); // Pointer Size (in bytes)
1577 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1581 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1582 /// temporary label to it if SymbolStem is specified.
1583 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1584 const char *SymbolStem = 0) {
1585 Asm->OutStreamer.SwitchSection(Section);
1586 if (!SymbolStem) return 0;
1588 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1589 Asm->OutStreamer.EmitLabel(TmpSym);
1593 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1594 /// the start of each one.
1595 void DwarfDebug::EmitSectionLabels() {
1596 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1598 // Dwarf sections base addresses.
1599 DwarfInfoSectionSym =
1600 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1601 DwarfAbbrevSectionSym =
1602 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1603 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1605 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1606 EmitSectionSym(Asm, MacroInfo);
1608 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1609 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1610 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1611 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1612 DwarfStrSectionSym =
1613 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1614 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1617 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1618 "section_debug_loc");
1620 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1621 EmitSectionSym(Asm, TLOF.getDataSection());
1624 /// emitDIE - Recursively emits a debug information entry.
1626 void DwarfDebug::emitDIE(DIE *Die) {
1627 // Get the abbreviation for this DIE.
1628 unsigned AbbrevNumber = Die->getAbbrevNumber();
1629 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1631 // Emit the code (index) for the abbreviation.
1632 if (Asm->isVerbose())
1633 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1634 Twine::utohexstr(Die->getOffset()) + ":0x" +
1635 Twine::utohexstr(Die->getSize()) + " " +
1636 dwarf::TagString(Abbrev->getTag()));
1637 Asm->EmitULEB128(AbbrevNumber);
1639 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1640 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1642 // Emit the DIE attribute values.
1643 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1644 unsigned Attr = AbbrevData[i].getAttribute();
1645 unsigned Form = AbbrevData[i].getForm();
1646 assert(Form && "Too many attributes for DIE (check abbreviation)");
1648 if (Asm->isVerbose())
1649 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1652 case dwarf::DW_AT_sibling:
1653 Asm->EmitInt32(Die->getSiblingOffset());
1655 case dwarf::DW_AT_abstract_origin: {
1656 DIEEntry *E = cast<DIEEntry>(Values[i]);
1657 DIE *Origin = E->getEntry();
1658 unsigned Addr = Origin->getOffset();
1659 Asm->EmitInt32(Addr);
1662 case dwarf::DW_AT_ranges: {
1663 // DW_AT_range Value encodes offset in debug_range section.
1664 DIEInteger *V = cast<DIEInteger>(Values[i]);
1666 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1667 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1671 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1673 DwarfDebugRangeSectionSym,
1678 case dwarf::DW_AT_location: {
1679 if (UseDotDebugLocEntry.count(Die) != 0) {
1680 DIELabel *L = cast<DIELabel>(Values[i]);
1681 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1683 Values[i]->EmitValue(Asm, Form);
1686 case dwarf::DW_AT_accessibility: {
1687 if (Asm->isVerbose()) {
1688 DIEInteger *V = cast<DIEInteger>(Values[i]);
1689 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1691 Values[i]->EmitValue(Asm, Form);
1695 // Emit an attribute using the defined form.
1696 Values[i]->EmitValue(Asm, Form);
1701 // Emit the DIE children if any.
1702 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1703 const std::vector<DIE *> &Children = Die->getChildren();
1705 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1706 emitDIE(Children[j]);
1708 if (Asm->isVerbose())
1709 Asm->OutStreamer.AddComment("End Of Children Mark");
1714 /// emitDebugInfo - Emit the debug info section.
1716 void DwarfDebug::emitDebugInfo() {
1717 // Start debug info section.
1718 Asm->OutStreamer.SwitchSection(
1719 Asm->getObjFileLowering().getDwarfInfoSection());
1720 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1721 E = CUMap.end(); I != E; ++I) {
1722 CompileUnit *TheCU = I->second;
1723 DIE *Die = TheCU->getCUDie();
1725 // Emit the compile units header.
1726 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1729 // Emit size of content not including length itself
1730 unsigned ContentSize = Die->getSize() +
1731 sizeof(int16_t) + // DWARF version number
1732 sizeof(int32_t) + // Offset Into Abbrev. Section
1733 sizeof(int8_t); // Pointer Size (in bytes)
1735 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1736 Asm->EmitInt32(ContentSize);
1737 Asm->OutStreamer.AddComment("DWARF version number");
1738 Asm->EmitInt16(dwarf::DWARF_VERSION);
1739 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1740 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1741 DwarfAbbrevSectionSym);
1742 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1743 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1746 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1750 /// emitAbbreviations - Emit the abbreviation section.
1752 void DwarfDebug::emitAbbreviations() const {
1753 // Check to see if it is worth the effort.
1754 if (!Abbreviations.empty()) {
1755 // Start the debug abbrev section.
1756 Asm->OutStreamer.SwitchSection(
1757 Asm->getObjFileLowering().getDwarfAbbrevSection());
1759 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1761 // For each abbrevation.
1762 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1763 // Get abbreviation data
1764 const DIEAbbrev *Abbrev = Abbreviations[i];
1766 // Emit the abbrevations code (base 1 index.)
1767 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1769 // Emit the abbreviations data.
1773 // Mark end of abbreviations.
1774 Asm->EmitULEB128(0, "EOM(3)");
1776 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1780 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1781 /// the line matrix.
1783 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1784 // Define last address of section.
1785 Asm->OutStreamer.AddComment("Extended Op");
1788 Asm->OutStreamer.AddComment("Op size");
1789 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1790 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1791 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1793 Asm->OutStreamer.AddComment("Section end label");
1795 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1796 Asm->getTargetData().getPointerSize(),
1799 // Mark end of matrix.
1800 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1806 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1808 void DwarfDebug::emitDebugPubNames() {
1809 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1810 E = CUMap.end(); I != E; ++I) {
1811 CompileUnit *TheCU = I->second;
1812 // Start the dwarf pubnames section.
1813 Asm->OutStreamer.SwitchSection(
1814 Asm->getObjFileLowering().getDwarfPubNamesSection());
1816 Asm->OutStreamer.AddComment("Length of Public Names Info");
1817 Asm->EmitLabelDifference(
1818 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1819 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1821 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1824 Asm->OutStreamer.AddComment("DWARF Version");
1825 Asm->EmitInt16(dwarf::DWARF_VERSION);
1827 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1828 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1829 DwarfInfoSectionSym);
1831 Asm->OutStreamer.AddComment("Compilation Unit Length");
1832 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1833 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1836 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1837 for (StringMap<DIE*>::const_iterator
1838 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1839 const char *Name = GI->getKeyData();
1840 DIE *Entity = GI->second;
1842 Asm->OutStreamer.AddComment("DIE offset");
1843 Asm->EmitInt32(Entity->getOffset());
1845 if (Asm->isVerbose())
1846 Asm->OutStreamer.AddComment("External Name");
1847 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1850 Asm->OutStreamer.AddComment("End Mark");
1852 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1857 void DwarfDebug::emitDebugPubTypes() {
1858 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1859 E = CUMap.end(); I != E; ++I) {
1860 CompileUnit *TheCU = I->second;
1861 // Start the dwarf pubnames section.
1862 Asm->OutStreamer.SwitchSection(
1863 Asm->getObjFileLowering().getDwarfPubTypesSection());
1864 Asm->OutStreamer.AddComment("Length of Public Types Info");
1865 Asm->EmitLabelDifference(
1866 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1867 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1869 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1872 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1873 Asm->EmitInt16(dwarf::DWARF_VERSION);
1875 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1876 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1877 DwarfInfoSectionSym);
1879 Asm->OutStreamer.AddComment("Compilation Unit Length");
1880 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1881 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1884 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1885 for (StringMap<DIE*>::const_iterator
1886 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1887 const char *Name = GI->getKeyData();
1888 DIE *Entity = GI->second;
1890 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1891 Asm->EmitInt32(Entity->getOffset());
1893 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1894 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1897 Asm->OutStreamer.AddComment("End Mark");
1899 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1904 /// emitDebugStr - Emit visible names into a debug str section.
1906 void DwarfDebug::emitDebugStr() {
1907 // Check to see if it is worth the effort.
1908 if (StringPool.empty()) return;
1910 // Start the dwarf str section.
1911 Asm->OutStreamer.SwitchSection(
1912 Asm->getObjFileLowering().getDwarfStrSection());
1914 // Get all of the string pool entries and put them in an array by their ID so
1915 // we can sort them.
1916 SmallVector<std::pair<unsigned,
1917 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1919 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1920 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1921 Entries.push_back(std::make_pair(I->second.second, &*I));
1923 array_pod_sort(Entries.begin(), Entries.end());
1925 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1926 // Emit a label for reference from debug information entries.
1927 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1929 // Emit the string itself.
1930 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1934 /// emitDebugLoc - Emit visible names into a debug loc section.
1936 void DwarfDebug::emitDebugLoc() {
1937 if (DotDebugLocEntries.empty())
1940 for (SmallVector<DotDebugLocEntry, 4>::iterator
1941 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1943 DotDebugLocEntry &Entry = *I;
1944 if (I + 1 != DotDebugLocEntries.end())
1948 // Start the dwarf loc section.
1949 Asm->OutStreamer.SwitchSection(
1950 Asm->getObjFileLowering().getDwarfLocSection());
1951 unsigned char Size = Asm->getTargetData().getPointerSize();
1952 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1954 for (SmallVector<DotDebugLocEntry, 4>::iterator
1955 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1956 I != E; ++I, ++index) {
1957 DotDebugLocEntry &Entry = *I;
1958 if (Entry.isMerged()) continue;
1959 if (Entry.isEmpty()) {
1960 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1961 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1962 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1964 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1965 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1966 DIVariable DV(Entry.Variable);
1967 Asm->OutStreamer.AddComment("Loc expr size");
1968 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1969 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1970 Asm->EmitLabelDifference(end, begin, 2);
1971 Asm->OutStreamer.EmitLabel(begin);
1972 if (Entry.isInt()) {
1973 DIBasicType BTy(DV.getType());
1975 (BTy.getEncoding() == dwarf::DW_ATE_signed
1976 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1977 Asm->OutStreamer.AddComment("DW_OP_consts");
1978 Asm->EmitInt8(dwarf::DW_OP_consts);
1979 Asm->EmitSLEB128(Entry.getInt());
1981 Asm->OutStreamer.AddComment("DW_OP_constu");
1982 Asm->EmitInt8(dwarf::DW_OP_constu);
1983 Asm->EmitULEB128(Entry.getInt());
1985 } else if (Entry.isLocation()) {
1986 if (!DV.hasComplexAddress())
1988 Asm->EmitDwarfRegOp(Entry.Loc);
1990 // Complex address entry.
1991 unsigned N = DV.getNumAddrElements();
1993 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1994 if (Entry.Loc.getOffset()) {
1996 Asm->EmitDwarfRegOp(Entry.Loc);
1997 Asm->OutStreamer.AddComment("DW_OP_deref");
1998 Asm->EmitInt8(dwarf::DW_OP_deref);
1999 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2000 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2001 Asm->EmitSLEB128(DV.getAddrElement(1));
2003 // If first address element is OpPlus then emit
2004 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2005 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2006 Asm->EmitDwarfRegOp(Loc);
2010 Asm->EmitDwarfRegOp(Entry.Loc);
2013 // Emit remaining complex address elements.
2014 for (; i < N; ++i) {
2015 uint64_t Element = DV.getAddrElement(i);
2016 if (Element == DIBuilder::OpPlus) {
2017 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2018 Asm->EmitULEB128(DV.getAddrElement(++i));
2019 } else if (Element == DIBuilder::OpDeref)
2020 Asm->EmitInt8(dwarf::DW_OP_deref);
2021 else llvm_unreachable("unknown Opcode found in complex address");
2025 // else ... ignore constant fp. There is not any good way to
2026 // to represent them here in dwarf.
2027 Asm->OutStreamer.EmitLabel(end);
2032 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2034 void DwarfDebug::EmitDebugARanges() {
2035 // Start the dwarf aranges section.
2036 Asm->OutStreamer.SwitchSection(
2037 Asm->getObjFileLowering().getDwarfARangesSection());
2040 /// emitDebugRanges - Emit visible names into a debug ranges section.
2042 void DwarfDebug::emitDebugRanges() {
2043 // Start the dwarf ranges section.
2044 Asm->OutStreamer.SwitchSection(
2045 Asm->getObjFileLowering().getDwarfRangesSection());
2046 unsigned char Size = Asm->getTargetData().getPointerSize();
2047 for (SmallVector<const MCSymbol *, 8>::iterator
2048 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2051 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2053 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2057 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2059 void DwarfDebug::emitDebugMacInfo() {
2060 if (const MCSection *LineInfo =
2061 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2062 // Start the dwarf macinfo section.
2063 Asm->OutStreamer.SwitchSection(LineInfo);
2067 /// emitDebugInlineInfo - Emit inline info using following format.
2069 /// 1. length of section
2070 /// 2. Dwarf version number
2071 /// 3. address size.
2073 /// Entries (one "entry" for each function that was inlined):
2075 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2076 /// otherwise offset into __debug_str for regular function name.
2077 /// 2. offset into __debug_str section for regular function name.
2078 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2079 /// instances for the function.
2081 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2082 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2083 /// __debug_info section, and the low_pc is the starting address for the
2084 /// inlining instance.
2085 void DwarfDebug::emitDebugInlineInfo() {
2086 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2092 Asm->OutStreamer.SwitchSection(
2093 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2095 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2096 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2097 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2099 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2101 Asm->OutStreamer.AddComment("Dwarf Version");
2102 Asm->EmitInt16(dwarf::DWARF_VERSION);
2103 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2104 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2106 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2107 E = InlinedSPNodes.end(); I != E; ++I) {
2109 const MDNode *Node = *I;
2110 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2111 = InlineInfo.find(Node);
2112 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2113 DISubprogram SP(Node);
2114 StringRef LName = SP.getLinkageName();
2115 StringRef Name = SP.getName();
2117 Asm->OutStreamer.AddComment("MIPS linkage name");
2118 if (LName.empty()) {
2119 Asm->OutStreamer.EmitBytes(Name, 0);
2120 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2122 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2123 DwarfStrSectionSym);
2125 Asm->OutStreamer.AddComment("Function name");
2126 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2127 Asm->EmitULEB128(Labels.size(), "Inline count");
2129 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2130 LE = Labels.end(); LI != LE; ++LI) {
2131 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2132 Asm->EmitInt32(LI->second->getOffset());
2134 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2135 Asm->OutStreamer.EmitSymbolValue(LI->first,
2136 Asm->getTargetData().getPointerSize(),0);
2140 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));