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