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