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