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());
387 DenseMap<const DbgVariable *, const DbgVariable *>::iterator
388 V2AVI = VarToAbstractVarMap.find(DV);
389 if (V2AVI != VarToAbstractVarMap.end())
390 AbsDIE = V2AVI->second->getDIE();
393 VariableCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
394 dwarf::DW_FORM_ref4, AbsDIE);
396 VariableCU->addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
398 VariableCU->addSourceLine(VariableDie, DV->getVariable());
400 // Add variable type.
401 VariableCU->addType(VariableDie, DV->getType());
404 if (DV->isArtificial())
405 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
406 dwarf::DW_FORM_flag, 1);
408 if (Scope->isAbstractScope()) {
409 DV->setDIE(VariableDie);
413 // Add variable address.
415 unsigned Offset = DV->getDotDebugLocOffset();
417 VariableCU->addLabel(VariableDie, dwarf::DW_AT_location,
418 dwarf::DW_FORM_data4,
419 Asm->GetTempSymbol("debug_loc", Offset));
420 DV->setDIE(VariableDie);
421 UseDotDebugLocEntry.insert(VariableDie);
425 // Check if variable is described by a DBG_VALUE instruction.
426 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
427 DbgVariableToDbgInstMap.find(DV);
428 if (DVI != DbgVariableToDbgInstMap.end()) {
429 const MachineInstr *DVInsn = DVI->second;
430 bool updated = false;
431 if (DVInsn->getNumOperands() == 3) {
432 if (DVInsn->getOperand(0).isReg()) {
433 const MachineOperand RegOp = DVInsn->getOperand(0);
434 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
435 if (DVInsn->getOperand(1).isImm() &&
436 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
437 unsigned FrameReg = 0;
438 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
440 TFI->getFrameIndexReference(*Asm->MF,
441 DVInsn->getOperand(1).getImm(),
443 MachineLocation Location(FrameReg, Offset);
444 VariableCU->addVariableAddress(DV, VariableDie, Location);
446 } else if (RegOp.getReg())
447 VariableCU->addVariableAddress(DV, VariableDie,
448 MachineLocation(RegOp.getReg()));
451 else if (DVInsn->getOperand(0).isImm())
453 VariableCU->addConstantValue(VariableDie, DVInsn->getOperand(0),
455 else if (DVInsn->getOperand(0).isFPImm())
457 VariableCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
458 else if (DVInsn->getOperand(0).isCImm())
460 VariableCU->addConstantValue(VariableDie,
461 DVInsn->getOperand(0).getCImm(),
462 DV->getType().isUnsignedDIType());
464 VariableCU->addVariableAddress(DV, VariableDie,
465 Asm->getDebugValueLocation(DVInsn));
469 // If variableDie is not updated then DBG_VALUE instruction does not
470 // have valid variable info.
474 DV->setDIE(VariableDie);
478 // .. else use frame index, if available.
480 if (findVariableFrameIndex(DV, &FI)) {
481 unsigned FrameReg = 0;
482 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
484 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
485 MachineLocation Location(FrameReg, Offset);
486 VariableCU->addVariableAddress(DV, VariableDie, Location);
489 DV->setDIE(VariableDie);
494 /// constructScopeDIE - Construct a DIE for this scope.
495 DIE *DwarfDebug::constructScopeDIE(LexicalScope *Scope) {
496 if (!Scope || !Scope->getScopeNode())
499 SmallVector <DIE *, 8> Children;
501 // Collect arguments for current function.
502 if (LScopes.isCurrentFunctionScope(Scope))
503 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
504 if (DbgVariable *ArgDV = CurrentFnArguments[i])
505 if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
506 Children.push_back(Arg);
508 // Collect lexical scope childrens first.
509 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
510 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
511 if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
512 Children.push_back(Variable);
513 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
514 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
515 if (DIE *Nested = constructScopeDIE(Scopes[j]))
516 Children.push_back(Nested);
517 DIScope DS(Scope->getScopeNode());
518 DIE *ScopeDIE = NULL;
519 if (Scope->getInlinedAt())
520 ScopeDIE = constructInlinedScopeDIE(Scope);
521 else if (DS.isSubprogram()) {
522 ProcessedSPNodes.insert(DS);
523 if (Scope->isAbstractScope()) {
524 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
525 // Note down abstract DIE.
527 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
530 ScopeDIE = updateSubprogramScopeDIE(DS);
533 // There is no need to emit empty lexical block DIE.
534 if (Children.empty())
536 ScopeDIE = constructLexicalScopeDIE(Scope);
539 if (!ScopeDIE) return NULL;
542 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
543 E = Children.end(); I != E; ++I)
544 ScopeDIE->addChild(*I);
546 if (DS.isSubprogram())
547 getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
552 /// GetOrCreateSourceID - Look up the source id with the given directory and
553 /// source file names. If none currently exists, create a new id and insert it
554 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
557 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
559 // If FE did not provide a file name, then assume stdin.
560 if (FileName.empty())
561 return GetOrCreateSourceID("<stdin>", StringRef());
563 // MCStream expects full path name as filename.
564 if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
565 SmallString<128> FullPathName = DirName;
566 sys::path::append(FullPathName, FileName);
567 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
568 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
571 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
572 if (Entry.getValue())
573 return Entry.getValue();
575 unsigned SrcId = SourceIdMap.size();
576 Entry.setValue(SrcId);
578 // Print out a .file directive to specify files for .loc directives.
579 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
584 /// constructCompileUnit - Create new CompileUnit for the given
585 /// metadata node with tag DW_TAG_compile_unit.
586 void DwarfDebug::constructCompileUnit(const MDNode *N) {
587 DICompileUnit DIUnit(N);
588 StringRef FN = DIUnit.getFilename();
589 StringRef Dir = DIUnit.getDirectory();
590 unsigned ID = GetOrCreateSourceID(FN, Dir);
592 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
593 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
594 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
595 DIUnit.getProducer());
596 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
597 DIUnit.getLanguage());
598 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
599 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
600 // simplifies debug range entries.
601 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
602 // DW_AT_stmt_list is a offset of line number information for this
603 // compile unit in debug_line section.
604 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
605 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
606 Asm->GetTempSymbol("section_line"));
608 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
611 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
612 if (DIUnit.isOptimized())
613 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
615 StringRef Flags = DIUnit.getFlags();
617 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,
620 unsigned RVer = DIUnit.getRunTimeVersion();
622 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
623 dwarf::DW_FORM_data1, RVer);
627 CUMap.insert(std::make_pair(N, NewCU));
630 /// getCompileUnit - Get CompileUnit DIE.
631 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
632 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
634 const MDNode *CUNode = NULL;
635 if (D.isCompileUnit())
637 else if (D.isSubprogram())
638 CUNode = DISubprogram(N).getCompileUnit();
640 CUNode = DIType(N).getCompileUnit();
641 else if (D.isGlobalVariable())
642 CUNode = DIGlobalVariable(N).getCompileUnit();
643 else if (D.isVariable())
644 CUNode = DIVariable(N).getCompileUnit();
645 else if (D.isNameSpace())
646 CUNode = DINameSpace(N).getCompileUnit();
648 CUNode = DIFile(N).getCompileUnit();
652 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
653 = CUMap.find(CUNode);
654 if (I == CUMap.end())
659 /// constructGlobalVariableDIE - Construct global variable DIE.
660 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
661 DIGlobalVariable GV(N);
663 // If debug information is malformed then ignore it.
664 if (GV.Verify() == false)
667 // Check for pre-existence.
668 CompileUnit *TheCU = getCompileUnit(N);
669 TheCU->createGlobalVariableDIE(N);
673 /// construct SubprogramDIE - Construct subprogram DIE.
674 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
677 // Check for pre-existence.
678 CompileUnit *TheCU = getCompileUnit(N);
679 if (TheCU->getDIE(N))
682 if (!SP.isDefinition())
683 // This is a method declaration which will be handled while constructing
687 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
690 TheCU->insertDIE(N, SubprogramDie);
692 // Add to context owner.
693 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
696 TheCU->addGlobal(SP.getName(), SubprogramDie);
701 /// beginModule - Emit all Dwarf sections that should come prior to the
702 /// content. Create global DIEs and emit initial debug info sections.
703 /// This is invoked by the target AsmPrinter.
704 void DwarfDebug::beginModule(Module *M) {
705 if (DisableDebugInfoPrinting)
708 // If module has named metadata anchors then use them, otherwise scan the
709 // module using debug info finder to collect debug info.
710 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
713 NamedMDNode *GV_Nodes = M->getNamedMetadata("llvm.dbg.gv");
714 NamedMDNode *SP_Nodes = M->getNamedMetadata("llvm.dbg.sp");
715 if (!GV_Nodes && !SP_Nodes)
716 // If there are not any global variables or any functions then
717 // there is not any debug info in this module.
720 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i)
721 constructCompileUnit(CU_Nodes->getOperand(i));
724 for (unsigned i = 0, e = GV_Nodes->getNumOperands(); i != e; ++i)
725 constructGlobalVariableDIE(GV_Nodes->getOperand(i));
728 for (unsigned i = 0, e = SP_Nodes->getNumOperands(); i != e; ++i)
729 constructSubprogramDIE(SP_Nodes->getOperand(i));
733 DebugInfoFinder DbgFinder;
734 DbgFinder.processModule(*M);
736 bool HasDebugInfo = false;
737 // Scan all the compile-units to see if there are any marked as the main
738 // unit. If not, we do not generate debug info.
739 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
740 E = DbgFinder.compile_unit_end(); I != E; ++I) {
741 if (DICompileUnit(*I).isMain()) {
746 if (!HasDebugInfo) return;
748 // Create all the compile unit DIEs.
749 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
750 E = DbgFinder.compile_unit_end(); I != E; ++I)
751 constructCompileUnit(*I);
753 // Create DIEs for each global variable.
754 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
755 E = DbgFinder.global_variable_end(); I != E; ++I)
756 constructGlobalVariableDIE(*I);
758 // Create DIEs for each subprogram.
759 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
760 E = DbgFinder.subprogram_end(); I != E; ++I)
761 constructSubprogramDIE(*I);
764 // Tell MMI that we have debug info.
765 MMI->setDebugInfoAvailability(true);
767 // Emit initial sections.
771 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
772 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
773 DIType Ty(NMD->getOperand(i));
774 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
777 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
778 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
779 DIType Ty(NMD->getOperand(i));
780 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
783 // Prime section data.
784 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
787 /// endModule - Emit all Dwarf sections that should come after the content.
789 void DwarfDebug::endModule() {
790 if (!FirstCU) return;
791 const Module *M = MMI->getModule();
792 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
793 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
794 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
795 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
796 DISubprogram SP(AllSPs->getOperand(SI));
797 if (!SP.Verify()) continue;
799 // Collect info for variables that were optimized out.
800 if (!SP.isDefinition()) continue;
801 StringRef FName = SP.getLinkageName();
803 FName = SP.getName();
804 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
806 unsigned E = NMD->getNumOperands();
808 LexicalScope *Scope = new LexicalScope(NULL, DIDescriptor(SP), NULL,
810 DeadFnScopeMap[SP] = Scope;
811 SmallVector<DbgVariable, 8> Variables;
812 for (unsigned I = 0; I != E; ++I) {
813 DIVariable DV(NMD->getOperand(I));
814 if (!DV.Verify()) continue;
815 Variables.push_back(DbgVariable(DV));
818 // Construct subprogram DIE and add variables DIEs.
819 constructSubprogramDIE(SP);
820 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
821 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
822 if (DIE *VariableDIE = constructVariableDIE(&Variables[i], Scope))
823 ScopeDIE->addChild(VariableDIE);
828 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
829 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
830 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
832 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
835 // Emit DW_AT_containing_type attribute to connect types with their
836 // vtable holding type.
837 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
838 CUE = CUMap.end(); CUI != CUE; ++CUI) {
839 CompileUnit *TheCU = CUI->second;
840 TheCU->constructContainingTypeDIEs();
843 // Standard sections final addresses.
844 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
845 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
846 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
847 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
849 // End text sections.
850 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
851 Asm->OutStreamer.SwitchSection(SectionMap[i]);
852 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
855 // Compute DIE offsets and sizes.
856 computeSizeAndOffsets();
858 // Emit all the DIEs into a debug info section
861 // Corresponding abbreviations into a abbrev section.
864 // Emit info into a debug pubnames section.
867 // Emit info into a debug pubtypes section.
870 // Emit info into a debug loc section.
873 // Emit info into a debug aranges section.
876 // Emit info into a debug ranges section.
879 // Emit info into a debug macinfo section.
883 emitDebugInlineInfo();
885 // Emit info into a debug str section.
889 DeleteContainerSeconds(DeadFnScopeMap);
890 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
891 E = CUMap.end(); I != E; ++I)
893 FirstCU = NULL; // Reset for the next Module, if any.
896 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
897 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
899 LLVMContext &Ctx = DV->getContext();
900 // More then one inlined variable corresponds to one abstract variable.
901 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
902 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
904 return AbsDbgVariable;
906 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
910 AbsDbgVariable = new DbgVariable(Var);
911 addScopeVariable(Scope, AbsDbgVariable);
912 AbstractVariables[Var] = AbsDbgVariable;
913 return AbsDbgVariable;
916 /// addCurrentFnArgument - If Var is a current function argument then add
917 /// it to CurrentFnArguments list.
918 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
919 DbgVariable *Var, LexicalScope *Scope) {
920 if (!LScopes.isCurrentFunctionScope(Scope))
922 DIVariable DV = Var->getVariable();
923 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
925 unsigned ArgNo = DV.getArgNumber();
929 size_t Size = CurrentFnArguments.size();
931 CurrentFnArguments.resize(MF->getFunction()->arg_size());
932 // llvm::Function argument size is not good indicator of how many
933 // arguments does the function have at source level.
935 CurrentFnArguments.resize(ArgNo * 2);
936 CurrentFnArguments[ArgNo - 1] = Var;
940 /// collectVariableInfoFromMMITable - Collect variable information from
941 /// side table maintained by MMI.
943 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
944 SmallPtrSet<const MDNode *, 16> &Processed) {
945 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
946 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
947 VE = VMap.end(); VI != VE; ++VI) {
948 const MDNode *Var = VI->first;
950 Processed.insert(Var);
952 const std::pair<unsigned, DebugLoc> &VP = VI->second;
954 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
956 // If variable scope is not found then skip this variable.
960 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
961 DbgVariable *RegVar = new DbgVariable(DV);
962 recordVariableFrameIndex(RegVar, VP.first);
963 if (!addCurrentFnArgument(MF, RegVar, Scope))
964 addScopeVariable(Scope, RegVar);
965 if (AbsDbgVariable) {
966 recordVariableFrameIndex(AbsDbgVariable, VP.first);
967 VarToAbstractVarMap[RegVar] = AbsDbgVariable;
972 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
973 /// DBG_VALUE instruction, is in a defined reg.
974 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
975 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
976 return MI->getNumOperands() == 3 &&
977 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
978 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
981 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
983 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
984 const MCSymbol *FLabel,
985 const MCSymbol *SLabel,
986 const MachineInstr *MI) {
987 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
989 if (MI->getNumOperands() != 3) {
990 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
991 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
993 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
994 MachineLocation MLoc;
995 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
996 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
998 if (MI->getOperand(0).isImm())
999 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1000 if (MI->getOperand(0).isFPImm())
1001 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1002 if (MI->getOperand(0).isCImm())
1003 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1005 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
1006 return DotDebugLocEntry();
1009 /// collectVariableInfo - Find variables for each lexical scope.
1011 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1012 SmallPtrSet<const MDNode *, 16> &Processed) {
1014 /// collection info from MMI table.
1015 collectVariableInfoFromMMITable(MF, Processed);
1017 for (SmallVectorImpl<const MDNode*>::const_iterator
1018 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1020 const MDNode *Var = *UVI;
1021 if (Processed.count(Var))
1024 // History contains relevant DBG_VALUE instructions for Var and instructions
1026 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1027 if (History.empty())
1029 const MachineInstr *MInsn = History.front();
1032 LexicalScope *Scope = NULL;
1033 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1034 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1035 Scope = LScopes.getCurrentFunctionScope();
1037 if (DV.getVersion() <= LLVMDebugVersion9)
1038 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1040 if (MDNode *IA = DV.getInlinedAt())
1041 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1043 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1046 // If variable scope is not found then skip this variable.
1050 Processed.insert(DV);
1051 assert(MInsn->isDebugValue() && "History must begin with debug value");
1052 DbgVariable *RegVar = new DbgVariable(DV);
1053 if (!addCurrentFnArgument(MF, RegVar, Scope))
1054 addScopeVariable(Scope, RegVar);
1055 if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
1056 DbgVariableToDbgInstMap[AbsVar] = MInsn;
1057 VarToAbstractVarMap[RegVar] = AbsVar;
1060 // Simple ranges that are fully coalesced.
1061 if (History.size() <= 1 || (History.size() == 2 &&
1062 MInsn->isIdenticalTo(History.back()))) {
1063 DbgVariableToDbgInstMap[RegVar] = MInsn;
1067 // handle multiple DBG_VALUE instructions describing one variable.
1068 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1070 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1071 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1072 const MachineInstr *Begin = *HI;
1073 assert(Begin->isDebugValue() && "Invalid History entry");
1075 // Check if DBG_VALUE is truncating a range.
1076 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1077 && !Begin->getOperand(0).getReg())
1080 // Compute the range for a register location.
1081 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1082 const MCSymbol *SLabel = 0;
1085 // If Begin is the last instruction in History then its value is valid
1086 // until the end of the function.
1087 SLabel = FunctionEndSym;
1089 const MachineInstr *End = HI[1];
1090 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1091 << "\t" << *Begin << "\t" << *End << "\n");
1092 if (End->isDebugValue())
1093 SLabel = getLabelBeforeInsn(End);
1095 // End is a normal instruction clobbering the range.
1096 SLabel = getLabelAfterInsn(End);
1097 assert(SLabel && "Forgot label after clobber instruction");
1102 // The value is valid until the next DBG_VALUE or clobber.
1103 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1105 DotDebugLocEntries.push_back(DotDebugLocEntry());
1108 // Collect info for variables that were optimized out.
1109 const Function *F = MF->getFunction();
1110 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1111 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1112 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1113 if (!DV || !Processed.insert(DV))
1115 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1116 addScopeVariable(Scope, new DbgVariable(DV));
1121 /// getLabelBeforeInsn - Return Label preceding the instruction.
1122 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1123 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1124 assert(Label && "Didn't insert label before instruction");
1128 /// getLabelAfterInsn - Return Label immediately following the instruction.
1129 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1130 return LabelsAfterInsn.lookup(MI);
1133 /// beginInstruction - Process beginning of an instruction.
1134 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1135 // Check if source location changes, but ignore DBG_VALUE locations.
1136 if (!MI->isDebugValue()) {
1137 DebugLoc DL = MI->getDebugLoc();
1138 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1139 unsigned Flags = DWARF2_FLAG_IS_STMT;
1141 if (DL == PrologEndLoc) {
1142 Flags |= DWARF2_FLAG_PROLOGUE_END;
1143 PrologEndLoc = DebugLoc();
1145 if (!DL.isUnknown()) {
1146 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1147 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1149 recordSourceLine(0, 0, 0, 0);
1153 // Insert labels where requested.
1154 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1155 LabelsBeforeInsn.find(MI);
1158 if (I == LabelsBeforeInsn.end())
1161 // Label already assigned.
1166 PrevLabel = MMI->getContext().CreateTempSymbol();
1167 Asm->OutStreamer.EmitLabel(PrevLabel);
1169 I->second = PrevLabel;
1172 /// endInstruction - Process end of an instruction.
1173 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1174 // Don't create a new label after DBG_VALUE instructions.
1175 // They don't generate code.
1176 if (!MI->isDebugValue())
1179 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1180 LabelsAfterInsn.find(MI);
1183 if (I == LabelsAfterInsn.end())
1186 // Label already assigned.
1190 // We need a label after this instruction.
1192 PrevLabel = MMI->getContext().CreateTempSymbol();
1193 Asm->OutStreamer.EmitLabel(PrevLabel);
1195 I->second = PrevLabel;
1198 /// identifyScopeMarkers() -
1199 /// Each LexicalScope has first instruction and last instruction to mark
1200 /// beginning and end of a scope respectively. Create an inverse map that list
1201 /// scopes starts (and ends) with an instruction. One instruction may start (or
1202 /// end) multiple scopes. Ignore scopes that are not reachable.
1203 void DwarfDebug::identifyScopeMarkers() {
1204 SmallVector<LexicalScope *, 4> WorkList;
1205 WorkList.push_back(LScopes.getCurrentFunctionScope());
1206 while (!WorkList.empty()) {
1207 LexicalScope *S = WorkList.pop_back_val();
1209 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1210 if (!Children.empty())
1211 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1212 SE = Children.end(); SI != SE; ++SI)
1213 WorkList.push_back(*SI);
1215 if (S->isAbstractScope())
1218 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1221 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1222 RE = Ranges.end(); RI != RE; ++RI) {
1223 assert(RI->first && "InsnRange does not have first instruction!");
1224 assert(RI->second && "InsnRange does not have second instruction!");
1225 requestLabelBeforeInsn(RI->first);
1226 requestLabelAfterInsn(RI->second);
1231 /// getScopeNode - Get MDNode for DebugLoc's scope.
1232 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1233 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1234 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1235 return DL.getScope(Ctx);
1238 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1239 /// line number info for the function.
1240 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1241 const MDNode *Scope = getScopeNode(DL, Ctx);
1242 DISubprogram SP = getDISubprogram(Scope);
1244 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1248 /// beginFunction - Gather pre-function debug information. Assumes being
1249 /// emitted immediately after the function entry point.
1250 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1251 if (!MMI->hasDebugInfo()) return;
1252 LScopes.initialize(*MF);
1253 if (LScopes.empty()) return;
1254 identifyScopeMarkers();
1256 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1257 Asm->getFunctionNumber());
1258 // Assumes in correct section after the entry point.
1259 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1261 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1263 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1264 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1265 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1267 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1269 bool AtBlockEntry = true;
1270 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1272 const MachineInstr *MI = II;
1274 if (MI->isDebugValue()) {
1275 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1277 // Keep track of user variables.
1279 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1281 // Variable is in a register, we need to check for clobbers.
1282 if (isDbgValueInDefinedReg(MI))
1283 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1285 // Check the history of this variable.
1286 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1287 if (History.empty()) {
1288 UserVariables.push_back(Var);
1289 // The first mention of a function argument gets the FunctionBeginSym
1290 // label, so arguments are visible when breaking at function entry.
1292 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1293 DISubprogram(getDISubprogram(DV.getContext()))
1294 .describes(MF->getFunction()))
1295 LabelsBeforeInsn[MI] = FunctionBeginSym;
1297 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1298 const MachineInstr *Prev = History.back();
1299 if (Prev->isDebugValue()) {
1300 // Coalesce identical entries at the end of History.
1301 if (History.size() >= 2 &&
1302 Prev->isIdenticalTo(History[History.size() - 2])) {
1303 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1305 << "\t" << *History[History.size() - 2] << "\n");
1309 // Terminate old register assignments that don't reach MI;
1310 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1311 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1312 isDbgValueInDefinedReg(Prev)) {
1313 // Previous register assignment needs to terminate at the end of
1315 MachineBasicBlock::const_iterator LastMI =
1316 PrevMBB->getLastNonDebugInstr();
1317 if (LastMI == PrevMBB->end()) {
1318 // Drop DBG_VALUE for empty range.
1319 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1320 << "\t" << *Prev << "\n");
1324 // Terminate after LastMI.
1325 History.push_back(LastMI);
1330 History.push_back(MI);
1332 // Not a DBG_VALUE instruction.
1334 AtBlockEntry = false;
1336 // First known non DBG_VALUE location marks beginning of function
1338 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1339 PrologEndLoc = MI->getDebugLoc();
1341 // Check if the instruction clobbers any registers with debug vars.
1342 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1343 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1344 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1346 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1347 unsigned Reg = *AI; ++AI) {
1348 const MDNode *Var = LiveUserVar[Reg];
1351 // Reg is now clobbered.
1352 LiveUserVar[Reg] = 0;
1354 // Was MD last defined by a DBG_VALUE referring to Reg?
1355 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1356 if (HistI == DbgValues.end())
1358 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1359 if (History.empty())
1361 const MachineInstr *Prev = History.back();
1362 // Sanity-check: Register assignments are terminated at the end of
1364 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1366 // Is the variable still in Reg?
1367 if (!isDbgValueInDefinedReg(Prev) ||
1368 Prev->getOperand(0).getReg() != Reg)
1370 // Var is clobbered. Make sure the next instruction gets a label.
1371 History.push_back(MI);
1378 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1380 SmallVectorImpl<const MachineInstr*> &History = I->second;
1381 if (History.empty())
1384 // Make sure the final register assignments are terminated.
1385 const MachineInstr *Prev = History.back();
1386 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1387 const MachineBasicBlock *PrevMBB = Prev->getParent();
1388 MachineBasicBlock::const_iterator LastMI =
1389 PrevMBB->getLastNonDebugInstr();
1390 if (LastMI == PrevMBB->end())
1391 // Drop DBG_VALUE for empty range.
1394 // Terminate after LastMI.
1395 History.push_back(LastMI);
1398 // Request labels for the full history.
1399 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1400 const MachineInstr *MI = History[i];
1401 if (MI->isDebugValue())
1402 requestLabelBeforeInsn(MI);
1404 requestLabelAfterInsn(MI);
1408 PrevInstLoc = DebugLoc();
1409 PrevLabel = FunctionBeginSym;
1411 // Record beginning of function.
1412 if (!PrologEndLoc.isUnknown()) {
1413 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1414 MF->getFunction()->getContext());
1415 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1416 FnStartDL.getScope(MF->getFunction()->getContext()),
1417 DWARF2_FLAG_IS_STMT);
1421 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1422 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1423 ScopeVariables[LS].push_back(Var);
1424 // Vars.push_back(Var);
1427 /// endFunction - Gather and emit post-function debug information.
1429 void DwarfDebug::endFunction(const MachineFunction *MF) {
1430 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1432 // Define end label for subprogram.
1433 FunctionEndSym = Asm->GetTempSymbol("func_end",
1434 Asm->getFunctionNumber());
1435 // Assumes in correct section after the entry point.
1436 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1438 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1439 collectVariableInfo(MF, ProcessedVars);
1441 // Construct abstract scopes.
1442 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1443 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1444 LexicalScope *AScope = AList[i];
1445 DISubprogram SP(AScope->getScopeNode());
1447 // Collect info for variables that were optimized out.
1448 StringRef FName = SP.getLinkageName();
1450 FName = SP.getName();
1451 if (NamedMDNode *NMD =
1452 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
1453 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1454 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1455 if (!DV || !ProcessedVars.insert(DV))
1457 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1458 addScopeVariable(Scope, new DbgVariable(DV));
1462 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1463 constructScopeDIE(AScope);
1466 DIE *CurFnDIE = constructScopeDIE(LScopes.getCurrentFunctionScope());
1468 if (!DisableFramePointerElim(*MF)) {
1469 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1470 CompileUnit *TheCU = getCompileUnit(FnScope->getScopeNode());
1471 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1472 dwarf::DW_FORM_flag, 1);
1474 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1475 MMI->getFrameMoves()));
1478 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1479 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1480 DeleteContainerPointers(I->second);
1481 ScopeVariables.clear();
1482 DeleteContainerPointers(CurrentFnArguments);
1483 DbgVariableToFrameIndexMap.clear();
1484 VarToAbstractVarMap.clear();
1485 DbgVariableToDbgInstMap.clear();
1486 UserVariables.clear();
1488 AbstractVariables.clear();
1489 LabelsBeforeInsn.clear();
1490 LabelsAfterInsn.clear();
1494 /// recordVariableFrameIndex - Record a variable's index.
1495 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
1496 assert (V && "Invalid DbgVariable!");
1497 DbgVariableToFrameIndexMap[V] = Index;
1500 /// findVariableFrameIndex - Return true if frame index for the variable
1501 /// is found. Update FI to hold value of the index.
1502 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
1503 assert (V && "Invalid DbgVariable!");
1504 DenseMap<const DbgVariable *, int>::iterator I =
1505 DbgVariableToFrameIndexMap.find(V);
1506 if (I == DbgVariableToFrameIndexMap.end())
1512 /// recordSourceLine - Register a source line with debug info. Returns the
1513 /// unique label that was emitted and which provides correspondence to
1514 /// the source line list.
1515 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1521 DIDescriptor Scope(S);
1523 if (Scope.isCompileUnit()) {
1524 DICompileUnit CU(S);
1525 Fn = CU.getFilename();
1526 Dir = CU.getDirectory();
1527 } else if (Scope.isFile()) {
1529 Fn = F.getFilename();
1530 Dir = F.getDirectory();
1531 } else if (Scope.isSubprogram()) {
1533 Fn = SP.getFilename();
1534 Dir = SP.getDirectory();
1535 } else if (Scope.isLexicalBlock()) {
1536 DILexicalBlock DB(S);
1537 Fn = DB.getFilename();
1538 Dir = DB.getDirectory();
1540 assert(0 && "Unexpected scope info");
1542 Src = GetOrCreateSourceID(Fn, Dir);
1544 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1547 //===----------------------------------------------------------------------===//
1549 //===----------------------------------------------------------------------===//
1551 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1554 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1555 // Get the children.
1556 const std::vector<DIE *> &Children = Die->getChildren();
1558 // If not last sibling and has children then add sibling offset attribute.
1559 if (!Last && !Children.empty())
1560 Die->addSiblingOffset(DIEValueAllocator);
1562 // Record the abbreviation.
1563 assignAbbrevNumber(Die->getAbbrev());
1565 // Get the abbreviation for this DIE.
1566 unsigned AbbrevNumber = Die->getAbbrevNumber();
1567 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1570 Die->setOffset(Offset);
1572 // Start the size with the size of abbreviation code.
1573 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1575 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1576 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1578 // Size the DIE attribute values.
1579 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1580 // Size attribute value.
1581 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1583 // Size the DIE children if any.
1584 if (!Children.empty()) {
1585 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1586 "Children flag not set");
1588 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1589 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1591 // End of children marker.
1592 Offset += sizeof(int8_t);
1595 Die->setSize(Offset - Die->getOffset());
1599 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1601 void DwarfDebug::computeSizeAndOffsets() {
1602 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1603 E = CUMap.end(); I != E; ++I) {
1604 // Compute size of compile unit header.
1606 sizeof(int32_t) + // Length of Compilation Unit Info
1607 sizeof(int16_t) + // DWARF version number
1608 sizeof(int32_t) + // Offset Into Abbrev. Section
1609 sizeof(int8_t); // Pointer Size (in bytes)
1610 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1614 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1615 /// temporary label to it if SymbolStem is specified.
1616 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1617 const char *SymbolStem = 0) {
1618 Asm->OutStreamer.SwitchSection(Section);
1619 if (!SymbolStem) return 0;
1621 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1622 Asm->OutStreamer.EmitLabel(TmpSym);
1626 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1627 /// the start of each one.
1628 void DwarfDebug::EmitSectionLabels() {
1629 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1631 // Dwarf sections base addresses.
1632 DwarfInfoSectionSym =
1633 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1634 DwarfAbbrevSectionSym =
1635 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1636 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1638 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1639 EmitSectionSym(Asm, MacroInfo);
1641 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1642 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1643 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1644 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1645 DwarfStrSectionSym =
1646 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1647 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1650 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1651 "section_debug_loc");
1653 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1654 EmitSectionSym(Asm, TLOF.getDataSection());
1657 /// emitDIE - Recursively emits a debug information entry.
1659 void DwarfDebug::emitDIE(DIE *Die) {
1660 // Get the abbreviation for this DIE.
1661 unsigned AbbrevNumber = Die->getAbbrevNumber();
1662 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1664 // Emit the code (index) for the abbreviation.
1665 if (Asm->isVerbose())
1666 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1667 Twine::utohexstr(Die->getOffset()) + ":0x" +
1668 Twine::utohexstr(Die->getSize()) + " " +
1669 dwarf::TagString(Abbrev->getTag()));
1670 Asm->EmitULEB128(AbbrevNumber);
1672 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1673 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1675 // Emit the DIE attribute values.
1676 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1677 unsigned Attr = AbbrevData[i].getAttribute();
1678 unsigned Form = AbbrevData[i].getForm();
1679 assert(Form && "Too many attributes for DIE (check abbreviation)");
1681 if (Asm->isVerbose())
1682 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1685 case dwarf::DW_AT_sibling:
1686 Asm->EmitInt32(Die->getSiblingOffset());
1688 case dwarf::DW_AT_abstract_origin: {
1689 DIEEntry *E = cast<DIEEntry>(Values[i]);
1690 DIE *Origin = E->getEntry();
1691 unsigned Addr = Origin->getOffset();
1692 Asm->EmitInt32(Addr);
1695 case dwarf::DW_AT_ranges: {
1696 // DW_AT_range Value encodes offset in debug_range section.
1697 DIEInteger *V = cast<DIEInteger>(Values[i]);
1699 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1700 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1704 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1706 DwarfDebugRangeSectionSym,
1711 case dwarf::DW_AT_location: {
1712 if (UseDotDebugLocEntry.count(Die) != 0) {
1713 DIELabel *L = cast<DIELabel>(Values[i]);
1714 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1716 Values[i]->EmitValue(Asm, Form);
1719 case dwarf::DW_AT_accessibility: {
1720 if (Asm->isVerbose()) {
1721 DIEInteger *V = cast<DIEInteger>(Values[i]);
1722 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1724 Values[i]->EmitValue(Asm, Form);
1728 // Emit an attribute using the defined form.
1729 Values[i]->EmitValue(Asm, Form);
1734 // Emit the DIE children if any.
1735 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1736 const std::vector<DIE *> &Children = Die->getChildren();
1738 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1739 emitDIE(Children[j]);
1741 if (Asm->isVerbose())
1742 Asm->OutStreamer.AddComment("End Of Children Mark");
1747 /// emitDebugInfo - Emit the debug info section.
1749 void DwarfDebug::emitDebugInfo() {
1750 // Start debug info section.
1751 Asm->OutStreamer.SwitchSection(
1752 Asm->getObjFileLowering().getDwarfInfoSection());
1753 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1754 E = CUMap.end(); I != E; ++I) {
1755 CompileUnit *TheCU = I->second;
1756 DIE *Die = TheCU->getCUDie();
1758 // Emit the compile units header.
1759 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1762 // Emit size of content not including length itself
1763 unsigned ContentSize = Die->getSize() +
1764 sizeof(int16_t) + // DWARF version number
1765 sizeof(int32_t) + // Offset Into Abbrev. Section
1766 sizeof(int8_t); // Pointer Size (in bytes)
1768 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1769 Asm->EmitInt32(ContentSize);
1770 Asm->OutStreamer.AddComment("DWARF version number");
1771 Asm->EmitInt16(dwarf::DWARF_VERSION);
1772 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1773 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1774 DwarfAbbrevSectionSym);
1775 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1776 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1779 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1783 /// emitAbbreviations - Emit the abbreviation section.
1785 void DwarfDebug::emitAbbreviations() const {
1786 // Check to see if it is worth the effort.
1787 if (!Abbreviations.empty()) {
1788 // Start the debug abbrev section.
1789 Asm->OutStreamer.SwitchSection(
1790 Asm->getObjFileLowering().getDwarfAbbrevSection());
1792 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1794 // For each abbrevation.
1795 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1796 // Get abbreviation data
1797 const DIEAbbrev *Abbrev = Abbreviations[i];
1799 // Emit the abbrevations code (base 1 index.)
1800 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1802 // Emit the abbreviations data.
1806 // Mark end of abbreviations.
1807 Asm->EmitULEB128(0, "EOM(3)");
1809 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1813 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1814 /// the line matrix.
1816 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1817 // Define last address of section.
1818 Asm->OutStreamer.AddComment("Extended Op");
1821 Asm->OutStreamer.AddComment("Op size");
1822 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1823 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1824 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1826 Asm->OutStreamer.AddComment("Section end label");
1828 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1829 Asm->getTargetData().getPointerSize(),
1832 // Mark end of matrix.
1833 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1839 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1841 void DwarfDebug::emitDebugPubNames() {
1842 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1843 E = CUMap.end(); I != E; ++I) {
1844 CompileUnit *TheCU = I->second;
1845 // Start the dwarf pubnames section.
1846 Asm->OutStreamer.SwitchSection(
1847 Asm->getObjFileLowering().getDwarfPubNamesSection());
1849 Asm->OutStreamer.AddComment("Length of Public Names Info");
1850 Asm->EmitLabelDifference(
1851 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1852 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1854 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1857 Asm->OutStreamer.AddComment("DWARF Version");
1858 Asm->EmitInt16(dwarf::DWARF_VERSION);
1860 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1861 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1862 DwarfInfoSectionSym);
1864 Asm->OutStreamer.AddComment("Compilation Unit Length");
1865 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1866 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1869 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1870 for (StringMap<DIE*>::const_iterator
1871 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1872 const char *Name = GI->getKeyData();
1873 DIE *Entity = GI->second;
1875 Asm->OutStreamer.AddComment("DIE offset");
1876 Asm->EmitInt32(Entity->getOffset());
1878 if (Asm->isVerbose())
1879 Asm->OutStreamer.AddComment("External Name");
1880 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1883 Asm->OutStreamer.AddComment("End Mark");
1885 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1890 void DwarfDebug::emitDebugPubTypes() {
1891 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1892 E = CUMap.end(); I != E; ++I) {
1893 CompileUnit *TheCU = I->second;
1894 // Start the dwarf pubnames section.
1895 Asm->OutStreamer.SwitchSection(
1896 Asm->getObjFileLowering().getDwarfPubTypesSection());
1897 Asm->OutStreamer.AddComment("Length of Public Types Info");
1898 Asm->EmitLabelDifference(
1899 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1900 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1902 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1905 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1906 Asm->EmitInt16(dwarf::DWARF_VERSION);
1908 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1909 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1910 DwarfInfoSectionSym);
1912 Asm->OutStreamer.AddComment("Compilation Unit Length");
1913 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1914 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1917 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1918 for (StringMap<DIE*>::const_iterator
1919 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1920 const char *Name = GI->getKeyData();
1921 DIE *Entity = GI->second;
1923 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1924 Asm->EmitInt32(Entity->getOffset());
1926 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1927 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1930 Asm->OutStreamer.AddComment("End Mark");
1932 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1937 /// emitDebugStr - Emit visible names into a debug str section.
1939 void DwarfDebug::emitDebugStr() {
1940 // Check to see if it is worth the effort.
1941 if (StringPool.empty()) return;
1943 // Start the dwarf str section.
1944 Asm->OutStreamer.SwitchSection(
1945 Asm->getObjFileLowering().getDwarfStrSection());
1947 // Get all of the string pool entries and put them in an array by their ID so
1948 // we can sort them.
1949 SmallVector<std::pair<unsigned,
1950 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1952 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1953 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1954 Entries.push_back(std::make_pair(I->second.second, &*I));
1956 array_pod_sort(Entries.begin(), Entries.end());
1958 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1959 // Emit a label for reference from debug information entries.
1960 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1962 // Emit the string itself.
1963 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1967 /// emitDebugLoc - Emit visible names into a debug loc section.
1969 void DwarfDebug::emitDebugLoc() {
1970 if (DotDebugLocEntries.empty())
1973 for (SmallVector<DotDebugLocEntry, 4>::iterator
1974 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1976 DotDebugLocEntry &Entry = *I;
1977 if (I + 1 != DotDebugLocEntries.end())
1981 // Start the dwarf loc section.
1982 Asm->OutStreamer.SwitchSection(
1983 Asm->getObjFileLowering().getDwarfLocSection());
1984 unsigned char Size = Asm->getTargetData().getPointerSize();
1985 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1987 for (SmallVector<DotDebugLocEntry, 4>::iterator
1988 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1989 I != E; ++I, ++index) {
1990 DotDebugLocEntry &Entry = *I;
1991 if (Entry.isMerged()) continue;
1992 if (Entry.isEmpty()) {
1993 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1994 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1995 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1997 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1998 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1999 DIVariable DV(Entry.Variable);
2000 Asm->OutStreamer.AddComment("Loc expr size");
2001 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2002 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2003 Asm->EmitLabelDifference(end, begin, 2);
2004 Asm->OutStreamer.EmitLabel(begin);
2005 if (Entry.isInt()) {
2006 DIBasicType BTy(DV.getType());
2008 (BTy.getEncoding() == dwarf::DW_ATE_signed
2009 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2010 Asm->OutStreamer.AddComment("DW_OP_consts");
2011 Asm->EmitInt8(dwarf::DW_OP_consts);
2012 Asm->EmitSLEB128(Entry.getInt());
2014 Asm->OutStreamer.AddComment("DW_OP_constu");
2015 Asm->EmitInt8(dwarf::DW_OP_constu);
2016 Asm->EmitULEB128(Entry.getInt());
2018 } else if (Entry.isLocation()) {
2019 if (!DV.hasComplexAddress())
2021 Asm->EmitDwarfRegOp(Entry.Loc);
2023 // Complex address entry.
2024 unsigned N = DV.getNumAddrElements();
2026 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2027 if (Entry.Loc.getOffset()) {
2029 Asm->EmitDwarfRegOp(Entry.Loc);
2030 Asm->OutStreamer.AddComment("DW_OP_deref");
2031 Asm->EmitInt8(dwarf::DW_OP_deref);
2032 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2033 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2034 Asm->EmitSLEB128(DV.getAddrElement(1));
2036 // If first address element is OpPlus then emit
2037 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2038 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2039 Asm->EmitDwarfRegOp(Loc);
2043 Asm->EmitDwarfRegOp(Entry.Loc);
2046 // Emit remaining complex address elements.
2047 for (; i < N; ++i) {
2048 uint64_t Element = DV.getAddrElement(i);
2049 if (Element == DIBuilder::OpPlus) {
2050 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2051 Asm->EmitULEB128(DV.getAddrElement(++i));
2052 } else if (Element == DIBuilder::OpDeref)
2053 Asm->EmitInt8(dwarf::DW_OP_deref);
2054 else llvm_unreachable("unknown Opcode found in complex address");
2058 // else ... ignore constant fp. There is not any good way to
2059 // to represent them here in dwarf.
2060 Asm->OutStreamer.EmitLabel(end);
2065 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2067 void DwarfDebug::EmitDebugARanges() {
2068 // Start the dwarf aranges section.
2069 Asm->OutStreamer.SwitchSection(
2070 Asm->getObjFileLowering().getDwarfARangesSection());
2073 /// emitDebugRanges - Emit visible names into a debug ranges section.
2075 void DwarfDebug::emitDebugRanges() {
2076 // Start the dwarf ranges section.
2077 Asm->OutStreamer.SwitchSection(
2078 Asm->getObjFileLowering().getDwarfRangesSection());
2079 unsigned char Size = Asm->getTargetData().getPointerSize();
2080 for (SmallVector<const MCSymbol *, 8>::iterator
2081 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2084 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2086 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2090 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2092 void DwarfDebug::emitDebugMacInfo() {
2093 if (const MCSection *LineInfo =
2094 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2095 // Start the dwarf macinfo section.
2096 Asm->OutStreamer.SwitchSection(LineInfo);
2100 /// emitDebugInlineInfo - Emit inline info using following format.
2102 /// 1. length of section
2103 /// 2. Dwarf version number
2104 /// 3. address size.
2106 /// Entries (one "entry" for each function that was inlined):
2108 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2109 /// otherwise offset into __debug_str for regular function name.
2110 /// 2. offset into __debug_str section for regular function name.
2111 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2112 /// instances for the function.
2114 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2115 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2116 /// __debug_info section, and the low_pc is the starting address for the
2117 /// inlining instance.
2118 void DwarfDebug::emitDebugInlineInfo() {
2119 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2125 Asm->OutStreamer.SwitchSection(
2126 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2128 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2129 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2130 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2132 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2134 Asm->OutStreamer.AddComment("Dwarf Version");
2135 Asm->EmitInt16(dwarf::DWARF_VERSION);
2136 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2137 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2139 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2140 E = InlinedSPNodes.end(); I != E; ++I) {
2142 const MDNode *Node = *I;
2143 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2144 = InlineInfo.find(Node);
2145 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2146 DISubprogram SP(Node);
2147 StringRef LName = SP.getLinkageName();
2148 StringRef Name = SP.getName();
2150 Asm->OutStreamer.AddComment("MIPS linkage name");
2151 if (LName.empty()) {
2152 Asm->OutStreamer.EmitBytes(Name, 0);
2153 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2155 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2156 DwarfStrSectionSym);
2158 Asm->OutStreamer.AddComment("Function name");
2159 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2160 Asm->EmitULEB128(Labels.size(), "Inline count");
2162 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2163 LE = Labels.end(); LI != LE; ++LI) {
2164 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2165 Asm->EmitInt32(LI->second->getOffset());
2167 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2168 Asm->OutStreamer.EmitSymbolValue(LI->first,
2169 Asm->getTargetData().getPointerSize(),0);
2173 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));