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