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