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