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