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