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/Mangler.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Analysis/DebugInfo.h"
35 #include "llvm/Analysis/DIBuilder.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/ValueHandle.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/Path.h"
48 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
50 cl::desc("Disable debug info printing"));
52 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
53 cl::desc("Make an absence of debug location information explicit."),
57 const char *DWARFGroupName = "DWARF Emission";
58 const char *DbgTimerName = "DWARF Debug Writer";
59 } // end anonymous namespace
61 //===----------------------------------------------------------------------===//
63 /// Configuration values for initial hash set sizes (log2).
65 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
69 DIType DbgVariable::getType() const {
70 DIType Ty = Var.getType();
71 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
73 if (Var.isBlockByrefVariable()) {
74 /* Byref variables, in Blocks, are declared by the programmer as
75 "SomeType VarName;", but the compiler creates a
76 __Block_byref_x_VarName struct, and gives the variable VarName
77 either the struct, or a pointer to the struct, as its type. This
78 is necessary for various behind-the-scenes things the compiler
79 needs to do with by-reference variables in blocks.
81 However, as far as the original *programmer* is concerned, the
82 variable should still have type 'SomeType', as originally declared.
84 The following function dives into the __Block_byref_x_VarName
85 struct to find the original type of the variable. This will be
86 passed back to the code generating the type for the Debug
87 Information Entry for the variable 'VarName'. 'VarName' will then
88 have the original type 'SomeType' in its debug information.
90 The original type 'SomeType' will be the type of the field named
91 'VarName' inside the __Block_byref_x_VarName struct.
93 NOTE: In order for this to not completely fail on the debugger
94 side, the Debug Information Entry for the variable VarName needs to
95 have a DW_AT_location that tells the debugger how to unwind through
96 the pointers and __Block_byref_x_VarName struct to find the actual
97 value of the variable. The function addBlockByrefType does this. */
99 unsigned tag = Ty.getTag();
101 if (tag == dwarf::DW_TAG_pointer_type) {
102 DIDerivedType DTy = DIDerivedType(Ty);
103 subType = DTy.getTypeDerivedFrom();
106 DICompositeType blockStruct = DICompositeType(subType);
107 DIArray Elements = blockStruct.getTypeArray();
109 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
110 DIDescriptor Element = Elements.getElement(i);
111 DIDerivedType DT = DIDerivedType(Element);
112 if (getName() == DT.getName())
113 return (DT.getTypeDerivedFrom());
120 } // end llvm namespace
122 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
123 : Asm(A), MMI(Asm->MMI), FirstCU(0),
124 AbbreviationsSet(InitAbbreviationsSetSize),
126 NextStringPoolNumber = 0;
128 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
129 DwarfStrSectionSym = TextSectionSym = 0;
130 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
131 FunctionBeginSym = FunctionEndSym = 0;
133 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
137 DwarfDebug::~DwarfDebug() {
140 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
141 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
142 if (Entry.first) return Entry.first;
144 Entry.second = NextStringPoolNumber++;
145 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
149 /// assignAbbrevNumber - Define a unique number for the abbreviation.
151 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
152 // Profile the node so that we can make it unique.
156 // Check the set for priors.
157 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
159 // If it's newly added.
160 if (InSet == &Abbrev) {
161 // Add to abbreviation list.
162 Abbreviations.push_back(&Abbrev);
164 // Assign the vector position + 1 as its number.
165 Abbrev.setNumber(Abbreviations.size());
167 // Assign existing abbreviation number.
168 Abbrev.setNumber(InSet->getNumber());
172 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
173 /// printer to not emit usual symbol prefix before the symbol name is used then
174 /// return linkage name after skipping this special LLVM prefix.
175 static StringRef getRealLinkageName(StringRef LinkageName) {
177 if (LinkageName.startswith(StringRef(&One, 1)))
178 return LinkageName.substr(1);
182 /// isSubprogramContext - Return true if Context is either a subprogram
183 /// or another context nested inside a subprogram.
184 static bool isSubprogramContext(const MDNode *Context) {
187 DIDescriptor D(Context);
188 if (D.isSubprogram())
191 return isSubprogramContext(DIType(Context).getContext());
195 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
196 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
197 /// If there are global variables in this scope then create and insert
198 /// DIEs for these variables.
199 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
200 CompileUnit *SPCU = getCompileUnit(SPNode);
201 DIE *SPDie = SPCU->getDIE(SPNode);
203 assert(SPDie && "Unable to find subprogram DIE!");
204 DISubprogram SP(SPNode);
206 DISubprogram SPDecl = SP.getFunctionDeclaration();
207 if (SPDecl.isSubprogram())
208 // Refer function declaration directly.
209 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
210 SPCU->getOrCreateSubprogramDIE(SPDecl));
212 // There is not any need to generate specification DIE for a function
213 // defined at compile unit level. If a function is defined inside another
214 // function then gdb prefers the definition at top level and but does not
215 // expect specification DIE in parent function. So avoid creating
216 // specification DIE for a function defined inside a function.
217 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
218 !SP.getContext().isFile() &&
219 !isSubprogramContext(SP.getContext())) {
220 SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
223 DICompositeType SPTy = SP.getType();
224 DIArray Args = SPTy.getTypeArray();
225 unsigned SPTag = SPTy.getTag();
226 if (SPTag == dwarf::DW_TAG_subroutine_type)
227 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
228 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
229 DIType ATy = DIType(DIType(Args.getElement(i)));
230 SPCU->addType(Arg, ATy);
231 if (ATy.isArtificial())
232 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
233 SPDie->addChild(Arg);
235 DIE *SPDeclDie = SPDie;
236 SPDie = new DIE(dwarf::DW_TAG_subprogram);
237 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
242 // Pick up abstract subprogram DIE.
243 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
244 SPDie = new DIE(dwarf::DW_TAG_subprogram);
245 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
246 dwarf::DW_FORM_ref4, AbsSPDIE);
250 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
251 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
252 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
253 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
254 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
255 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
256 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
261 /// constructLexicalScope - Construct new DW_TAG_lexical_block
262 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
263 DIE *DwarfDebug::constructLexicalScopeDIE(LexicalScope *Scope) {
265 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
266 if (Scope->isAbstractScope())
269 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
273 CompileUnit *TheCU = getCompileUnit(Scope->getScopeNode());
274 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
275 if (Ranges.size() > 1) {
276 // .debug_range section has not been laid out yet. Emit offset in
277 // .debug_range as a uint, size 4, for now. emitDIE will handle
278 // DW_AT_ranges appropriately.
279 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
280 DebugRangeSymbols.size()
281 * Asm->getTargetData().getPointerSize());
282 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
283 RE = Ranges.end(); RI != RE; ++RI) {
284 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
285 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
287 DebugRangeSymbols.push_back(NULL);
288 DebugRangeSymbols.push_back(NULL);
292 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
293 const MCSymbol *End = getLabelAfterInsn(RI->second);
295 if (End == 0) return 0;
297 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
298 assert(End->isDefined() && "Invalid end label for an inlined scope!");
300 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
301 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
306 /// constructInlinedScopeDIE - This scope represents inlined body of
307 /// a function. Construct DIE to represent this concrete inlined copy
309 DIE *DwarfDebug::constructInlinedScopeDIE(LexicalScope *Scope) {
311 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
312 assert (Ranges.empty() == false
313 && "LexicalScope does not have instruction markers!");
315 if (!Scope->getScopeNode())
317 DIScope DS(Scope->getScopeNode());
318 DISubprogram InlinedSP = getDISubprogram(DS);
319 CompileUnit *TheCU = getCompileUnit(InlinedSP);
320 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
322 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
326 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
327 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
328 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
330 if (StartLabel == 0 || EndLabel == 0) {
331 assert (0 && "Unexpected Start and End labels for a inlined scope!");
334 assert(StartLabel->isDefined() &&
335 "Invalid starting label for an inlined scope!");
336 assert(EndLabel->isDefined() &&
337 "Invalid end label for an inlined scope!");
339 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
340 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
341 dwarf::DW_FORM_ref4, OriginDIE);
343 if (Ranges.size() > 1) {
344 // .debug_range section has not been laid out yet. Emit offset in
345 // .debug_range as a uint, size 4, for now. emitDIE will handle
346 // DW_AT_ranges appropriately.
347 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
348 DebugRangeSymbols.size()
349 * Asm->getTargetData().getPointerSize());
350 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
351 RE = Ranges.end(); RI != RE; ++RI) {
352 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
353 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
355 DebugRangeSymbols.push_back(NULL);
356 DebugRangeSymbols.push_back(NULL);
358 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
360 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
364 InlinedSubprogramDIEs.insert(OriginDIE);
366 // Track the start label for this inlined function.
367 //.debug_inlined section specification does not clearly state how
368 // to emit inlined scope that is split into multiple instruction ranges.
369 // For now, use first instruction range and emit low_pc/high_pc pair and
370 // corresponding .debug_inlined section entry for this pair.
371 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
372 I = InlineInfo.find(InlinedSP);
374 if (I == InlineInfo.end()) {
375 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
377 InlinedSPNodes.push_back(InlinedSP);
379 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
381 DILocation DL(Scope->getInlinedAt());
382 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
383 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
388 /// isUnsignedDIType - Return true if type encoding is unsigned.
389 static bool isUnsignedDIType(DIType Ty) {
390 DIDerivedType DTy(Ty);
392 return isUnsignedDIType(DTy.getTypeDerivedFrom());
396 unsigned Encoding = BTy.getEncoding();
397 if (Encoding == dwarf::DW_ATE_unsigned ||
398 Encoding == dwarf::DW_ATE_unsigned_char)
404 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
405 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, LexicalScope *Scope) {
406 StringRef Name = DV->getName();
410 // Translate tag to proper Dwarf tag. The result variable is dropped for
413 switch (DV->getTag()) {
414 case dwarf::DW_TAG_return_variable:
416 case dwarf::DW_TAG_arg_variable:
417 Tag = dwarf::DW_TAG_formal_parameter;
419 case dwarf::DW_TAG_auto_variable: // fall thru
421 Tag = dwarf::DW_TAG_variable;
425 // Define variable debug information entry.
426 DIE *VariableDie = new DIE(Tag);
427 CompileUnit *VariableCU = getCompileUnit(DV->getVariable());
429 DenseMap<const DbgVariable *, const DbgVariable *>::iterator
430 V2AVI = VarToAbstractVarMap.find(DV);
431 if (V2AVI != VarToAbstractVarMap.end())
432 AbsDIE = V2AVI->second->getDIE();
435 VariableCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
436 dwarf::DW_FORM_ref4, AbsDIE);
438 VariableCU->addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
440 VariableCU->addSourceLine(VariableDie, DV->getVariable());
442 // Add variable type.
443 VariableCU->addType(VariableDie, DV->getType());
446 if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
447 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
448 dwarf::DW_FORM_flag, 1);
449 else if (DIVariable(DV->getVariable()).isArtificial())
450 VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial,
451 dwarf::DW_FORM_flag, 1);
453 if (Scope->isAbstractScope()) {
454 DV->setDIE(VariableDie);
458 // Add variable address.
460 unsigned Offset = DV->getDotDebugLocOffset();
462 VariableCU->addLabel(VariableDie, dwarf::DW_AT_location,
463 dwarf::DW_FORM_data4,
464 Asm->GetTempSymbol("debug_loc", Offset));
465 DV->setDIE(VariableDie);
466 UseDotDebugLocEntry.insert(VariableDie);
470 // Check if variable is described by a DBG_VALUE instruction.
471 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
472 DbgVariableToDbgInstMap.find(DV);
473 if (DVI != DbgVariableToDbgInstMap.end()) {
474 const MachineInstr *DVInsn = DVI->second;
475 bool updated = false;
476 if (DVInsn->getNumOperands() == 3) {
477 if (DVInsn->getOperand(0).isReg()) {
478 const MachineOperand RegOp = DVInsn->getOperand(0);
479 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
480 if (DVInsn->getOperand(1).isImm() &&
481 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
482 unsigned FrameReg = 0;
483 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
485 TFI->getFrameIndexReference(*Asm->MF,
486 DVInsn->getOperand(1).getImm(),
488 MachineLocation Location(FrameReg, Offset);
489 VariableCU->addVariableAddress(DV, VariableDie, Location);
491 } else if (RegOp.getReg())
492 VariableCU->addVariableAddress(DV, VariableDie,
493 MachineLocation(RegOp.getReg()));
496 else if (DVInsn->getOperand(0).isImm())
498 VariableCU->addConstantValue(VariableDie, DVInsn->getOperand(0),
500 else if (DVInsn->getOperand(0).isFPImm())
502 VariableCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
503 else if (DVInsn->getOperand(0).isCImm())
505 VariableCU->addConstantValue(VariableDie,
506 DVInsn->getOperand(0).getCImm(),
507 isUnsignedDIType(DV->getType()));
509 VariableCU->addVariableAddress(DV, VariableDie,
510 Asm->getDebugValueLocation(DVInsn));
514 // If variableDie is not updated then DBG_VALUE instruction does not
515 // have valid variable info.
519 DV->setDIE(VariableDie);
523 // .. else use frame index, if available.
525 if (findVariableFrameIndex(DV, &FI)) {
526 unsigned FrameReg = 0;
527 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
529 TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
530 MachineLocation Location(FrameReg, Offset);
531 VariableCU->addVariableAddress(DV, VariableDie, Location);
534 DV->setDIE(VariableDie);
539 /// constructScopeDIE - Construct a DIE for this scope.
540 DIE *DwarfDebug::constructScopeDIE(LexicalScope *Scope) {
541 if (!Scope || !Scope->getScopeNode())
544 SmallVector <DIE *, 8> Children;
546 // Collect arguments for current function.
547 if (LScopes.isCurrentFunctionScope(Scope))
548 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
549 if (DbgVariable *ArgDV = CurrentFnArguments[i])
550 if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
551 Children.push_back(Arg);
553 // Collect lexical scope childrens first.
554 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
555 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
556 if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
557 Children.push_back(Variable);
558 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
559 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
560 if (DIE *Nested = constructScopeDIE(Scopes[j]))
561 Children.push_back(Nested);
562 DIScope DS(Scope->getScopeNode());
563 DIE *ScopeDIE = NULL;
564 if (Scope->getInlinedAt())
565 ScopeDIE = constructInlinedScopeDIE(Scope);
566 else if (DS.isSubprogram()) {
567 ProcessedSPNodes.insert(DS);
568 if (Scope->isAbstractScope()) {
569 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
570 // Note down abstract DIE.
572 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
575 ScopeDIE = updateSubprogramScopeDIE(DS);
578 // There is no need to emit empty lexical block DIE.
579 if (Children.empty())
581 ScopeDIE = constructLexicalScopeDIE(Scope);
584 if (!ScopeDIE) return NULL;
587 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
588 E = Children.end(); I != E; ++I)
589 ScopeDIE->addChild(*I);
591 if (DS.isSubprogram())
592 getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
597 /// GetOrCreateSourceID - Look up the source id with the given directory and
598 /// source file names. If none currently exists, create a new id and insert it
599 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
602 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
604 // If FE did not provide a file name, then assume stdin.
605 if (FileName.empty())
606 return GetOrCreateSourceID("<stdin>", StringRef());
608 // MCStream expects full path name as filename.
609 if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
610 SmallString<128> FullPathName = DirName;
611 sys::path::append(FullPathName, FileName);
612 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
613 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
616 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
617 if (Entry.getValue())
618 return Entry.getValue();
620 unsigned SrcId = SourceIdMap.size();
621 Entry.setValue(SrcId);
623 // Print out a .file directive to specify files for .loc directives.
624 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
629 /// constructCompileUnit - Create new CompileUnit for the given
630 /// metadata node with tag DW_TAG_compile_unit.
631 void DwarfDebug::constructCompileUnit(const MDNode *N) {
632 DICompileUnit DIUnit(N);
633 StringRef FN = DIUnit.getFilename();
634 StringRef Dir = DIUnit.getDirectory();
635 unsigned ID = GetOrCreateSourceID(FN, Dir);
637 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
638 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
639 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
640 DIUnit.getProducer());
641 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
642 DIUnit.getLanguage());
643 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
644 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
645 // simplifies debug range entries.
646 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
647 // DW_AT_stmt_list is a offset of line number information for this
648 // compile unit in debug_line section.
649 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
650 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
651 Asm->GetTempSymbol("section_line"));
653 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
656 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
657 if (DIUnit.isOptimized())
658 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
660 StringRef Flags = DIUnit.getFlags();
662 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,
665 unsigned RVer = DIUnit.getRunTimeVersion();
667 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
668 dwarf::DW_FORM_data1, RVer);
672 CUMap.insert(std::make_pair(N, NewCU));
675 /// getCompileUnit - Get CompileUnit DIE.
676 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
677 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
679 const MDNode *CUNode = NULL;
680 if (D.isCompileUnit())
682 else if (D.isSubprogram())
683 CUNode = DISubprogram(N).getCompileUnit();
685 CUNode = DIType(N).getCompileUnit();
686 else if (D.isGlobalVariable())
687 CUNode = DIGlobalVariable(N).getCompileUnit();
688 else if (D.isVariable())
689 CUNode = DIVariable(N).getCompileUnit();
690 else if (D.isNameSpace())
691 CUNode = DINameSpace(N).getCompileUnit();
693 CUNode = DIFile(N).getCompileUnit();
697 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
698 = CUMap.find(CUNode);
699 if (I == CUMap.end())
704 // Return const expression if value is a GEP to access merged global
706 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
707 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
708 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
709 if (!CE || CE->getNumOperands() != 3 ||
710 CE->getOpcode() != Instruction::GetElementPtr)
713 // First operand points to a global struct.
714 Value *Ptr = CE->getOperand(0);
715 if (!isa<GlobalValue>(Ptr) ||
716 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
719 // Second operand is zero.
720 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
721 if (!CI || !CI->isZero())
724 // Third operand is offset.
725 if (!isa<ConstantInt>(CE->getOperand(2)))
731 /// constructGlobalVariableDIE - Construct global variable DIE.
732 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
733 DIGlobalVariable GV(N);
735 // If debug information is malformed then ignore it.
736 if (GV.Verify() == false)
739 // Check for pre-existence.
740 CompileUnit *TheCU = getCompileUnit(N);
741 if (TheCU->getDIE(GV))
744 DIType GTy = GV.getType();
745 DIE *VariableDIE = new DIE(GV.getTag());
747 bool isGlobalVariable = GV.getGlobal() != NULL;
750 TheCU->addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
751 GV.getDisplayName());
752 StringRef LinkageName = GV.getLinkageName();
753 if (!LinkageName.empty() && isGlobalVariable)
754 TheCU->addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
755 dwarf::DW_FORM_string,
756 getRealLinkageName(LinkageName));
758 TheCU->addType(VariableDIE, GTy);
761 if (!GV.isLocalToUnit()) {
762 TheCU->addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
764 TheCU->addGlobal(GV.getName(), VariableDIE);
766 // Add line number info.
767 TheCU->addSourceLine(VariableDIE, GV);
769 TheCU->insertDIE(N, VariableDIE);
770 // Add to context owner.
771 DIDescriptor GVContext = GV.getContext();
772 TheCU->addToContextOwner(VariableDIE, GVContext);
774 if (isGlobalVariable) {
775 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
776 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
777 TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
778 Asm->Mang->getSymbol(GV.getGlobal()));
779 // Do not create specification DIE if context is either compile unit
781 if (GV.isDefinition() && !GVContext.isCompileUnit() &&
782 !GVContext.isFile() && !isSubprogramContext(GVContext)) {
783 // Create specification DIE.
784 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
785 TheCU->addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
786 dwarf::DW_FORM_ref4, VariableDIE);
787 TheCU->addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
788 TheCU->addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag,
790 TheCU->addDie(VariableSpecDIE);
792 TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
794 } else if (const ConstantInt *CI =
795 dyn_cast_or_null<ConstantInt>(GV.getConstant()))
796 TheCU->addConstantValue(VariableDIE, CI, isUnsignedDIType(GTy));
797 else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
798 // GV is a merged global.
799 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
800 Value *Ptr = CE->getOperand(0);
801 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
802 TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
803 Asm->Mang->getSymbol(cast<GlobalValue>(Ptr)));
804 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
805 SmallVector<Value*, 3> Idx(CE->op_begin()+1, CE->op_end());
806 TheCU->addUInt(Block, 0, dwarf::DW_FORM_udata,
807 Asm->getTargetData().getIndexedOffset(Ptr->getType(), Idx));
808 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
809 TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
815 /// construct SubprogramDIE - Construct subprogram DIE.
816 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
819 // Check for pre-existence.
820 CompileUnit *TheCU = getCompileUnit(N);
821 if (TheCU->getDIE(N))
824 if (!SP.isDefinition())
825 // This is a method declaration which will be handled while constructing
829 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
832 TheCU->insertDIE(N, SubprogramDie);
834 // Add to context owner.
835 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
838 TheCU->addGlobal(SP.getName(), SubprogramDie);
843 /// beginModule - Emit all Dwarf sections that should come prior to the
844 /// content. Create global DIEs and emit initial debug info sections.
845 /// This is invoked by the target AsmPrinter.
846 void DwarfDebug::beginModule(Module *M) {
847 if (DisableDebugInfoPrinting)
850 // If module has named metadata anchors then use them, otherwise scan the
851 // module using debug info finder to collect debug info.
852 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
855 NamedMDNode *GV_Nodes = M->getNamedMetadata("llvm.dbg.gv");
856 NamedMDNode *SP_Nodes = M->getNamedMetadata("llvm.dbg.sp");
857 if (!GV_Nodes && !SP_Nodes)
858 // If there are not any global variables or any functions then
859 // there is not any debug info in this module.
862 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i)
863 constructCompileUnit(CU_Nodes->getOperand(i));
866 for (unsigned i = 0, e = GV_Nodes->getNumOperands(); i != e; ++i)
867 constructGlobalVariableDIE(GV_Nodes->getOperand(i));
870 for (unsigned i = 0, e = SP_Nodes->getNumOperands(); i != e; ++i)
871 constructSubprogramDIE(SP_Nodes->getOperand(i));
875 DebugInfoFinder DbgFinder;
876 DbgFinder.processModule(*M);
878 bool HasDebugInfo = false;
879 // Scan all the compile-units to see if there are any marked as the main
880 // unit. If not, we do not generate debug info.
881 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
882 E = DbgFinder.compile_unit_end(); I != E; ++I) {
883 if (DICompileUnit(*I).isMain()) {
888 if (!HasDebugInfo) return;
890 // Create all the compile unit DIEs.
891 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
892 E = DbgFinder.compile_unit_end(); I != E; ++I)
893 constructCompileUnit(*I);
895 // Create DIEs for each global variable.
896 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
897 E = DbgFinder.global_variable_end(); I != E; ++I)
898 constructGlobalVariableDIE(*I);
900 // Create DIEs for each subprogram.
901 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
902 E = DbgFinder.subprogram_end(); I != E; ++I)
903 constructSubprogramDIE(*I);
906 // Tell MMI that we have debug info.
907 MMI->setDebugInfoAvailability(true);
909 // Emit initial sections.
913 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
914 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
915 DIType Ty(NMD->getOperand(i));
916 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
919 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
920 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
921 DIType Ty(NMD->getOperand(i));
922 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
925 // Prime section data.
926 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
929 /// endModule - Emit all Dwarf sections that should come after the content.
931 void DwarfDebug::endModule() {
932 if (!FirstCU) return;
933 const Module *M = MMI->getModule();
934 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
935 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
936 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
937 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
938 DISubprogram SP(AllSPs->getOperand(SI));
939 if (!SP.Verify()) continue;
941 // Collect info for variables that were optimized out.
942 if (!SP.isDefinition()) continue;
943 StringRef FName = SP.getLinkageName();
945 FName = SP.getName();
946 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
948 unsigned E = NMD->getNumOperands();
950 LexicalScope *Scope = new LexicalScope(NULL, DIDescriptor(SP), NULL,
952 DeadFnScopeMap[SP] = Scope;
953 SmallVector<DbgVariable, 8> Variables;
954 for (unsigned I = 0; I != E; ++I) {
955 DIVariable DV(NMD->getOperand(I));
956 if (!DV.Verify()) continue;
957 Variables.push_back(DbgVariable(DV));
960 // Construct subprogram DIE and add variables DIEs.
961 constructSubprogramDIE(SP);
962 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
963 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
964 if (DIE *VariableDIE = constructVariableDIE(&Variables[i], Scope))
965 ScopeDIE->addChild(VariableDIE);
970 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
971 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
972 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
974 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
977 // Emit DW_AT_containing_type attribute to connect types with their
978 // vtable holding type.
979 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
980 CUE = CUMap.end(); CUI != CUE; ++CUI) {
981 CompileUnit *TheCU = CUI->second;
982 TheCU->constructContainingTypeDIEs();
985 // Standard sections final addresses.
986 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
987 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
988 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
989 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
991 // End text sections.
992 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
993 Asm->OutStreamer.SwitchSection(SectionMap[i]);
994 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
997 // Compute DIE offsets and sizes.
998 computeSizeAndOffsets();
1000 // Emit all the DIEs into a debug info section
1003 // Corresponding abbreviations into a abbrev section.
1004 emitAbbreviations();
1006 // Emit info into a debug pubnames section.
1007 emitDebugPubNames();
1009 // Emit info into a debug pubtypes section.
1010 emitDebugPubTypes();
1012 // Emit info into a debug loc section.
1015 // Emit info into a debug aranges section.
1018 // Emit info into a debug ranges section.
1021 // Emit info into a debug macinfo section.
1024 // Emit inline info.
1025 emitDebugInlineInfo();
1027 // Emit info into a debug str section.
1031 DeleteContainerSeconds(DeadFnScopeMap);
1032 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1033 E = CUMap.end(); I != E; ++I)
1035 FirstCU = NULL; // Reset for the next Module, if any.
1038 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1039 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1040 DebugLoc ScopeLoc) {
1041 LLVMContext &Ctx = DV->getContext();
1042 // More then one inlined variable corresponds to one abstract variable.
1043 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1044 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1046 return AbsDbgVariable;
1048 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1052 AbsDbgVariable = new DbgVariable(Var);
1053 addScopeVariable(Scope, AbsDbgVariable);
1054 AbstractVariables[Var] = AbsDbgVariable;
1055 return AbsDbgVariable;
1058 /// addCurrentFnArgument - If Var is a current function argument then add
1059 /// it to CurrentFnArguments list.
1060 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1061 DbgVariable *Var, LexicalScope *Scope) {
1062 if (!LScopes.isCurrentFunctionScope(Scope))
1064 DIVariable DV = Var->getVariable();
1065 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1067 unsigned ArgNo = DV.getArgNumber();
1071 size_t Size = CurrentFnArguments.size();
1073 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1074 // llvm::Function argument size is not good indicator of how many
1075 // arguments does the function have at source level.
1077 CurrentFnArguments.resize(ArgNo * 2);
1078 CurrentFnArguments[ArgNo - 1] = Var;
1082 /// collectVariableInfoFromMMITable - Collect variable information from
1083 /// side table maintained by MMI.
1085 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1086 SmallPtrSet<const MDNode *, 16> &Processed) {
1087 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1088 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1089 VE = VMap.end(); VI != VE; ++VI) {
1090 const MDNode *Var = VI->first;
1092 Processed.insert(Var);
1094 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1096 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1098 // If variable scope is not found then skip this variable.
1102 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1103 DbgVariable *RegVar = new DbgVariable(DV);
1104 recordVariableFrameIndex(RegVar, VP.first);
1105 if (!addCurrentFnArgument(MF, RegVar, Scope))
1106 addScopeVariable(Scope, RegVar);
1107 if (AbsDbgVariable) {
1108 recordVariableFrameIndex(AbsDbgVariable, VP.first);
1109 VarToAbstractVarMap[RegVar] = AbsDbgVariable;
1114 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
1115 /// DBG_VALUE instruction, is in a defined reg.
1116 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1117 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1118 return MI->getNumOperands() == 3 &&
1119 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1120 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1123 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
1125 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1126 const MCSymbol *FLabel,
1127 const MCSymbol *SLabel,
1128 const MachineInstr *MI) {
1129 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1131 if (MI->getNumOperands() != 3) {
1132 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1133 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1135 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1136 MachineLocation MLoc;
1137 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1138 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1140 if (MI->getOperand(0).isImm())
1141 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1142 if (MI->getOperand(0).isFPImm())
1143 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1144 if (MI->getOperand(0).isCImm())
1145 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1147 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
1148 return DotDebugLocEntry();
1151 /// collectVariableInfo - Find variables for each lexical scope.
1153 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1154 SmallPtrSet<const MDNode *, 16> &Processed) {
1156 /// collection info from MMI table.
1157 collectVariableInfoFromMMITable(MF, Processed);
1159 for (SmallVectorImpl<const MDNode*>::const_iterator
1160 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1162 const MDNode *Var = *UVI;
1163 if (Processed.count(Var))
1166 // History contains relevant DBG_VALUE instructions for Var and instructions
1168 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1169 if (History.empty())
1171 const MachineInstr *MInsn = History.front();
1174 LexicalScope *Scope = NULL;
1175 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1176 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1177 Scope = LScopes.getCurrentFunctionScope();
1179 if (DV.getVersion() <= LLVMDebugVersion9)
1180 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1182 if (MDNode *IA = DV.getInlinedAt())
1183 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1185 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1188 // If variable scope is not found then skip this variable.
1192 Processed.insert(DV);
1193 assert(MInsn->isDebugValue() && "History must begin with debug value");
1194 DbgVariable *RegVar = new DbgVariable(DV);
1195 if (!addCurrentFnArgument(MF, RegVar, Scope))
1196 addScopeVariable(Scope, RegVar);
1197 if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
1198 DbgVariableToDbgInstMap[AbsVar] = MInsn;
1199 VarToAbstractVarMap[RegVar] = AbsVar;
1202 // Simple ranges that are fully coalesced.
1203 if (History.size() <= 1 || (History.size() == 2 &&
1204 MInsn->isIdenticalTo(History.back()))) {
1205 DbgVariableToDbgInstMap[RegVar] = MInsn;
1209 // handle multiple DBG_VALUE instructions describing one variable.
1210 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1212 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1213 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1214 const MachineInstr *Begin = *HI;
1215 assert(Begin->isDebugValue() && "Invalid History entry");
1217 // Check if DBG_VALUE is truncating a range.
1218 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1219 && !Begin->getOperand(0).getReg())
1222 // Compute the range for a register location.
1223 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1224 const MCSymbol *SLabel = 0;
1227 // If Begin is the last instruction in History then its value is valid
1228 // until the end of the function.
1229 SLabel = FunctionEndSym;
1231 const MachineInstr *End = HI[1];
1232 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1233 << "\t" << *Begin << "\t" << *End << "\n");
1234 if (End->isDebugValue())
1235 SLabel = getLabelBeforeInsn(End);
1237 // End is a normal instruction clobbering the range.
1238 SLabel = getLabelAfterInsn(End);
1239 assert(SLabel && "Forgot label after clobber instruction");
1244 // The value is valid until the next DBG_VALUE or clobber.
1245 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1247 DotDebugLocEntries.push_back(DotDebugLocEntry());
1250 // Collect info for variables that were optimized out.
1251 const Function *F = MF->getFunction();
1252 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1253 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1254 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1255 if (!DV || !Processed.insert(DV))
1257 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1258 addScopeVariable(Scope, new DbgVariable(DV));
1263 /// getLabelBeforeInsn - Return Label preceding the instruction.
1264 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1265 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1266 assert(Label && "Didn't insert label before instruction");
1270 /// getLabelAfterInsn - Return Label immediately following the instruction.
1271 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1272 return LabelsAfterInsn.lookup(MI);
1275 /// beginInstruction - Process beginning of an instruction.
1276 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1277 // Check if source location changes, but ignore DBG_VALUE locations.
1278 if (!MI->isDebugValue()) {
1279 DebugLoc DL = MI->getDebugLoc();
1280 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1281 unsigned Flags = DWARF2_FLAG_IS_STMT;
1283 if (DL == PrologEndLoc) {
1284 Flags |= DWARF2_FLAG_PROLOGUE_END;
1285 PrologEndLoc = DebugLoc();
1287 if (!DL.isUnknown()) {
1288 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1289 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1291 recordSourceLine(0, 0, 0, 0);
1295 // Insert labels where requested.
1296 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1297 LabelsBeforeInsn.find(MI);
1300 if (I == LabelsBeforeInsn.end())
1303 // Label already assigned.
1308 PrevLabel = MMI->getContext().CreateTempSymbol();
1309 Asm->OutStreamer.EmitLabel(PrevLabel);
1311 I->second = PrevLabel;
1314 /// endInstruction - Process end of an instruction.
1315 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1316 // Don't create a new label after DBG_VALUE instructions.
1317 // They don't generate code.
1318 if (!MI->isDebugValue())
1321 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1322 LabelsAfterInsn.find(MI);
1325 if (I == LabelsAfterInsn.end())
1328 // Label already assigned.
1332 // We need a label after this instruction.
1334 PrevLabel = MMI->getContext().CreateTempSymbol();
1335 Asm->OutStreamer.EmitLabel(PrevLabel);
1337 I->second = PrevLabel;
1340 /// identifyScopeMarkers() -
1341 /// Each LexicalScope has first instruction and last instruction to mark
1342 /// beginning and end of a scope respectively. Create an inverse map that list
1343 /// scopes starts (and ends) with an instruction. One instruction may start (or
1344 /// end) multiple scopes. Ignore scopes that are not reachable.
1345 void DwarfDebug::identifyScopeMarkers() {
1346 SmallVector<LexicalScope *, 4> WorkList;
1347 WorkList.push_back(LScopes.getCurrentFunctionScope());
1348 while (!WorkList.empty()) {
1349 LexicalScope *S = WorkList.pop_back_val();
1351 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1352 if (!Children.empty())
1353 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1354 SE = Children.end(); SI != SE; ++SI)
1355 WorkList.push_back(*SI);
1357 if (S->isAbstractScope())
1360 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1363 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1364 RE = Ranges.end(); RI != RE; ++RI) {
1365 assert(RI->first && "InsnRange does not have first instruction!");
1366 assert(RI->second && "InsnRange does not have second instruction!");
1367 requestLabelBeforeInsn(RI->first);
1368 requestLabelAfterInsn(RI->second);
1373 /// getScopeNode - Get MDNode for DebugLoc's scope.
1374 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1375 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1376 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1377 return DL.getScope(Ctx);
1380 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1381 /// line number info for the function.
1382 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1383 const MDNode *Scope = getScopeNode(DL, Ctx);
1384 DISubprogram SP = getDISubprogram(Scope);
1386 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1390 /// beginFunction - Gather pre-function debug information. Assumes being
1391 /// emitted immediately after the function entry point.
1392 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1393 if (!MMI->hasDebugInfo()) return;
1394 LScopes.initialize(*MF);
1395 if (LScopes.empty()) return;
1396 identifyScopeMarkers();
1398 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1399 Asm->getFunctionNumber());
1400 // Assumes in correct section after the entry point.
1401 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1403 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1405 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1406 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1407 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1409 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1411 bool AtBlockEntry = true;
1412 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1414 const MachineInstr *MI = II;
1416 if (MI->isDebugValue()) {
1417 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1419 // Keep track of user variables.
1421 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1423 // Variable is in a register, we need to check for clobbers.
1424 if (isDbgValueInDefinedReg(MI))
1425 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1427 // Check the history of this variable.
1428 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1429 if (History.empty()) {
1430 UserVariables.push_back(Var);
1431 // The first mention of a function argument gets the FunctionBeginSym
1432 // label, so arguments are visible when breaking at function entry.
1434 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1435 DISubprogram(getDISubprogram(DV.getContext()))
1436 .describes(MF->getFunction()))
1437 LabelsBeforeInsn[MI] = FunctionBeginSym;
1439 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1440 const MachineInstr *Prev = History.back();
1441 if (Prev->isDebugValue()) {
1442 // Coalesce identical entries at the end of History.
1443 if (History.size() >= 2 &&
1444 Prev->isIdenticalTo(History[History.size() - 2])) {
1445 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1447 << "\t" << *History[History.size() - 2] << "\n");
1451 // Terminate old register assignments that don't reach MI;
1452 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1453 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1454 isDbgValueInDefinedReg(Prev)) {
1455 // Previous register assignment needs to terminate at the end of
1457 MachineBasicBlock::const_iterator LastMI =
1458 PrevMBB->getLastNonDebugInstr();
1459 if (LastMI == PrevMBB->end()) {
1460 // Drop DBG_VALUE for empty range.
1461 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1462 << "\t" << *Prev << "\n");
1466 // Terminate after LastMI.
1467 History.push_back(LastMI);
1472 History.push_back(MI);
1474 // Not a DBG_VALUE instruction.
1476 AtBlockEntry = false;
1478 // First known non DBG_VALUE location marks beginning of function
1480 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1481 PrologEndLoc = MI->getDebugLoc();
1483 // Check if the instruction clobbers any registers with debug vars.
1484 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1485 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1486 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1488 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1489 unsigned Reg = *AI; ++AI) {
1490 const MDNode *Var = LiveUserVar[Reg];
1493 // Reg is now clobbered.
1494 LiveUserVar[Reg] = 0;
1496 // Was MD last defined by a DBG_VALUE referring to Reg?
1497 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1498 if (HistI == DbgValues.end())
1500 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1501 if (History.empty())
1503 const MachineInstr *Prev = History.back();
1504 // Sanity-check: Register assignments are terminated at the end of
1506 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1508 // Is the variable still in Reg?
1509 if (!isDbgValueInDefinedReg(Prev) ||
1510 Prev->getOperand(0).getReg() != Reg)
1512 // Var is clobbered. Make sure the next instruction gets a label.
1513 History.push_back(MI);
1520 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1522 SmallVectorImpl<const MachineInstr*> &History = I->second;
1523 if (History.empty())
1526 // Make sure the final register assignments are terminated.
1527 const MachineInstr *Prev = History.back();
1528 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1529 const MachineBasicBlock *PrevMBB = Prev->getParent();
1530 MachineBasicBlock::const_iterator LastMI =
1531 PrevMBB->getLastNonDebugInstr();
1532 if (LastMI == PrevMBB->end())
1533 // Drop DBG_VALUE for empty range.
1536 // Terminate after LastMI.
1537 History.push_back(LastMI);
1540 // Request labels for the full history.
1541 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1542 const MachineInstr *MI = History[i];
1543 if (MI->isDebugValue())
1544 requestLabelBeforeInsn(MI);
1546 requestLabelAfterInsn(MI);
1550 PrevInstLoc = DebugLoc();
1551 PrevLabel = FunctionBeginSym;
1553 // Record beginning of function.
1554 if (!PrologEndLoc.isUnknown()) {
1555 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1556 MF->getFunction()->getContext());
1557 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1558 FnStartDL.getScope(MF->getFunction()->getContext()),
1559 DWARF2_FLAG_IS_STMT);
1563 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1564 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1565 ScopeVariables[LS].push_back(Var);
1566 // Vars.push_back(Var);
1569 /// endFunction - Gather and emit post-function debug information.
1571 void DwarfDebug::endFunction(const MachineFunction *MF) {
1572 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1574 // Define end label for subprogram.
1575 FunctionEndSym = Asm->GetTempSymbol("func_end",
1576 Asm->getFunctionNumber());
1577 // Assumes in correct section after the entry point.
1578 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1580 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1581 collectVariableInfo(MF, ProcessedVars);
1583 // Construct abstract scopes.
1584 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1585 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1586 LexicalScope *AScope = AList[i];
1587 DISubprogram SP(AScope->getScopeNode());
1589 // Collect info for variables that were optimized out.
1590 StringRef FName = SP.getLinkageName();
1592 FName = SP.getName();
1593 if (NamedMDNode *NMD =
1594 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
1595 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1596 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1597 if (!DV || !ProcessedVars.insert(DV))
1599 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1600 addScopeVariable(Scope, new DbgVariable(DV));
1604 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1605 constructScopeDIE(AScope);
1608 DIE *CurFnDIE = constructScopeDIE(LScopes.getCurrentFunctionScope());
1610 if (!DisableFramePointerElim(*MF)) {
1611 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1612 CompileUnit *TheCU = getCompileUnit(FnScope->getScopeNode());
1613 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1614 dwarf::DW_FORM_flag, 1);
1616 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1617 MMI->getFrameMoves()));
1620 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1621 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1622 DeleteContainerPointers(I->second);
1623 ScopeVariables.clear();
1624 DeleteContainerPointers(CurrentFnArguments);
1625 DbgVariableToFrameIndexMap.clear();
1626 VarToAbstractVarMap.clear();
1627 DbgVariableToDbgInstMap.clear();
1628 UserVariables.clear();
1630 AbstractVariables.clear();
1631 LabelsBeforeInsn.clear();
1632 LabelsAfterInsn.clear();
1636 /// recordVariableFrameIndex - Record a variable's index.
1637 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
1638 assert (V && "Invalid DbgVariable!");
1639 DbgVariableToFrameIndexMap[V] = Index;
1642 /// findVariableFrameIndex - Return true if frame index for the variable
1643 /// is found. Update FI to hold value of the index.
1644 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
1645 assert (V && "Invalid DbgVariable!");
1646 DenseMap<const DbgVariable *, int>::iterator I =
1647 DbgVariableToFrameIndexMap.find(V);
1648 if (I == DbgVariableToFrameIndexMap.end())
1654 /// recordSourceLine - Register a source line with debug info. Returns the
1655 /// unique label that was emitted and which provides correspondence to
1656 /// the source line list.
1657 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1663 DIDescriptor Scope(S);
1665 if (Scope.isCompileUnit()) {
1666 DICompileUnit CU(S);
1667 Fn = CU.getFilename();
1668 Dir = CU.getDirectory();
1669 } else if (Scope.isFile()) {
1671 Fn = F.getFilename();
1672 Dir = F.getDirectory();
1673 } else if (Scope.isSubprogram()) {
1675 Fn = SP.getFilename();
1676 Dir = SP.getDirectory();
1677 } else if (Scope.isLexicalBlock()) {
1678 DILexicalBlock DB(S);
1679 Fn = DB.getFilename();
1680 Dir = DB.getDirectory();
1682 assert(0 && "Unexpected scope info");
1684 Src = GetOrCreateSourceID(Fn, Dir);
1686 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1689 //===----------------------------------------------------------------------===//
1691 //===----------------------------------------------------------------------===//
1693 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1696 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1697 // Get the children.
1698 const std::vector<DIE *> &Children = Die->getChildren();
1700 // If not last sibling and has children then add sibling offset attribute.
1701 if (!Last && !Children.empty())
1702 Die->addSiblingOffset(DIEValueAllocator);
1704 // Record the abbreviation.
1705 assignAbbrevNumber(Die->getAbbrev());
1707 // Get the abbreviation for this DIE.
1708 unsigned AbbrevNumber = Die->getAbbrevNumber();
1709 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1712 Die->setOffset(Offset);
1714 // Start the size with the size of abbreviation code.
1715 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1717 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1718 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1720 // Size the DIE attribute values.
1721 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1722 // Size attribute value.
1723 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1725 // Size the DIE children if any.
1726 if (!Children.empty()) {
1727 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1728 "Children flag not set");
1730 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1731 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1733 // End of children marker.
1734 Offset += sizeof(int8_t);
1737 Die->setSize(Offset - Die->getOffset());
1741 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1743 void DwarfDebug::computeSizeAndOffsets() {
1744 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1745 E = CUMap.end(); I != E; ++I) {
1746 // Compute size of compile unit header.
1748 sizeof(int32_t) + // Length of Compilation Unit Info
1749 sizeof(int16_t) + // DWARF version number
1750 sizeof(int32_t) + // Offset Into Abbrev. Section
1751 sizeof(int8_t); // Pointer Size (in bytes)
1752 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1756 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1757 /// temporary label to it if SymbolStem is specified.
1758 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1759 const char *SymbolStem = 0) {
1760 Asm->OutStreamer.SwitchSection(Section);
1761 if (!SymbolStem) return 0;
1763 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1764 Asm->OutStreamer.EmitLabel(TmpSym);
1768 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1769 /// the start of each one.
1770 void DwarfDebug::EmitSectionLabels() {
1771 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1773 // Dwarf sections base addresses.
1774 DwarfInfoSectionSym =
1775 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1776 DwarfAbbrevSectionSym =
1777 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1778 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1780 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1781 EmitSectionSym(Asm, MacroInfo);
1783 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1784 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1785 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1786 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1787 DwarfStrSectionSym =
1788 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1789 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1792 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1793 "section_debug_loc");
1795 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1796 EmitSectionSym(Asm, TLOF.getDataSection());
1799 /// emitDIE - Recursively emits a debug information entry.
1801 void DwarfDebug::emitDIE(DIE *Die) {
1802 // Get the abbreviation for this DIE.
1803 unsigned AbbrevNumber = Die->getAbbrevNumber();
1804 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1806 // Emit the code (index) for the abbreviation.
1807 if (Asm->isVerbose())
1808 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1809 Twine::utohexstr(Die->getOffset()) + ":0x" +
1810 Twine::utohexstr(Die->getSize()) + " " +
1811 dwarf::TagString(Abbrev->getTag()));
1812 Asm->EmitULEB128(AbbrevNumber);
1814 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1815 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1817 // Emit the DIE attribute values.
1818 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1819 unsigned Attr = AbbrevData[i].getAttribute();
1820 unsigned Form = AbbrevData[i].getForm();
1821 assert(Form && "Too many attributes for DIE (check abbreviation)");
1823 if (Asm->isVerbose())
1824 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1827 case dwarf::DW_AT_sibling:
1828 Asm->EmitInt32(Die->getSiblingOffset());
1830 case dwarf::DW_AT_abstract_origin: {
1831 DIEEntry *E = cast<DIEEntry>(Values[i]);
1832 DIE *Origin = E->getEntry();
1833 unsigned Addr = Origin->getOffset();
1834 Asm->EmitInt32(Addr);
1837 case dwarf::DW_AT_ranges: {
1838 // DW_AT_range Value encodes offset in debug_range section.
1839 DIEInteger *V = cast<DIEInteger>(Values[i]);
1841 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1842 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1846 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1848 DwarfDebugRangeSectionSym,
1853 case dwarf::DW_AT_location: {
1854 if (UseDotDebugLocEntry.count(Die) != 0) {
1855 DIELabel *L = cast<DIELabel>(Values[i]);
1856 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1858 Values[i]->EmitValue(Asm, Form);
1861 case dwarf::DW_AT_accessibility: {
1862 if (Asm->isVerbose()) {
1863 DIEInteger *V = cast<DIEInteger>(Values[i]);
1864 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1866 Values[i]->EmitValue(Asm, Form);
1870 // Emit an attribute using the defined form.
1871 Values[i]->EmitValue(Asm, Form);
1876 // Emit the DIE children if any.
1877 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1878 const std::vector<DIE *> &Children = Die->getChildren();
1880 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1881 emitDIE(Children[j]);
1883 if (Asm->isVerbose())
1884 Asm->OutStreamer.AddComment("End Of Children Mark");
1889 /// emitDebugInfo - Emit the debug info section.
1891 void DwarfDebug::emitDebugInfo() {
1892 // Start debug info section.
1893 Asm->OutStreamer.SwitchSection(
1894 Asm->getObjFileLowering().getDwarfInfoSection());
1895 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1896 E = CUMap.end(); I != E; ++I) {
1897 CompileUnit *TheCU = I->second;
1898 DIE *Die = TheCU->getCUDie();
1900 // Emit the compile units header.
1901 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1904 // Emit size of content not including length itself
1905 unsigned ContentSize = Die->getSize() +
1906 sizeof(int16_t) + // DWARF version number
1907 sizeof(int32_t) + // Offset Into Abbrev. Section
1908 sizeof(int8_t); // Pointer Size (in bytes)
1910 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1911 Asm->EmitInt32(ContentSize);
1912 Asm->OutStreamer.AddComment("DWARF version number");
1913 Asm->EmitInt16(dwarf::DWARF_VERSION);
1914 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1915 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1916 DwarfAbbrevSectionSym);
1917 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1918 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1921 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1925 /// emitAbbreviations - Emit the abbreviation section.
1927 void DwarfDebug::emitAbbreviations() const {
1928 // Check to see if it is worth the effort.
1929 if (!Abbreviations.empty()) {
1930 // Start the debug abbrev section.
1931 Asm->OutStreamer.SwitchSection(
1932 Asm->getObjFileLowering().getDwarfAbbrevSection());
1934 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1936 // For each abbrevation.
1937 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1938 // Get abbreviation data
1939 const DIEAbbrev *Abbrev = Abbreviations[i];
1941 // Emit the abbrevations code (base 1 index.)
1942 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1944 // Emit the abbreviations data.
1948 // Mark end of abbreviations.
1949 Asm->EmitULEB128(0, "EOM(3)");
1951 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1955 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1956 /// the line matrix.
1958 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1959 // Define last address of section.
1960 Asm->OutStreamer.AddComment("Extended Op");
1963 Asm->OutStreamer.AddComment("Op size");
1964 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1965 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1966 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1968 Asm->OutStreamer.AddComment("Section end label");
1970 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1971 Asm->getTargetData().getPointerSize(),
1974 // Mark end of matrix.
1975 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1981 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1983 void DwarfDebug::emitDebugPubNames() {
1984 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1985 E = CUMap.end(); I != E; ++I) {
1986 CompileUnit *TheCU = I->second;
1987 // Start the dwarf pubnames section.
1988 Asm->OutStreamer.SwitchSection(
1989 Asm->getObjFileLowering().getDwarfPubNamesSection());
1991 Asm->OutStreamer.AddComment("Length of Public Names Info");
1992 Asm->EmitLabelDifference(
1993 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1994 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1996 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1999 Asm->OutStreamer.AddComment("DWARF Version");
2000 Asm->EmitInt16(dwarf::DWARF_VERSION);
2002 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2003 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2004 DwarfInfoSectionSym);
2006 Asm->OutStreamer.AddComment("Compilation Unit Length");
2007 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2008 Asm->GetTempSymbol("info_begin", TheCU->getID()),
2011 const StringMap<DIE*> &Globals = TheCU->getGlobals();
2012 for (StringMap<DIE*>::const_iterator
2013 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2014 const char *Name = GI->getKeyData();
2015 DIE *Entity = GI->second;
2017 Asm->OutStreamer.AddComment("DIE offset");
2018 Asm->EmitInt32(Entity->getOffset());
2020 if (Asm->isVerbose())
2021 Asm->OutStreamer.AddComment("External Name");
2022 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2025 Asm->OutStreamer.AddComment("End Mark");
2027 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
2032 void DwarfDebug::emitDebugPubTypes() {
2033 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2034 E = CUMap.end(); I != E; ++I) {
2035 CompileUnit *TheCU = I->second;
2036 // Start the dwarf pubnames section.
2037 Asm->OutStreamer.SwitchSection(
2038 Asm->getObjFileLowering().getDwarfPubTypesSection());
2039 Asm->OutStreamer.AddComment("Length of Public Types Info");
2040 Asm->EmitLabelDifference(
2041 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
2042 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
2044 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2047 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2048 Asm->EmitInt16(dwarf::DWARF_VERSION);
2050 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2051 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2052 DwarfInfoSectionSym);
2054 Asm->OutStreamer.AddComment("Compilation Unit Length");
2055 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2056 Asm->GetTempSymbol("info_begin", TheCU->getID()),
2059 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2060 for (StringMap<DIE*>::const_iterator
2061 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2062 const char *Name = GI->getKeyData();
2063 DIE *Entity = GI->second;
2065 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2066 Asm->EmitInt32(Entity->getOffset());
2068 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2069 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2072 Asm->OutStreamer.AddComment("End Mark");
2074 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2079 /// emitDebugStr - Emit visible names into a debug str section.
2081 void DwarfDebug::emitDebugStr() {
2082 // Check to see if it is worth the effort.
2083 if (StringPool.empty()) return;
2085 // Start the dwarf str section.
2086 Asm->OutStreamer.SwitchSection(
2087 Asm->getObjFileLowering().getDwarfStrSection());
2089 // Get all of the string pool entries and put them in an array by their ID so
2090 // we can sort them.
2091 SmallVector<std::pair<unsigned,
2092 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2094 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2095 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2096 Entries.push_back(std::make_pair(I->second.second, &*I));
2098 array_pod_sort(Entries.begin(), Entries.end());
2100 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2101 // Emit a label for reference from debug information entries.
2102 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2104 // Emit the string itself.
2105 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
2109 /// emitDebugLoc - Emit visible names into a debug loc section.
2111 void DwarfDebug::emitDebugLoc() {
2112 if (DotDebugLocEntries.empty())
2115 for (SmallVector<DotDebugLocEntry, 4>::iterator
2116 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2118 DotDebugLocEntry &Entry = *I;
2119 if (I + 1 != DotDebugLocEntries.end())
2123 // Start the dwarf loc section.
2124 Asm->OutStreamer.SwitchSection(
2125 Asm->getObjFileLowering().getDwarfLocSection());
2126 unsigned char Size = Asm->getTargetData().getPointerSize();
2127 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2129 for (SmallVector<DotDebugLocEntry, 4>::iterator
2130 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2131 I != E; ++I, ++index) {
2132 DotDebugLocEntry &Entry = *I;
2133 if (Entry.isMerged()) continue;
2134 if (Entry.isEmpty()) {
2135 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2136 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2137 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2139 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2140 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2141 DIVariable DV(Entry.Variable);
2142 Asm->OutStreamer.AddComment("Loc expr size");
2143 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2144 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2145 Asm->EmitLabelDifference(end, begin, 2);
2146 Asm->OutStreamer.EmitLabel(begin);
2147 if (Entry.isInt()) {
2148 DIBasicType BTy(DV.getType());
2150 (BTy.getEncoding() == dwarf::DW_ATE_signed
2151 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2152 Asm->OutStreamer.AddComment("DW_OP_consts");
2153 Asm->EmitInt8(dwarf::DW_OP_consts);
2154 Asm->EmitSLEB128(Entry.getInt());
2156 Asm->OutStreamer.AddComment("DW_OP_constu");
2157 Asm->EmitInt8(dwarf::DW_OP_constu);
2158 Asm->EmitULEB128(Entry.getInt());
2160 } else if (Entry.isLocation()) {
2161 if (!DV.hasComplexAddress())
2163 Asm->EmitDwarfRegOp(Entry.Loc);
2165 // Complex address entry.
2166 unsigned N = DV.getNumAddrElements();
2168 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2169 if (Entry.Loc.getOffset()) {
2171 Asm->EmitDwarfRegOp(Entry.Loc);
2172 Asm->OutStreamer.AddComment("DW_OP_deref");
2173 Asm->EmitInt8(dwarf::DW_OP_deref);
2174 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2175 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2176 Asm->EmitSLEB128(DV.getAddrElement(1));
2178 // If first address element is OpPlus then emit
2179 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2180 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2181 Asm->EmitDwarfRegOp(Loc);
2185 Asm->EmitDwarfRegOp(Entry.Loc);
2188 // Emit remaining complex address elements.
2189 for (; i < N; ++i) {
2190 uint64_t Element = DV.getAddrElement(i);
2191 if (Element == DIBuilder::OpPlus) {
2192 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2193 Asm->EmitULEB128(DV.getAddrElement(++i));
2194 } else if (Element == DIBuilder::OpDeref)
2195 Asm->EmitInt8(dwarf::DW_OP_deref);
2196 else llvm_unreachable("unknown Opcode found in complex address");
2200 // else ... ignore constant fp. There is not any good way to
2201 // to represent them here in dwarf.
2202 Asm->OutStreamer.EmitLabel(end);
2207 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2209 void DwarfDebug::EmitDebugARanges() {
2210 // Start the dwarf aranges section.
2211 Asm->OutStreamer.SwitchSection(
2212 Asm->getObjFileLowering().getDwarfARangesSection());
2215 /// emitDebugRanges - Emit visible names into a debug ranges section.
2217 void DwarfDebug::emitDebugRanges() {
2218 // Start the dwarf ranges section.
2219 Asm->OutStreamer.SwitchSection(
2220 Asm->getObjFileLowering().getDwarfRangesSection());
2221 unsigned char Size = Asm->getTargetData().getPointerSize();
2222 for (SmallVector<const MCSymbol *, 8>::iterator
2223 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2226 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2228 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2232 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2234 void DwarfDebug::emitDebugMacInfo() {
2235 if (const MCSection *LineInfo =
2236 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2237 // Start the dwarf macinfo section.
2238 Asm->OutStreamer.SwitchSection(LineInfo);
2242 /// emitDebugInlineInfo - Emit inline info using following format.
2244 /// 1. length of section
2245 /// 2. Dwarf version number
2246 /// 3. address size.
2248 /// Entries (one "entry" for each function that was inlined):
2250 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2251 /// otherwise offset into __debug_str for regular function name.
2252 /// 2. offset into __debug_str section for regular function name.
2253 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2254 /// instances for the function.
2256 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2257 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2258 /// __debug_info section, and the low_pc is the starting address for the
2259 /// inlining instance.
2260 void DwarfDebug::emitDebugInlineInfo() {
2261 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2267 Asm->OutStreamer.SwitchSection(
2268 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2270 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2271 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2272 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2274 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2276 Asm->OutStreamer.AddComment("Dwarf Version");
2277 Asm->EmitInt16(dwarf::DWARF_VERSION);
2278 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2279 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2281 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2282 E = InlinedSPNodes.end(); I != E; ++I) {
2284 const MDNode *Node = *I;
2285 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2286 = InlineInfo.find(Node);
2287 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2288 DISubprogram SP(Node);
2289 StringRef LName = SP.getLinkageName();
2290 StringRef Name = SP.getName();
2292 Asm->OutStreamer.AddComment("MIPS linkage name");
2293 if (LName.empty()) {
2294 Asm->OutStreamer.EmitBytes(Name, 0);
2295 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2297 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2298 DwarfStrSectionSym);
2300 Asm->OutStreamer.AddComment("Function name");
2301 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2302 Asm->EmitULEB128(Labels.size(), "Inline count");
2304 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2305 LE = Labels.end(); LI != LE; ++LI) {
2306 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2307 Asm->EmitInt32(LI->second->getOffset());
2309 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2310 Asm->OutStreamer.EmitSymbolValue(LI->first,
2311 Asm->getTargetData().getPointerSize(),0);
2315 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));