f97ddcb5a84e2186866fbe668fe9383ecf4a76d7
[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
827   // Emit initial sections so we can reference labels later.
828   emitSectionLabels();
829
830   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
831     DICompileUnit CUNode(CU_Nodes->getOperand(i));
832     CompileUnit *CU = constructCompileUnit(CUNode);
833     DIArray ImportedEntities = CUNode.getImportedEntities();
834     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
835       ScopesWithImportedEntities.push_back(std::make_pair(
836           DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
837           ImportedEntities.getElement(i)));
838     std::sort(ScopesWithImportedEntities.begin(),
839               ScopesWithImportedEntities.end(), less_first());
840     DIArray GVs = CUNode.getGlobalVariables();
841     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
842       CU->createGlobalVariableDIE(GVs.getElement(i));
843     DIArray SPs = CUNode.getSubprograms();
844     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
845       constructSubprogramDIE(CU, SPs.getElement(i));
846     DIArray EnumTypes = CUNode.getEnumTypes();
847     for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
848       CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
849     DIArray RetainedTypes = CUNode.getRetainedTypes();
850     for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
851       CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
852     // Emit imported_modules last so that the relevant context is already
853     // available.
854     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
855       constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
856   }
857
858   // Tell MMI that we have debug info.
859   MMI->setDebugInfoAvailability(true);
860
861   // Prime section data.
862   SectionMap.insert(Asm->getObjFileLowering().getTextSection());
863 }
864
865 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
866 void DwarfDebug::computeInlinedDIEs() {
867   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
868   for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
869          AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
870     DIE *ISP = *AI;
871     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
872   }
873   for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
874          AE = AbstractSPDies.end(); AI != AE; ++AI) {
875     DIE *ISP = AI->second;
876     if (InlinedSubprogramDIEs.count(ISP))
877       continue;
878     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
879   }
880 }
881
882 // Collect info for variables that were optimized out.
883 void DwarfDebug::collectDeadVariables() {
884   const Module *M = MMI->getModule();
885   DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
886
887   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
888     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
889       DICompileUnit TheCU(CU_Nodes->getOperand(i));
890       DIArray Subprograms = TheCU.getSubprograms();
891       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
892         DISubprogram SP(Subprograms.getElement(i));
893         if (ProcessedSPNodes.count(SP) != 0) continue;
894         if (!SP.isSubprogram()) continue;
895         if (!SP.isDefinition()) continue;
896         DIArray Variables = SP.getVariables();
897         if (Variables.getNumElements() == 0) continue;
898
899         LexicalScope *Scope =
900           new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
901         DeadFnScopeMap[SP] = Scope;
902
903         // Construct subprogram DIE and add variables DIEs.
904         CompileUnit *SPCU = CUMap.lookup(TheCU);
905         assert(SPCU && "Unable to find Compile Unit!");
906         constructSubprogramDIE(SPCU, SP);
907         DIE *ScopeDIE = SPCU->getDIE(SP);
908         for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
909           DIVariable DV(Variables.getElement(vi));
910           if (!DV.isVariable()) continue;
911           DbgVariable NewVar(DV, NULL);
912           if (DIE *VariableDIE =
913               SPCU->constructVariableDIE(&NewVar, Scope->isAbstractScope()))
914             ScopeDIE->addChild(VariableDIE);
915         }
916       }
917     }
918   }
919   DeleteContainerSeconds(DeadFnScopeMap);
920 }
921
922 // Type Signature [7.27] and ODR Hash code.
923
924 /// \brief Grabs the string in whichever attribute is passed in and returns
925 /// a reference to it. Returns "" if the attribute doesn't exist.
926 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
927   DIEValue *V = Die->findAttribute(Attr);
928
929   if (DIEString *S = dyn_cast_or_null<DIEString>(V))
930     return S->getString();
931
932   return StringRef("");
933 }
934
935 /// Return true if the current DIE is contained within an anonymous namespace.
936 static bool isContainedInAnonNamespace(DIE *Die) {
937   DIE *Parent = Die->getParent();
938
939   while (Parent) {
940     if (Parent->getTag() == dwarf::DW_TAG_namespace &&
941         getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
942       return true;
943     Parent = Parent->getParent();
944   }
945
946   return false;
947 }
948
949 /// Test if the current CU language is C++ and that we have
950 /// a named type that is not contained in an anonymous namespace.
951 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
952   return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
953          getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
954          !isContainedInAnonNamespace(Die);
955 }
956
957 void DwarfDebug::finalizeModuleInfo() {
958   // Collect info for variables that were optimized out.
959   collectDeadVariables();
960
961   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
962   computeInlinedDIEs();
963
964   // Split out type units and conditionally add an ODR tag to the split
965   // out type.
966   // FIXME: Do type splitting.
967   for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
968     DIE *Die = TypeUnits[i];
969     DIEHash Hash;
970     // If we've requested ODR hashes and it's applicable for an ODR hash then
971     // add the ODR signature now.
972     // FIXME: This should be added onto the type unit, not the type, but this
973     // works as an intermediate stage.
974     if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
975       CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
976                                      dwarf::DW_FORM_data8,
977                                      Hash.computeDIEODRSignature(Die));
978   }
979
980   // Handle anything that needs to be done on a per-cu basis.
981   for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
982                                                          CUE = CUMap.end();
983        CUI != CUE; ++CUI) {
984     CompileUnit *TheCU = CUI->second;
985     // Emit DW_AT_containing_type attribute to connect types with their
986     // vtable holding type.
987     TheCU->constructContainingTypeDIEs();
988
989     // If we're splitting the dwarf out now that we've got the entire
990     // CU then construct a skeleton CU based upon it.
991     if (useSplitDwarf()) {
992       uint64_t ID = 0;
993       if (GenerateCUHash) {
994         DIEHash CUHash;
995         ID = CUHash.computeCUSignature(TheCU->getCUDie());
996       }
997       // This should be a unique identifier when we want to build .dwp files.
998       TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
999                      dwarf::DW_FORM_data8, ID);
1000       // Now construct the skeleton CU associated.
1001       CompileUnit *SkCU = constructSkeletonCU(TheCU);
1002       // This should be a unique identifier when we want to build .dwp files.
1003       SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1004                     dwarf::DW_FORM_data8, ID);
1005     }
1006   }
1007
1008   // Compute DIE offsets and sizes.
1009   InfoHolder.computeSizeAndOffsets();
1010   if (useSplitDwarf())
1011     SkeletonHolder.computeSizeAndOffsets();
1012 }
1013
1014 void DwarfDebug::endSections() {
1015   // Standard sections final addresses.
1016   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1017   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1018   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1019   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1020
1021   // End text sections.
1022   for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
1023     Asm->OutStreamer.SwitchSection(SectionMap[I]);
1024     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
1025   }
1026 }
1027
1028 // Emit all Dwarf sections that should come after the content.
1029 void DwarfDebug::endModule() {
1030
1031   if (!FirstCU) return;
1032
1033   // End any existing sections.
1034   // TODO: Does this need to happen?
1035   endSections();
1036
1037   // Finalize the debug info for the module.
1038   finalizeModuleInfo();
1039
1040   if (!useSplitDwarf()) {
1041     // Emit all the DIEs into a debug info section.
1042     emitDebugInfo();
1043
1044     // Corresponding abbreviations into a abbrev section.
1045     emitAbbreviations();
1046
1047     // Emit info into a debug loc section.
1048     emitDebugLoc();
1049
1050     // Emit info into a debug aranges section.
1051     emitDebugARanges();
1052
1053     // Emit info into a debug ranges section.
1054     emitDebugRanges();
1055
1056     // Emit info into a debug macinfo section.
1057     emitDebugMacInfo();
1058
1059   } else {
1060     // TODO: Fill this in for separated debug sections and separate
1061     // out information into new sections.
1062
1063     // Emit the debug info section and compile units.
1064     emitDebugInfo();
1065     emitDebugInfoDWO();
1066
1067     // Corresponding abbreviations into a abbrev section.
1068     emitAbbreviations();
1069     emitDebugAbbrevDWO();
1070
1071     // Emit info into a debug loc section.
1072     emitDebugLoc();
1073
1074     // Emit info into a debug aranges section.
1075     emitDebugARanges();
1076
1077     // Emit info into a debug ranges section.
1078     emitDebugRanges();
1079
1080     // Emit info into a debug macinfo section.
1081     emitDebugMacInfo();
1082
1083     // Emit DWO addresses.
1084     InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1085
1086   }
1087
1088   // Emit info into the dwarf accelerator table sections.
1089   if (useDwarfAccelTables()) {
1090     emitAccelNames();
1091     emitAccelObjC();
1092     emitAccelNamespaces();
1093     emitAccelTypes();
1094   }
1095
1096   // Emit the pubnames and pubtypes sections if requested.
1097   if (HasDwarfPubSections) {
1098     emitDebugPubnames();
1099     emitDebugPubTypes();
1100   }
1101
1102   // Finally emit string information into a string table.
1103   emitDebugStr();
1104   if (useSplitDwarf())
1105     emitDebugStrDWO();
1106
1107   // clean up.
1108   SPMap.clear();
1109   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1110          E = CUMap.end(); I != E; ++I)
1111     delete I->second;
1112
1113   for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1114          E = SkeletonCUs.end(); I != E; ++I)
1115     delete *I;
1116
1117   // Reset these for the next Module if we have one.
1118   FirstCU = NULL;
1119 }
1120
1121 // Find abstract variable, if any, associated with Var.
1122 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1123                                               DebugLoc ScopeLoc) {
1124   LLVMContext &Ctx = DV->getContext();
1125   // More then one inlined variable corresponds to one abstract variable.
1126   DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1127   DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1128   if (AbsDbgVariable)
1129     return AbsDbgVariable;
1130
1131   LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1132   if (!Scope)
1133     return NULL;
1134
1135   AbsDbgVariable = new DbgVariable(Var, NULL);
1136   addScopeVariable(Scope, AbsDbgVariable);
1137   AbstractVariables[Var] = AbsDbgVariable;
1138   return AbsDbgVariable;
1139 }
1140
1141 // If Var is a current function argument then add it to CurrentFnArguments list.
1142 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1143                                       DbgVariable *Var, LexicalScope *Scope) {
1144   if (!LScopes.isCurrentFunctionScope(Scope))
1145     return false;
1146   DIVariable DV = Var->getVariable();
1147   if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1148     return false;
1149   unsigned ArgNo = DV.getArgNumber();
1150   if (ArgNo == 0)
1151     return false;
1152
1153   size_t Size = CurrentFnArguments.size();
1154   if (Size == 0)
1155     CurrentFnArguments.resize(MF->getFunction()->arg_size());
1156   // llvm::Function argument size is not good indicator of how many
1157   // arguments does the function have at source level.
1158   if (ArgNo > Size)
1159     CurrentFnArguments.resize(ArgNo * 2);
1160   CurrentFnArguments[ArgNo - 1] = Var;
1161   return true;
1162 }
1163
1164 // Collect variable information from side table maintained by MMI.
1165 void
1166 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1167                                    SmallPtrSet<const MDNode *, 16> &Processed) {
1168   MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1169   for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1170          VE = VMap.end(); VI != VE; ++VI) {
1171     const MDNode *Var = VI->first;
1172     if (!Var) continue;
1173     Processed.insert(Var);
1174     DIVariable DV(Var);
1175     const std::pair<unsigned, DebugLoc> &VP = VI->second;
1176
1177     LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1178
1179     // If variable scope is not found then skip this variable.
1180     if (Scope == 0)
1181       continue;
1182
1183     DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1184     DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1185     RegVar->setFrameIndex(VP.first);
1186     if (!addCurrentFnArgument(MF, RegVar, Scope))
1187       addScopeVariable(Scope, RegVar);
1188     if (AbsDbgVariable)
1189       AbsDbgVariable->setFrameIndex(VP.first);
1190   }
1191 }
1192
1193 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1194 // defined reg.
1195 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1196   assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1197   return MI->getNumOperands() == 3 &&
1198          MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1199          (MI->getOperand(1).isImm() ||
1200           (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1201 }
1202
1203 // Get .debug_loc entry for the instruction range starting at MI.
1204 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1205                                          const MCSymbol *FLabel,
1206                                          const MCSymbol *SLabel,
1207                                          const MachineInstr *MI) {
1208   const MDNode *Var =  MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1209
1210   assert(MI->getNumOperands() == 3);
1211   if (MI->getOperand(0).isReg()) {
1212     MachineLocation MLoc;
1213     // If the second operand is an immediate, this is a
1214     // register-indirect address.
1215     if (!MI->getOperand(1).isImm())
1216       MLoc.set(MI->getOperand(0).getReg());
1217     else
1218       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1219     return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1220   }
1221   if (MI->getOperand(0).isImm())
1222     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1223   if (MI->getOperand(0).isFPImm())
1224     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1225   if (MI->getOperand(0).isCImm())
1226     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1227
1228   llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1229 }
1230
1231 // Find variables for each lexical scope.
1232 void
1233 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1234                                 SmallPtrSet<const MDNode *, 16> &Processed) {
1235
1236   // Grab the variable info that was squirreled away in the MMI side-table.
1237   collectVariableInfoFromMMITable(MF, Processed);
1238
1239   for (SmallVectorImpl<const MDNode*>::const_iterator
1240          UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1241          ++UVI) {
1242     const MDNode *Var = *UVI;
1243     if (Processed.count(Var))
1244       continue;
1245
1246     // History contains relevant DBG_VALUE instructions for Var and instructions
1247     // clobbering it.
1248     SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1249     if (History.empty())
1250       continue;
1251     const MachineInstr *MInsn = History.front();
1252
1253     DIVariable DV(Var);
1254     LexicalScope *Scope = NULL;
1255     if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1256         DISubprogram(DV.getContext()).describes(MF->getFunction()))
1257       Scope = LScopes.getCurrentFunctionScope();
1258     else if (MDNode *IA = DV.getInlinedAt())
1259       Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1260     else
1261       Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1262     // If variable scope is not found then skip this variable.
1263     if (!Scope)
1264       continue;
1265
1266     Processed.insert(DV);
1267     assert(MInsn->isDebugValue() && "History must begin with debug value");
1268     DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1269     DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1270     if (!addCurrentFnArgument(MF, RegVar, Scope))
1271       addScopeVariable(Scope, RegVar);
1272     if (AbsVar)
1273       AbsVar->setMInsn(MInsn);
1274
1275     // Simplify ranges that are fully coalesced.
1276     if (History.size() <= 1 || (History.size() == 2 &&
1277                                 MInsn->isIdenticalTo(History.back()))) {
1278       RegVar->setMInsn(MInsn);
1279       continue;
1280     }
1281
1282     // Handle multiple DBG_VALUE instructions describing one variable.
1283     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1284
1285     for (SmallVectorImpl<const MachineInstr*>::const_iterator
1286            HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1287       const MachineInstr *Begin = *HI;
1288       assert(Begin->isDebugValue() && "Invalid History entry");
1289
1290       // Check if DBG_VALUE is truncating a range.
1291       if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1292           && !Begin->getOperand(0).getReg())
1293         continue;
1294
1295       // Compute the range for a register location.
1296       const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1297       const MCSymbol *SLabel = 0;
1298
1299       if (HI + 1 == HE)
1300         // If Begin is the last instruction in History then its value is valid
1301         // until the end of the function.
1302         SLabel = FunctionEndSym;
1303       else {
1304         const MachineInstr *End = HI[1];
1305         DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1306               << "\t" << *Begin << "\t" << *End << "\n");
1307         if (End->isDebugValue())
1308           SLabel = getLabelBeforeInsn(End);
1309         else {
1310           // End is a normal instruction clobbering the range.
1311           SLabel = getLabelAfterInsn(End);
1312           assert(SLabel && "Forgot label after clobber instruction");
1313           ++HI;
1314         }
1315       }
1316
1317       // The value is valid until the next DBG_VALUE or clobber.
1318       DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1319                                                     Begin));
1320     }
1321     DotDebugLocEntries.push_back(DotDebugLocEntry());
1322   }
1323
1324   // Collect info for variables that were optimized out.
1325   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1326   DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1327   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1328     DIVariable DV(Variables.getElement(i));
1329     if (!DV || !DV.isVariable() || !Processed.insert(DV))
1330       continue;
1331     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1332       addScopeVariable(Scope, new DbgVariable(DV, NULL));
1333   }
1334 }
1335
1336 // Return Label preceding the instruction.
1337 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1338   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1339   assert(Label && "Didn't insert label before instruction");
1340   return Label;
1341 }
1342
1343 // Return Label immediately following the instruction.
1344 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1345   return LabelsAfterInsn.lookup(MI);
1346 }
1347
1348 // Process beginning of an instruction.
1349 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1350   // Check if source location changes, but ignore DBG_VALUE locations.
1351   if (!MI->isDebugValue()) {
1352     DebugLoc DL = MI->getDebugLoc();
1353     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1354       unsigned Flags = 0;
1355       PrevInstLoc = DL;
1356       if (DL == PrologEndLoc) {
1357         Flags |= DWARF2_FLAG_PROLOGUE_END;
1358         PrologEndLoc = DebugLoc();
1359       }
1360       if (PrologEndLoc.isUnknown())
1361         Flags |= DWARF2_FLAG_IS_STMT;
1362
1363       if (!DL.isUnknown()) {
1364         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1365         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1366       } else
1367         recordSourceLine(0, 0, 0, 0);
1368     }
1369   }
1370
1371   // Insert labels where requested.
1372   DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1373     LabelsBeforeInsn.find(MI);
1374
1375   // No label needed.
1376   if (I == LabelsBeforeInsn.end())
1377     return;
1378
1379   // Label already assigned.
1380   if (I->second)
1381     return;
1382
1383   if (!PrevLabel) {
1384     PrevLabel = MMI->getContext().CreateTempSymbol();
1385     Asm->OutStreamer.EmitLabel(PrevLabel);
1386   }
1387   I->second = PrevLabel;
1388 }
1389
1390 // Process end of an instruction.
1391 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1392   // Don't create a new label after DBG_VALUE instructions.
1393   // They don't generate code.
1394   if (!MI->isDebugValue())
1395     PrevLabel = 0;
1396
1397   DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1398     LabelsAfterInsn.find(MI);
1399
1400   // No label needed.
1401   if (I == LabelsAfterInsn.end())
1402     return;
1403
1404   // Label already assigned.
1405   if (I->second)
1406     return;
1407
1408   // We need a label after this instruction.
1409   if (!PrevLabel) {
1410     PrevLabel = MMI->getContext().CreateTempSymbol();
1411     Asm->OutStreamer.EmitLabel(PrevLabel);
1412   }
1413   I->second = PrevLabel;
1414 }
1415
1416 // Each LexicalScope has first instruction and last instruction to mark
1417 // beginning and end of a scope respectively. Create an inverse map that list
1418 // scopes starts (and ends) with an instruction. One instruction may start (or
1419 // end) multiple scopes. Ignore scopes that are not reachable.
1420 void DwarfDebug::identifyScopeMarkers() {
1421   SmallVector<LexicalScope *, 4> WorkList;
1422   WorkList.push_back(LScopes.getCurrentFunctionScope());
1423   while (!WorkList.empty()) {
1424     LexicalScope *S = WorkList.pop_back_val();
1425
1426     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1427     if (!Children.empty())
1428       for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1429              SE = Children.end(); SI != SE; ++SI)
1430         WorkList.push_back(*SI);
1431
1432     if (S->isAbstractScope())
1433       continue;
1434
1435     const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1436     if (Ranges.empty())
1437       continue;
1438     for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1439            RE = Ranges.end(); RI != RE; ++RI) {
1440       assert(RI->first && "InsnRange does not have first instruction!");
1441       assert(RI->second && "InsnRange does not have second instruction!");
1442       requestLabelBeforeInsn(RI->first);
1443       requestLabelAfterInsn(RI->second);
1444     }
1445   }
1446 }
1447
1448 // Get MDNode for DebugLoc's scope.
1449 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1450   if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1451     return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1452   return DL.getScope(Ctx);
1453 }
1454
1455 // Walk up the scope chain of given debug loc and find line number info
1456 // for the function.
1457 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1458   const MDNode *Scope = getScopeNode(DL, Ctx);
1459   DISubprogram SP = getDISubprogram(Scope);
1460   if (SP.isSubprogram()) {
1461     // Check for number of operands since the compatibility is
1462     // cheap here.
1463     if (SP->getNumOperands() > 19)
1464       return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1465     else
1466       return DebugLoc::get(SP.getLineNumber(), 0, SP);
1467   }
1468
1469   return DebugLoc();
1470 }
1471
1472 // Gather pre-function debug information.  Assumes being called immediately
1473 // after the function entry point has been emitted.
1474 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1475   if (!MMI->hasDebugInfo()) return;
1476   LScopes.initialize(*MF);
1477   if (LScopes.empty()) return;
1478   identifyScopeMarkers();
1479
1480   // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1481   // belongs to.
1482   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1483   CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1484   assert(TheCU && "Unable to find compile unit!");
1485   if (Asm->TM.hasMCUseLoc() &&
1486       Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1487     // Use a single line table if we are using .loc and generating assembly.
1488     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1489   else
1490     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1491
1492   FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1493                                         Asm->getFunctionNumber());
1494   // Assumes in correct section after the entry point.
1495   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1496
1497   assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1498
1499   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1500   // LiveUserVar - Map physreg numbers to the MDNode they contain.
1501   std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1502
1503   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1504        I != E; ++I) {
1505     bool AtBlockEntry = true;
1506     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1507          II != IE; ++II) {
1508       const MachineInstr *MI = II;
1509
1510       if (MI->isDebugValue()) {
1511         assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1512
1513         // Keep track of user variables.
1514         const MDNode *Var =
1515           MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1516
1517         // Variable is in a register, we need to check for clobbers.
1518         if (isDbgValueInDefinedReg(MI))
1519           LiveUserVar[MI->getOperand(0).getReg()] = Var;
1520
1521         // Check the history of this variable.
1522         SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1523         if (History.empty()) {
1524           UserVariables.push_back(Var);
1525           // The first mention of a function argument gets the FunctionBeginSym
1526           // label, so arguments are visible when breaking at function entry.
1527           DIVariable DV(Var);
1528           if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1529               DISubprogram(getDISubprogram(DV.getContext()))
1530                 .describes(MF->getFunction()))
1531             LabelsBeforeInsn[MI] = FunctionBeginSym;
1532         } else {
1533           // We have seen this variable before. Try to coalesce DBG_VALUEs.
1534           const MachineInstr *Prev = History.back();
1535           if (Prev->isDebugValue()) {
1536             // Coalesce identical entries at the end of History.
1537             if (History.size() >= 2 &&
1538                 Prev->isIdenticalTo(History[History.size() - 2])) {
1539               DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1540                     << "\t" << *Prev
1541                     << "\t" << *History[History.size() - 2] << "\n");
1542               History.pop_back();
1543             }
1544
1545             // Terminate old register assignments that don't reach MI;
1546             MachineFunction::const_iterator PrevMBB = Prev->getParent();
1547             if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1548                 isDbgValueInDefinedReg(Prev)) {
1549               // Previous register assignment needs to terminate at the end of
1550               // its basic block.
1551               MachineBasicBlock::const_iterator LastMI =
1552                 PrevMBB->getLastNonDebugInstr();
1553               if (LastMI == PrevMBB->end()) {
1554                 // Drop DBG_VALUE for empty range.
1555                 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1556                       << "\t" << *Prev << "\n");
1557                 History.pop_back();
1558               } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1559                 // Terminate after LastMI.
1560                 History.push_back(LastMI);
1561             }
1562           }
1563         }
1564         History.push_back(MI);
1565       } else {
1566         // Not a DBG_VALUE instruction.
1567         if (!MI->isLabel())
1568           AtBlockEntry = false;
1569
1570         // First known non-DBG_VALUE and non-frame setup location marks
1571         // the beginning of the function body.
1572         if (!MI->getFlag(MachineInstr::FrameSetup) &&
1573             (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1574           PrologEndLoc = MI->getDebugLoc();
1575
1576         // Check if the instruction clobbers any registers with debug vars.
1577         for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1578                MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1579           if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1580             continue;
1581           for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1582                AI.isValid(); ++AI) {
1583             unsigned Reg = *AI;
1584             const MDNode *Var = LiveUserVar[Reg];
1585             if (!Var)
1586               continue;
1587             // Reg is now clobbered.
1588             LiveUserVar[Reg] = 0;
1589
1590             // Was MD last defined by a DBG_VALUE referring to Reg?
1591             DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1592             if (HistI == DbgValues.end())
1593               continue;
1594             SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1595             if (History.empty())
1596               continue;
1597             const MachineInstr *Prev = History.back();
1598             // Sanity-check: Register assignments are terminated at the end of
1599             // their block.
1600             if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1601               continue;
1602             // Is the variable still in Reg?
1603             if (!isDbgValueInDefinedReg(Prev) ||
1604                 Prev->getOperand(0).getReg() != Reg)
1605               continue;
1606             // Var is clobbered. Make sure the next instruction gets a label.
1607             History.push_back(MI);
1608           }
1609         }
1610       }
1611     }
1612   }
1613
1614   for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1615        I != E; ++I) {
1616     SmallVectorImpl<const MachineInstr*> &History = I->second;
1617     if (History.empty())
1618       continue;
1619
1620     // Make sure the final register assignments are terminated.
1621     const MachineInstr *Prev = History.back();
1622     if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1623       const MachineBasicBlock *PrevMBB = Prev->getParent();
1624       MachineBasicBlock::const_iterator LastMI =
1625         PrevMBB->getLastNonDebugInstr();
1626       if (LastMI == PrevMBB->end())
1627         // Drop DBG_VALUE for empty range.
1628         History.pop_back();
1629       else if (PrevMBB != &PrevMBB->getParent()->back()) {
1630         // Terminate after LastMI.
1631         History.push_back(LastMI);
1632       }
1633     }
1634     // Request labels for the full history.
1635     for (unsigned i = 0, e = History.size(); i != e; ++i) {
1636       const MachineInstr *MI = History[i];
1637       if (MI->isDebugValue())
1638         requestLabelBeforeInsn(MI);
1639       else
1640         requestLabelAfterInsn(MI);
1641     }
1642   }
1643
1644   PrevInstLoc = DebugLoc();
1645   PrevLabel = FunctionBeginSym;
1646
1647   // Record beginning of function.
1648   if (!PrologEndLoc.isUnknown()) {
1649     DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1650                                        MF->getFunction()->getContext());
1651     recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1652                      FnStartDL.getScope(MF->getFunction()->getContext()),
1653     // We'd like to list the prologue as "not statements" but GDB behaves
1654     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1655                      DWARF2_FLAG_IS_STMT);
1656   }
1657 }
1658
1659 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1660   SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1661   DIVariable DV = Var->getVariable();
1662   // Variables with positive arg numbers are parameters.
1663   if (unsigned ArgNum = DV.getArgNumber()) {
1664     // Keep all parameters in order at the start of the variable list to ensure
1665     // function types are correct (no out-of-order parameters)
1666     //
1667     // This could be improved by only doing it for optimized builds (unoptimized
1668     // builds have the right order to begin with), searching from the back (this
1669     // would catch the unoptimized case quickly), or doing a binary search
1670     // rather than linear search.
1671     SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1672     while (I != Vars.end()) {
1673       unsigned CurNum = (*I)->getVariable().getArgNumber();
1674       // A local (non-parameter) variable has been found, insert immediately
1675       // before it.
1676       if (CurNum == 0)
1677         break;
1678       // A later indexed parameter has been found, insert immediately before it.
1679       if (CurNum > ArgNum)
1680         break;
1681       ++I;
1682     }
1683     Vars.insert(I, Var);
1684     return;
1685   }
1686
1687   Vars.push_back(Var);
1688 }
1689
1690 // Gather and emit post-function debug information.
1691 void DwarfDebug::endFunction(const MachineFunction *MF) {
1692   if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1693
1694   // Define end label for subprogram.
1695   FunctionEndSym = Asm->GetTempSymbol("func_end",
1696                                       Asm->getFunctionNumber());
1697   // Assumes in correct section after the entry point.
1698   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1699   // Set DwarfCompileUnitID in MCContext to default value.
1700   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1701
1702   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1703   collectVariableInfo(MF, ProcessedVars);
1704
1705   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1706   CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1707   assert(TheCU && "Unable to find compile unit!");
1708
1709   // Construct abstract scopes.
1710   ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1711   for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1712     LexicalScope *AScope = AList[i];
1713     DISubprogram SP(AScope->getScopeNode());
1714     if (SP.isSubprogram()) {
1715       // Collect info for variables that were optimized out.
1716       DIArray Variables = SP.getVariables();
1717       for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1718         DIVariable DV(Variables.getElement(i));
1719         if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1720           continue;
1721         // Check that DbgVariable for DV wasn't created earlier, when
1722         // findAbstractVariable() was called for inlined instance of DV.
1723         LLVMContext &Ctx = DV->getContext();
1724         DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1725         if (AbstractVariables.lookup(CleanDV))
1726           continue;
1727         if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1728           addScopeVariable(Scope, new DbgVariable(DV, NULL));
1729       }
1730     }
1731     if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1732       constructScopeDIE(TheCU, AScope);
1733   }
1734
1735   DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1736
1737   if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1738     TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1739
1740   // Clear debug info
1741   for (ScopeVariablesMap::iterator
1742          I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1743     DeleteContainerPointers(I->second);
1744   ScopeVariables.clear();
1745   DeleteContainerPointers(CurrentFnArguments);
1746   UserVariables.clear();
1747   DbgValues.clear();
1748   AbstractVariables.clear();
1749   LabelsBeforeInsn.clear();
1750   LabelsAfterInsn.clear();
1751   PrevLabel = NULL;
1752 }
1753
1754 // Register a source line with debug info. Returns the  unique label that was
1755 // emitted and which provides correspondence to the source line list.
1756 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1757                                   unsigned Flags) {
1758   StringRef Fn;
1759   StringRef Dir;
1760   unsigned Src = 1;
1761   if (S) {
1762     DIDescriptor Scope(S);
1763
1764     if (Scope.isCompileUnit()) {
1765       DICompileUnit CU(S);
1766       Fn = CU.getFilename();
1767       Dir = CU.getDirectory();
1768     } else if (Scope.isFile()) {
1769       DIFile F(S);
1770       Fn = F.getFilename();
1771       Dir = F.getDirectory();
1772     } else if (Scope.isSubprogram()) {
1773       DISubprogram SP(S);
1774       Fn = SP.getFilename();
1775       Dir = SP.getDirectory();
1776     } else if (Scope.isLexicalBlockFile()) {
1777       DILexicalBlockFile DBF(S);
1778       Fn = DBF.getFilename();
1779       Dir = DBF.getDirectory();
1780     } else if (Scope.isLexicalBlock()) {
1781       DILexicalBlock DB(S);
1782       Fn = DB.getFilename();
1783       Dir = DB.getDirectory();
1784     } else
1785       llvm_unreachable("Unexpected scope info");
1786
1787     Src = getOrCreateSourceID(Fn, Dir,
1788             Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1789   }
1790   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1791 }
1792
1793 //===----------------------------------------------------------------------===//
1794 // Emit Methods
1795 //===----------------------------------------------------------------------===//
1796
1797 // Compute the size and offset of a DIE.
1798 unsigned
1799 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1800   // Get the children.
1801   const std::vector<DIE *> &Children = Die->getChildren();
1802
1803   // Record the abbreviation.
1804   assignAbbrevNumber(Die->getAbbrev());
1805
1806   // Get the abbreviation for this DIE.
1807   unsigned AbbrevNumber = Die->getAbbrevNumber();
1808   const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1809
1810   // Set DIE offset
1811   Die->setOffset(Offset);
1812
1813   // Start the size with the size of abbreviation code.
1814   Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1815
1816   const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1817   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1818
1819   // Size the DIE attribute values.
1820   for (unsigned i = 0, N = Values.size(); i < N; ++i)
1821     // Size attribute value.
1822     Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1823
1824   // Size the DIE children if any.
1825   if (!Children.empty()) {
1826     assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1827            "Children flag not set");
1828
1829     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1830       Offset = computeSizeAndOffset(Children[j], Offset);
1831
1832     // End of children marker.
1833     Offset += sizeof(int8_t);
1834   }
1835
1836   Die->setSize(Offset - Die->getOffset());
1837   return Offset;
1838 }
1839
1840 // Compute the size and offset of all the DIEs.
1841 void DwarfUnits::computeSizeAndOffsets() {
1842   // Offset from the beginning of debug info section.
1843   unsigned SecOffset = 0;
1844   for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1845          E = CUs.end(); I != E; ++I) {
1846     (*I)->setDebugInfoOffset(SecOffset);
1847     unsigned Offset =
1848       sizeof(int32_t) + // Length of Compilation Unit Info
1849       sizeof(int16_t) + // DWARF version number
1850       sizeof(int32_t) + // Offset Into Abbrev. Section
1851       sizeof(int8_t);   // Pointer Size (in bytes)
1852
1853     unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1854     SecOffset += EndOffset;
1855   }
1856 }
1857
1858 // Emit initial Dwarf sections with a label at the start of each one.
1859 void DwarfDebug::emitSectionLabels() {
1860   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1861
1862   // Dwarf sections base addresses.
1863   DwarfInfoSectionSym =
1864     emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1865   DwarfAbbrevSectionSym =
1866     emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1867   if (useSplitDwarf())
1868     DwarfAbbrevDWOSectionSym =
1869       emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1870                      "section_abbrev_dwo");
1871   emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1872
1873   if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1874     emitSectionSym(Asm, MacroInfo);
1875
1876   DwarfLineSectionSym =
1877     emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1878   emitSectionSym(Asm, TLOF.getDwarfLocSection());
1879   if (HasDwarfPubSections) {
1880     emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1881     emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1882   }
1883   DwarfStrSectionSym =
1884     emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1885   if (useSplitDwarf()) {
1886     DwarfStrDWOSectionSym =
1887       emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1888     DwarfAddrSectionSym =
1889       emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1890   }
1891   DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1892                                              "debug_range");
1893
1894   DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1895                                            "section_debug_loc");
1896
1897   TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1898   emitSectionSym(Asm, TLOF.getDataSection());
1899 }
1900
1901 // Recursively emits a debug information entry.
1902 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1903   // Get the abbreviation for this DIE.
1904   unsigned AbbrevNumber = Die->getAbbrevNumber();
1905   const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1906
1907   // Emit the code (index) for the abbreviation.
1908   if (Asm->isVerbose())
1909     Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1910                                 Twine::utohexstr(Die->getOffset()) + ":0x" +
1911                                 Twine::utohexstr(Die->getSize()) + " " +
1912                                 dwarf::TagString(Abbrev->getTag()));
1913   Asm->EmitULEB128(AbbrevNumber);
1914
1915   const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1916   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1917
1918   // Emit the DIE attribute values.
1919   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1920     unsigned Attr = AbbrevData[i].getAttribute();
1921     unsigned Form = AbbrevData[i].getForm();
1922     assert(Form && "Too many attributes for DIE (check abbreviation)");
1923
1924     if (Asm->isVerbose())
1925       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1926
1927     switch (Attr) {
1928     case dwarf::DW_AT_abstract_origin: {
1929       DIEEntry *E = cast<DIEEntry>(Values[i]);
1930       DIE *Origin = E->getEntry();
1931       unsigned Addr = Origin->getOffset();
1932       if (Form == dwarf::DW_FORM_ref_addr) {
1933         // For DW_FORM_ref_addr, output the offset from beginning of debug info
1934         // section. Origin->getOffset() returns the offset from start of the
1935         // compile unit.
1936         DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1937         Addr += Holder.getCUOffset(Origin->getCompileUnit());
1938       }
1939       Asm->OutStreamer.EmitIntValue(Addr,
1940           Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
1941       break;
1942     }
1943     case dwarf::DW_AT_ranges: {
1944       // DW_AT_range Value encodes offset in debug_range section.
1945       DIEInteger *V = cast<DIEInteger>(Values[i]);
1946
1947       if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1948         Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1949                                  V->getValue(),
1950                                  4);
1951       } else {
1952         Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1953                                        V->getValue(),
1954                                        DwarfDebugRangeSectionSym,
1955                                        4);
1956       }
1957       break;
1958     }
1959     case dwarf::DW_AT_location: {
1960       if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1961         if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1962           Asm->EmitLabelReference(L->getValue(), 4);
1963         else
1964           Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1965       } else {
1966         Values[i]->EmitValue(Asm, Form);
1967       }
1968       break;
1969     }
1970     case dwarf::DW_AT_accessibility: {
1971       if (Asm->isVerbose()) {
1972         DIEInteger *V = cast<DIEInteger>(Values[i]);
1973         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1974       }
1975       Values[i]->EmitValue(Asm, Form);
1976       break;
1977     }
1978     default:
1979       // Emit an attribute using the defined form.
1980       Values[i]->EmitValue(Asm, Form);
1981       break;
1982     }
1983   }
1984
1985   // Emit the DIE children if any.
1986   if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1987     const std::vector<DIE *> &Children = Die->getChildren();
1988
1989     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1990       emitDIE(Children[j], Abbrevs);
1991
1992     if (Asm->isVerbose())
1993       Asm->OutStreamer.AddComment("End Of Children Mark");
1994     Asm->EmitInt8(0);
1995   }
1996 }
1997
1998 // Emit the various dwarf units to the unit section USection with
1999 // the abbreviations going into ASection.
2000 void DwarfUnits::emitUnits(DwarfDebug *DD,
2001                            const MCSection *USection,
2002                            const MCSection *ASection,
2003                            const MCSymbol *ASectionSym) {
2004   Asm->OutStreamer.SwitchSection(USection);
2005   for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2006          E = CUs.end(); I != E; ++I) {
2007     CompileUnit *TheCU = *I;
2008     DIE *Die = TheCU->getCUDie();
2009
2010     // Emit the compile units header.
2011     Asm->OutStreamer
2012       .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2013                                     TheCU->getUniqueID()));
2014
2015     // Emit size of content not including length itself
2016     unsigned ContentSize = Die->getSize() +
2017       sizeof(int16_t) + // DWARF version number
2018       sizeof(int32_t) + // Offset Into Abbrev. Section
2019       sizeof(int8_t);   // Pointer Size (in bytes)
2020
2021     Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2022     Asm->EmitInt32(ContentSize);
2023     Asm->OutStreamer.AddComment("DWARF version number");
2024     Asm->EmitInt16(DD->getDwarfVersion());
2025     Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2026     Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2027                            ASectionSym);
2028     Asm->OutStreamer.AddComment("Address Size (in bytes)");
2029     Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2030
2031     DD->emitDIE(Die, Abbreviations);
2032     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2033                                                   TheCU->getUniqueID()));
2034   }
2035 }
2036
2037 /// For a given compile unit DIE, returns offset from beginning of debug info.
2038 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2039   assert(Die->getTag() == dwarf::DW_TAG_compile_unit  &&
2040          "Input DIE should be compile unit in getCUOffset.");
2041   for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
2042        I != E; ++I) {
2043     CompileUnit *TheCU = *I;
2044     if (TheCU->getCUDie() == Die)
2045       return TheCU->getDebugInfoOffset();
2046   }
2047   llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2048 }
2049
2050 // Emit the debug info section.
2051 void DwarfDebug::emitDebugInfo() {
2052   DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2053
2054   Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2055                    Asm->getObjFileLowering().getDwarfAbbrevSection(),
2056                    DwarfAbbrevSectionSym);
2057 }
2058
2059 // Emit the abbreviation section.
2060 void DwarfDebug::emitAbbreviations() {
2061   if (!useSplitDwarf())
2062     emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2063                 &Abbreviations);
2064   else
2065     emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2066 }
2067
2068 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2069                              std::vector<DIEAbbrev *> *Abbrevs) {
2070   // Check to see if it is worth the effort.
2071   if (!Abbrevs->empty()) {
2072     // Start the debug abbrev section.
2073     Asm->OutStreamer.SwitchSection(Section);
2074
2075     MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2076     Asm->OutStreamer.EmitLabel(Begin);
2077
2078     // For each abbrevation.
2079     for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2080       // Get abbreviation data
2081       const DIEAbbrev *Abbrev = Abbrevs->at(i);
2082
2083       // Emit the abbrevations code (base 1 index.)
2084       Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2085
2086       // Emit the abbreviations data.
2087       Abbrev->Emit(Asm);
2088     }
2089
2090     // Mark end of abbreviations.
2091     Asm->EmitULEB128(0, "EOM(3)");
2092
2093     MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2094     Asm->OutStreamer.EmitLabel(End);
2095   }
2096 }
2097
2098 // Emit the last address of the section and the end of the line matrix.
2099 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2100   // Define last address of section.
2101   Asm->OutStreamer.AddComment("Extended Op");
2102   Asm->EmitInt8(0);
2103
2104   Asm->OutStreamer.AddComment("Op size");
2105   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2106   Asm->OutStreamer.AddComment("DW_LNE_set_address");
2107   Asm->EmitInt8(dwarf::DW_LNE_set_address);
2108
2109   Asm->OutStreamer.AddComment("Section end label");
2110
2111   Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2112                                    Asm->getDataLayout().getPointerSize());
2113
2114   // Mark end of matrix.
2115   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2116   Asm->EmitInt8(0);
2117   Asm->EmitInt8(1);
2118   Asm->EmitInt8(1);
2119 }
2120
2121 // Emit visible names into a hashed accelerator table section.
2122 void DwarfDebug::emitAccelNames() {
2123   DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2124                                            dwarf::DW_FORM_data4));
2125   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2126          E = CUMap.end(); I != E; ++I) {
2127     CompileUnit *TheCU = I->second;
2128     const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2129     for (StringMap<std::vector<DIE*> >::const_iterator
2130            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2131       StringRef Name = GI->getKey();
2132       const std::vector<DIE *> &Entities = GI->second;
2133       for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2134              DE = Entities.end(); DI != DE; ++DI)
2135         AT.AddName(Name, (*DI));
2136     }
2137   }
2138
2139   AT.FinalizeTable(Asm, "Names");
2140   Asm->OutStreamer.SwitchSection(
2141     Asm->getObjFileLowering().getDwarfAccelNamesSection());
2142   MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2143   Asm->OutStreamer.EmitLabel(SectionBegin);
2144
2145   // Emit the full data.
2146   AT.Emit(Asm, SectionBegin, &InfoHolder);
2147 }
2148
2149 // Emit objective C classes and categories into a hashed accelerator table
2150 // section.
2151 void DwarfDebug::emitAccelObjC() {
2152   DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2153                                            dwarf::DW_FORM_data4));
2154   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2155          E = CUMap.end(); I != E; ++I) {
2156     CompileUnit *TheCU = I->second;
2157     const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2158     for (StringMap<std::vector<DIE*> >::const_iterator
2159            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2160       StringRef Name = GI->getKey();
2161       const std::vector<DIE *> &Entities = GI->second;
2162       for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2163              DE = Entities.end(); DI != DE; ++DI)
2164         AT.AddName(Name, (*DI));
2165     }
2166   }
2167
2168   AT.FinalizeTable(Asm, "ObjC");
2169   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2170                                  .getDwarfAccelObjCSection());
2171   MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2172   Asm->OutStreamer.EmitLabel(SectionBegin);
2173
2174   // Emit the full data.
2175   AT.Emit(Asm, SectionBegin, &InfoHolder);
2176 }
2177
2178 // Emit namespace dies into a hashed accelerator table.
2179 void DwarfDebug::emitAccelNamespaces() {
2180   DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2181                                            dwarf::DW_FORM_data4));
2182   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2183          E = CUMap.end(); I != E; ++I) {
2184     CompileUnit *TheCU = I->second;
2185     const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2186     for (StringMap<std::vector<DIE*> >::const_iterator
2187            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2188       StringRef Name = GI->getKey();
2189       const std::vector<DIE *> &Entities = GI->second;
2190       for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2191              DE = Entities.end(); DI != DE; ++DI)
2192         AT.AddName(Name, (*DI));
2193     }
2194   }
2195
2196   AT.FinalizeTable(Asm, "namespac");
2197   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2198                                  .getDwarfAccelNamespaceSection());
2199   MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2200   Asm->OutStreamer.EmitLabel(SectionBegin);
2201
2202   // Emit the full data.
2203   AT.Emit(Asm, SectionBegin, &InfoHolder);
2204 }
2205
2206 // Emit type dies into a hashed accelerator table.
2207 void DwarfDebug::emitAccelTypes() {
2208   std::vector<DwarfAccelTable::Atom> Atoms;
2209   Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2210                                         dwarf::DW_FORM_data4));
2211   Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag,
2212                                         dwarf::DW_FORM_data2));
2213   Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags,
2214                                         dwarf::DW_FORM_data1));
2215   DwarfAccelTable AT(Atoms);
2216   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2217          E = CUMap.end(); I != E; ++I) {
2218     CompileUnit *TheCU = I->second;
2219     const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2220       = TheCU->getAccelTypes();
2221     for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2222            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2223       StringRef Name = GI->getKey();
2224       const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2225       for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2226              = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2227         AT.AddName(Name, (*DI).first, (*DI).second);
2228     }
2229   }
2230
2231   AT.FinalizeTable(Asm, "types");
2232   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2233                                  .getDwarfAccelTypesSection());
2234   MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2235   Asm->OutStreamer.EmitLabel(SectionBegin);
2236
2237   // Emit the full data.
2238   AT.Emit(Asm, SectionBegin, &InfoHolder);
2239 }
2240
2241 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2242 ///
2243 void DwarfDebug::emitDebugPubnames() {
2244   const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2245
2246   typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2247   for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2248     CompileUnit *TheCU = I->second;
2249     unsigned ID = TheCU->getUniqueID();
2250
2251     if (TheCU->getGlobalNames().empty())
2252       continue;
2253
2254     // Start the dwarf pubnames section.
2255     Asm->OutStreamer
2256         .SwitchSection(Asm->getObjFileLowering().getDwarfPubNamesSection());
2257
2258     Asm->OutStreamer.AddComment("Length of Public Names Info");
2259     Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2260                              Asm->GetTempSymbol("pubnames_begin", ID), 4);
2261
2262     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2263
2264     Asm->OutStreamer.AddComment("DWARF Version");
2265     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2266
2267     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2268     Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2269                            DwarfInfoSectionSym);
2270
2271     Asm->OutStreamer.AddComment("Compilation Unit Length");
2272     Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2273                              Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2274                              4);
2275
2276     const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2277     for (StringMap<DIE*>::const_iterator
2278            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2279       const char *Name = GI->getKeyData();
2280       const DIE *Entity = GI->second;
2281
2282       Asm->OutStreamer.AddComment("DIE offset");
2283       Asm->EmitInt32(Entity->getOffset());
2284
2285       if (Asm->isVerbose())
2286         Asm->OutStreamer.AddComment("External Name");
2287       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2288     }
2289
2290     Asm->OutStreamer.AddComment("End Mark");
2291     Asm->EmitInt32(0);
2292     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2293   }
2294 }
2295
2296 void DwarfDebug::emitDebugPubTypes() {
2297   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2298          E = CUMap.end(); I != E; ++I) {
2299     CompileUnit *TheCU = I->second;
2300     // Start the dwarf pubtypes section.
2301     Asm->OutStreamer.SwitchSection(
2302       Asm->getObjFileLowering().getDwarfPubTypesSection());
2303     Asm->OutStreamer.AddComment("Length of Public Types Info");
2304     Asm->EmitLabelDifference(
2305       Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2306       Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2307
2308     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2309                                                   TheCU->getUniqueID()));
2310
2311     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2312     Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2313
2314     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2315     const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2316     Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2317                                               TheCU->getUniqueID()),
2318                            DwarfInfoSectionSym);
2319
2320     Asm->OutStreamer.AddComment("Compilation Unit Length");
2321     Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2322                                                 TheCU->getUniqueID()),
2323                              Asm->GetTempSymbol(ISec->getLabelBeginName(),
2324                                                 TheCU->getUniqueID()),
2325                              4);
2326
2327     const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2328     for (StringMap<DIE*>::const_iterator
2329            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2330       const char *Name = GI->getKeyData();
2331       DIE *Entity = GI->second;
2332
2333       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2334       Asm->EmitInt32(Entity->getOffset());
2335
2336       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2337       // Emit the name with a terminating null byte.
2338       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2339     }
2340
2341     Asm->OutStreamer.AddComment("End Mark");
2342     Asm->EmitInt32(0);
2343     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2344                                                   TheCU->getUniqueID()));
2345   }
2346 }
2347
2348 // Emit strings into a string section.
2349 void DwarfUnits::emitStrings(const MCSection *StrSection,
2350                              const MCSection *OffsetSection = NULL,
2351                              const MCSymbol *StrSecSym = NULL) {
2352
2353   if (StringPool.empty()) return;
2354
2355   // Start the dwarf str section.
2356   Asm->OutStreamer.SwitchSection(StrSection);
2357
2358   // Get all of the string pool entries and put them in an array by their ID so
2359   // we can sort them.
2360   SmallVector<std::pair<unsigned,
2361                  StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2362
2363   for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2364          I = StringPool.begin(), E = StringPool.end();
2365        I != E; ++I)
2366     Entries.push_back(std::make_pair(I->second.second, &*I));
2367
2368   array_pod_sort(Entries.begin(), Entries.end());
2369
2370   for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2371     // Emit a label for reference from debug information entries.
2372     Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2373
2374     // Emit the string itself with a terminating null byte.
2375     Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2376                                          Entries[i].second->getKeyLength()+1));
2377   }
2378
2379   // If we've got an offset section go ahead and emit that now as well.
2380   if (OffsetSection) {
2381     Asm->OutStreamer.SwitchSection(OffsetSection);
2382     unsigned offset = 0;
2383     unsigned size = 4; // FIXME: DWARF64 is 8.
2384     for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2385       Asm->OutStreamer.EmitIntValue(offset, size);
2386       offset += Entries[i].second->getKeyLength() + 1;
2387     }
2388   }
2389 }
2390
2391 // Emit strings into a string section.
2392 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2393
2394   if (AddressPool.empty()) return;
2395
2396   // Start the dwarf addr section.
2397   Asm->OutStreamer.SwitchSection(AddrSection);
2398
2399   // Order the address pool entries by ID
2400   SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2401
2402   for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2403                                                     E = AddressPool.end();
2404        I != E; ++I)
2405     Entries[I->second] = I->first;
2406
2407   for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2408     // Emit an expression for reference from debug information entries.
2409     if (const MCExpr *Expr = Entries[i])
2410       Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2411     else
2412       Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2413   }
2414
2415 }
2416
2417 // Emit visible names into a debug str section.
2418 void DwarfDebug::emitDebugStr() {
2419   DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2420   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2421 }
2422
2423 // Emit locations into the debug loc section.
2424 void DwarfDebug::emitDebugLoc() {
2425   if (DotDebugLocEntries.empty())
2426     return;
2427
2428   for (SmallVectorImpl<DotDebugLocEntry>::iterator
2429          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2430        I != E; ++I) {
2431     DotDebugLocEntry &Entry = *I;
2432     if (I + 1 != DotDebugLocEntries.end())
2433       Entry.Merge(I+1);
2434   }
2435
2436   // Start the dwarf loc section.
2437   Asm->OutStreamer.SwitchSection(
2438     Asm->getObjFileLowering().getDwarfLocSection());
2439   unsigned char Size = Asm->getDataLayout().getPointerSize();
2440   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2441   unsigned index = 1;
2442   for (SmallVectorImpl<DotDebugLocEntry>::iterator
2443          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2444        I != E; ++I, ++index) {
2445     DotDebugLocEntry &Entry = *I;
2446     if (Entry.isMerged()) continue;
2447     if (Entry.isEmpty()) {
2448       Asm->OutStreamer.EmitIntValue(0, Size);
2449       Asm->OutStreamer.EmitIntValue(0, Size);
2450       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2451     } else {
2452       Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2453       Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2454       DIVariable DV(Entry.getVariable());
2455       Asm->OutStreamer.AddComment("Loc expr size");
2456       MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2457       MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2458       Asm->EmitLabelDifference(end, begin, 2);
2459       Asm->OutStreamer.EmitLabel(begin);
2460       if (Entry.isInt()) {
2461         DIBasicType BTy(DV.getType());
2462         if (BTy.Verify() &&
2463             (BTy.getEncoding()  == dwarf::DW_ATE_signed
2464              || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2465           Asm->OutStreamer.AddComment("DW_OP_consts");
2466           Asm->EmitInt8(dwarf::DW_OP_consts);
2467           Asm->EmitSLEB128(Entry.getInt());
2468         } else {
2469           Asm->OutStreamer.AddComment("DW_OP_constu");
2470           Asm->EmitInt8(dwarf::DW_OP_constu);
2471           Asm->EmitULEB128(Entry.getInt());
2472         }
2473       } else if (Entry.isLocation()) {
2474         MachineLocation Loc = Entry.getLoc();
2475         if (!DV.hasComplexAddress())
2476           // Regular entry.
2477           Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2478         else {
2479           // Complex address entry.
2480           unsigned N = DV.getNumAddrElements();
2481           unsigned i = 0;
2482           if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2483             if (Loc.getOffset()) {
2484               i = 2;
2485               Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2486               Asm->OutStreamer.AddComment("DW_OP_deref");
2487               Asm->EmitInt8(dwarf::DW_OP_deref);
2488               Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2489               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2490               Asm->EmitSLEB128(DV.getAddrElement(1));
2491             } else {
2492               // If first address element is OpPlus then emit
2493               // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2494               MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2495               Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2496               i = 2;
2497             }
2498           } else {
2499             Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2500           }
2501
2502           // Emit remaining complex address elements.
2503           for (; i < N; ++i) {
2504             uint64_t Element = DV.getAddrElement(i);
2505             if (Element == DIBuilder::OpPlus) {
2506               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2507               Asm->EmitULEB128(DV.getAddrElement(++i));
2508             } else if (Element == DIBuilder::OpDeref) {
2509               if (!Loc.isReg())
2510                 Asm->EmitInt8(dwarf::DW_OP_deref);
2511             } else
2512               llvm_unreachable("unknown Opcode found in complex address");
2513           }
2514         }
2515       }
2516       // else ... ignore constant fp. There is not any good way to
2517       // to represent them here in dwarf.
2518       Asm->OutStreamer.EmitLabel(end);
2519     }
2520   }
2521 }
2522
2523 // Emit visible names into a debug aranges section.
2524 void DwarfDebug::emitDebugARanges() {
2525   // Start the dwarf aranges section.
2526   Asm->OutStreamer
2527       .SwitchSection(Asm->getObjFileLowering().getDwarfARangesSection());
2528 }
2529
2530 // Emit visible names into a debug ranges section.
2531 void DwarfDebug::emitDebugRanges() {
2532   // Start the dwarf ranges section.
2533   Asm->OutStreamer
2534       .SwitchSection(Asm->getObjFileLowering().getDwarfRangesSection());
2535   unsigned char Size = Asm->getDataLayout().getPointerSize();
2536   for (SmallVectorImpl<const MCSymbol *>::iterator
2537          I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2538        I != E; ++I) {
2539     if (*I)
2540       Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2541     else
2542       Asm->OutStreamer.EmitIntValue(0, Size);
2543   }
2544 }
2545
2546 // Emit visible names into a debug macinfo section.
2547 void DwarfDebug::emitDebugMacInfo() {
2548   if (const MCSection *LineInfo =
2549       Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2550     // Start the dwarf macinfo section.
2551     Asm->OutStreamer.SwitchSection(LineInfo);
2552   }
2553 }
2554
2555 // DWARF5 Experimental Separate Dwarf emitters.
2556
2557 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2558 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2559 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2560 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2561 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2562
2563   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2564   CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2565                                        Asm, this, &SkeletonHolder);
2566
2567   NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2568                         DICompileUnit(CU->getNode()).getSplitDebugFilename());
2569
2570   // Relocate to the beginning of the addr_base section, else 0 for the
2571   // beginning of the one for this compile unit.
2572   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2573     NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2574                     DwarfAddrSectionSym);
2575   else
2576     NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2577                    dwarf::DW_FORM_sec_offset, 0);
2578
2579   // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2580   // into an entity. We're using 0, or a NULL label for this.
2581   NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2582
2583   // DW_AT_stmt_list is a offset of line number information for this
2584   // compile unit in debug_line section.
2585   // FIXME: Should handle multiple compile units.
2586   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2587     NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2588                     DwarfLineSectionSym);
2589   else
2590     NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2591
2592   if (!CompilationDir.empty())
2593     NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2594
2595   SkeletonHolder.addUnit(NewCU);
2596   SkeletonCUs.push_back(NewCU);
2597
2598   return NewCU;
2599 }
2600
2601 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2602   assert(useSplitDwarf() && "No split dwarf debug info?");
2603   emitAbbrevs(Section, &SkeletonAbbrevs);
2604 }
2605
2606 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2607 // compile units that would normally be in debug_info.
2608 void DwarfDebug::emitDebugInfoDWO() {
2609   assert(useSplitDwarf() && "No split dwarf debug info?");
2610   InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2611                        Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2612                        DwarfAbbrevDWOSectionSym);
2613 }
2614
2615 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2616 // abbreviations for the .debug_info.dwo section.
2617 void DwarfDebug::emitDebugAbbrevDWO() {
2618   assert(useSplitDwarf() && "No split dwarf?");
2619   emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2620               &Abbreviations);
2621 }
2622
2623 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2624 // string section and is identical in format to traditional .debug_str
2625 // sections.
2626 void DwarfDebug::emitDebugStrDWO() {
2627   assert(useSplitDwarf() && "No split dwarf?");
2628   const MCSection *OffSec = Asm->getObjFileLowering()
2629                             .getDwarfStrOffDWOSection();
2630   const MCSymbol *StrSym = DwarfStrSectionSym;
2631   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2632                          OffSec, StrSym);
2633 }