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