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