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