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