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