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