Whitespace and 80-column cleanup.
[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 "DwarfAccelTable.h"
18 #include "DwarfCompileUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DIBuilder.h"
27 #include "llvm/DataLayout.h"
28 #include "llvm/DebugInfo.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Module.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Target/TargetFrameLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 using namespace llvm;
48
49 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
50                                               cl::Hidden,
51      cl::desc("Disable debug info printing"));
52
53 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
54      cl::desc("Make an absence of debug location information explicit."),
55      cl::init(false));
56
57 namespace {
58   enum DefaultOnOff {
59     Default, Enable, Disable
60   };
61 }
62
63 static cl::opt<DefaultOnOff> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
64      cl::desc("Output prototype dwarf accelerator tables."),
65      cl::values(
66                 clEnumVal(Default, "Default for platform"),
67                 clEnumVal(Enable, "Enabled"),
68                 clEnumVal(Disable, "Disabled"),
69                 clEnumValEnd),
70      cl::init(Default));
71
72 static cl::opt<DefaultOnOff> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
73      cl::desc("Compatibility with Darwin gdb."),
74      cl::values(
75                 clEnumVal(Default, "Default for platform"),
76                 clEnumVal(Enable, "Enabled"),
77                 clEnumVal(Disable, "Disabled"),
78                 clEnumValEnd),
79      cl::init(Default));
80
81 static cl::opt<DefaultOnOff> SplitDwarf("split-dwarf", cl::Hidden,
82      cl::desc("Output prototype dwarf split debug info."),
83      cl::values(
84                 clEnumVal(Default, "Default for platform"),
85                 clEnumVal(Enable, "Enabled"),
86                 clEnumVal(Disable, "Disabled"),
87                 clEnumValEnd),
88      cl::init(Default));
89
90 namespace {
91   const char *DWARFGroupName = "DWARF Emission";
92   const char *DbgTimerName = "DWARF Debug Writer";
93 } // end anonymous namespace
94
95 //===----------------------------------------------------------------------===//
96
97 // Configuration values for initial hash set sizes (log2).
98 //
99 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
100
101 namespace llvm {
102
103 DIType DbgVariable::getType() const {
104   DIType Ty = Var.getType();
105   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
106   // addresses instead.
107   if (Var.isBlockByrefVariable()) {
108     /* Byref variables, in Blocks, are declared by the programmer as
109        "SomeType VarName;", but the compiler creates a
110        __Block_byref_x_VarName struct, and gives the variable VarName
111        either the struct, or a pointer to the struct, as its type.  This
112        is necessary for various behind-the-scenes things the compiler
113        needs to do with by-reference variables in blocks.
114
115        However, as far as the original *programmer* is concerned, the
116        variable should still have type 'SomeType', as originally declared.
117
118        The following function dives into the __Block_byref_x_VarName
119        struct to find the original type of the variable.  This will be
120        passed back to the code generating the type for the Debug
121        Information Entry for the variable 'VarName'.  'VarName' will then
122        have the original type 'SomeType' in its debug information.
123
124        The original type 'SomeType' will be the type of the field named
125        'VarName' inside the __Block_byref_x_VarName struct.
126
127        NOTE: In order for this to not completely fail on the debugger
128        side, the Debug Information Entry for the variable VarName needs to
129        have a DW_AT_location that tells the debugger how to unwind through
130        the pointers and __Block_byref_x_VarName struct to find the actual
131        value of the variable.  The function addBlockByrefType does this.  */
132     DIType subType = Ty;
133     unsigned tag = Ty.getTag();
134
135     if (tag == dwarf::DW_TAG_pointer_type) {
136       DIDerivedType DTy = DIDerivedType(Ty);
137       subType = DTy.getTypeDerivedFrom();
138     }
139
140     DICompositeType blockStruct = DICompositeType(subType);
141     DIArray Elements = blockStruct.getTypeArray();
142
143     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
144       DIDescriptor Element = Elements.getElement(i);
145       DIDerivedType DT = DIDerivedType(Element);
146       if (getName() == DT.getName())
147         return (DT.getTypeDerivedFrom());
148     }
149   }
150   return Ty;
151 }
152
153 } // end llvm namespace
154
155 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
156   : Asm(A), MMI(Asm->MMI), FirstCU(0),
157     AbbreviationsSet(InitAbbreviationsSetSize),
158     SourceIdMap(DIEValueAllocator), InfoStringPool(DIEValueAllocator),
159     PrevLabel(NULL), GlobalCUIndexCount(0),
160     InfoHolder(A, &AbbreviationsSet, &Abbreviations, &InfoStringPool),
161     SkeletonCU(0),
162     SkeletonAbbrevSet(InitAbbreviationsSetSize),
163     SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, &InfoStringPool) {
164
165   DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
166   DwarfStrSectionSym = TextSectionSym = 0;
167   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
168   DwarfAbbrevDWOSectionSym = 0;
169   FunctionBeginSym = FunctionEndSym = 0;
170
171   // Turn on accelerator tables and older gdb compatibility
172   // for Darwin.
173   bool IsDarwin = Triple(M->getTargetTriple()).isOSDarwin();
174   if (DarwinGDBCompat == Default) {
175     if (IsDarwin)
176       IsDarwinGDBCompat = true;
177     else
178       IsDarwinGDBCompat = false;
179   } else
180     IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
181
182   if (DwarfAccelTables == Default) {
183     if (IsDarwin)
184       HasDwarfAccelTables = true;
185     else
186       HasDwarfAccelTables = false;
187   } else
188     HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
189
190   if (SplitDwarf == Default)
191     HasSplitDwarf = false;
192   else
193     HasSplitDwarf = SplitDwarf == Enable ? true : false;
194
195   {
196     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
197     beginModule();
198   }
199 }
200 DwarfDebug::~DwarfDebug() {
201 }
202
203 // Switch to the specified MCSection and emit an assembler
204 // temporary label to it if SymbolStem is specified.
205 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
206                                 const char *SymbolStem = 0) {
207   Asm->OutStreamer.SwitchSection(Section);
208   if (!SymbolStem) return 0;
209
210   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
211   Asm->OutStreamer.EmitLabel(TmpSym);
212   return TmpSym;
213 }
214
215 MCSymbol *DwarfUnits::getStringPoolSym() {
216   return Asm->GetTempSymbol("section_str");
217 }
218
219 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
220   std::pair<MCSymbol*, unsigned> &Entry =
221     StringPool->GetOrCreateValue(Str).getValue();
222   if (Entry.first) return Entry.first;
223
224   Entry.second = NextStringPoolNumber++;
225   return Entry.first = Asm->GetTempSymbol("string", Entry.second);
226 }
227
228 // Define a unique number for the abbreviation.
229 //
230 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
231   // Profile the node so that we can make it unique.
232   FoldingSetNodeID ID;
233   Abbrev.Profile(ID);
234
235   // Check the set for priors.
236   DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
237
238   // If it's newly added.
239   if (InSet == &Abbrev) {
240     // Add to abbreviation list.
241     Abbreviations->push_back(&Abbrev);
242
243     // Assign the vector position + 1 as its number.
244     Abbrev.setNumber(Abbreviations->size());
245   } else {
246     // Assign existing abbreviation number.
247     Abbrev.setNumber(InSet->getNumber());
248   }
249 }
250
251 // If special LLVM prefix that is used to inform the asm
252 // printer to not emit usual symbol prefix before the symbol name is used then
253 // return linkage name after skipping this special LLVM prefix.
254 static StringRef getRealLinkageName(StringRef LinkageName) {
255   char One = '\1';
256   if (LinkageName.startswith(StringRef(&One, 1)))
257     return LinkageName.substr(1);
258   return LinkageName;
259 }
260
261 static bool isObjCClass(StringRef Name) {
262   return Name.startswith("+") || Name.startswith("-");
263 }
264
265 static bool hasObjCCategory(StringRef Name) {
266   if (!isObjCClass(Name)) return false;
267
268   size_t pos = Name.find(')');
269   if (pos != std::string::npos) {
270     if (Name[pos+1] != ' ') return false;
271     return true;
272   }
273   return false;
274 }
275
276 static void getObjCClassCategory(StringRef In, StringRef &Class,
277                                  StringRef &Category) {
278   if (!hasObjCCategory(In)) {
279     Class = In.slice(In.find('[') + 1, In.find(' '));
280     Category = "";
281     return;
282   }
283
284   Class = In.slice(In.find('[') + 1, In.find('('));
285   Category = In.slice(In.find('[') + 1, In.find(' '));
286   return;
287 }
288
289 static StringRef getObjCMethodName(StringRef In) {
290   return In.slice(In.find(' ') + 1, In.find(']'));
291 }
292
293 // Add the various names to the Dwarf accelerator table names.
294 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
295                                DIE* Die) {
296   if (!SP.isDefinition()) return;
297
298   TheCU->addAccelName(SP.getName(), Die);
299
300   // If the linkage name is different than the name, go ahead and output
301   // that as well into the name table.
302   if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
303     TheCU->addAccelName(SP.getLinkageName(), Die);
304
305   // If this is an Objective-C selector name add it to the ObjC accelerator
306   // too.
307   if (isObjCClass(SP.getName())) {
308     StringRef Class, Category;
309     getObjCClassCategory(SP.getName(), Class, Category);
310     TheCU->addAccelObjC(Class, Die);
311     if (Category != "")
312       TheCU->addAccelObjC(Category, Die);
313     // Also add the base method name to the name table.
314     TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
315   }
316 }
317
318 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
319 // and DW_AT_high_pc attributes. If there are global variables in this
320 // scope then create and insert DIEs for these variables.
321 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
322                                           const MDNode *SPNode) {
323   DIE *SPDie = SPCU->getDIE(SPNode);
324
325   assert(SPDie && "Unable to find subprogram DIE!");
326   DISubprogram SP(SPNode);
327
328   // If we're updating an abstract DIE, then we will be adding the children and
329   // object pointer later on. But what we don't want to do is process the
330   // concrete DIE twice.
331   if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
332     // Pick up abstract subprogram DIE.
333     SPDie = new DIE(dwarf::DW_TAG_subprogram);
334     SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
335                       dwarf::DW_FORM_ref4, AbsSPDIE);
336     SPCU->addDie(SPDie);
337   } else {
338     DISubprogram SPDecl = SP.getFunctionDeclaration();
339     if (!SPDecl.isSubprogram()) {
340       // There is not any need to generate specification DIE for a function
341       // defined at compile unit level. If a function is defined inside another
342       // function then gdb prefers the definition at top level and but does not
343       // expect specification DIE in parent function. So avoid creating
344       // specification DIE for a function defined inside a function.
345       if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
346           !SP.getContext().isFile() &&
347           !isSubprogramContext(SP.getContext())) {
348         SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
349
350         // Add arguments.
351         DICompositeType SPTy = SP.getType();
352         DIArray Args = SPTy.getTypeArray();
353         unsigned SPTag = SPTy.getTag();
354         if (SPTag == dwarf::DW_TAG_subroutine_type)
355           for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
356             DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
357             DIType ATy = DIType(Args.getElement(i));
358             SPCU->addType(Arg, ATy);
359             if (ATy.isArtificial())
360               SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
361             if (ATy.isObjectPointer())
362               SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
363                                 dwarf::DW_FORM_ref4, Arg);
364             SPDie->addChild(Arg);
365           }
366         DIE *SPDeclDie = SPDie;
367         SPDie = new DIE(dwarf::DW_TAG_subprogram);
368         SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
369                           dwarf::DW_FORM_ref4, SPDeclDie);
370         SPCU->addDie(SPDie);
371       }
372     }
373   }
374
375   SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
376                  Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
377   SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
378                  Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
379   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
380   MachineLocation Location(RI->getFrameRegister(*Asm->MF));
381   SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
382
383   // Add name to the name table, we do this here because we're guaranteed
384   // to have concrete versions of our DW_TAG_subprogram nodes.
385   addSubprogramNames(SPCU, SP, SPDie);
386
387   return SPDie;
388 }
389
390 // Construct new DW_TAG_lexical_block for this scope and attach
391 // DW_AT_low_pc/DW_AT_high_pc labels.
392 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
393                                           LexicalScope *Scope) {
394   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
395   if (Scope->isAbstractScope())
396     return ScopeDIE;
397
398   const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
399   if (Ranges.empty())
400     return 0;
401
402   SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
403   if (Ranges.size() > 1) {
404     // .debug_range section has not been laid out yet. Emit offset in
405     // .debug_range as a uint, size 4, for now. emitDIE will handle
406     // DW_AT_ranges appropriately.
407     TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
408                    DebugRangeSymbols.size()
409                    * Asm->getDataLayout().getPointerSize());
410     for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
411          RE = Ranges.end(); RI != RE; ++RI) {
412       DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
413       DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
414     }
415     DebugRangeSymbols.push_back(NULL);
416     DebugRangeSymbols.push_back(NULL);
417     return ScopeDIE;
418   }
419
420   const MCSymbol *Start = getLabelBeforeInsn(RI->first);
421   const MCSymbol *End = getLabelAfterInsn(RI->second);
422
423   if (End == 0) return 0;
424
425   assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
426   assert(End->isDefined() && "Invalid end label for an inlined scope!");
427
428   TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
429   TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
430
431   return ScopeDIE;
432 }
433
434 // This scope represents inlined body of a function. Construct DIE to
435 // represent this concrete inlined copy of the function.
436 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
437                                           LexicalScope *Scope) {
438   const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
439   assert(Ranges.empty() == false &&
440          "LexicalScope does not have instruction markers!");
441
442   if (!Scope->getScopeNode())
443     return NULL;
444   DIScope DS(Scope->getScopeNode());
445   DISubprogram InlinedSP = getDISubprogram(DS);
446   DIE *OriginDIE = TheCU->getDIE(InlinedSP);
447   if (!OriginDIE) {
448     DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
449     return NULL;
450   }
451
452   SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
453   const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
454   const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
455
456   if (StartLabel == 0 || EndLabel == 0) {
457     llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
458   }
459   assert(StartLabel->isDefined() &&
460          "Invalid starting label for an inlined scope!");
461   assert(EndLabel->isDefined() &&
462          "Invalid end label for an inlined scope!");
463
464   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
465   TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
466                      dwarf::DW_FORM_ref4, OriginDIE);
467
468   if (Ranges.size() > 1) {
469     // .debug_range section has not been laid out yet. Emit offset in
470     // .debug_range as a uint, size 4, for now. emitDIE will handle
471     // DW_AT_ranges appropriately.
472     TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
473                    DebugRangeSymbols.size()
474                    * Asm->getDataLayout().getPointerSize());
475     for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
476          RE = Ranges.end(); RI != RE; ++RI) {
477       DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
478       DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
479     }
480     DebugRangeSymbols.push_back(NULL);
481     DebugRangeSymbols.push_back(NULL);
482   } else {
483     TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
484                     StartLabel);
485     TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
486                     EndLabel);
487   }
488
489   InlinedSubprogramDIEs.insert(OriginDIE);
490
491   // Track the start label for this inlined function.
492   //.debug_inlined section specification does not clearly state how
493   // to emit inlined scope that is split into multiple instruction ranges.
494   // For now, use first instruction range and emit low_pc/high_pc pair and
495   // corresponding .debug_inlined section entry for this pair.
496   DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
497     I = InlineInfo.find(InlinedSP);
498
499   if (I == InlineInfo.end()) {
500     InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
501     InlinedSPNodes.push_back(InlinedSP);
502   } else
503     I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
504
505   DILocation DL(Scope->getInlinedAt());
506   TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
507                  getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
508   TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
509
510   // Add name to the name table, we do this here because we're guaranteed
511   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
512   addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
513
514   return ScopeDIE;
515 }
516
517 // Construct a DIE for this scope.
518 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
519   if (!Scope || !Scope->getScopeNode())
520     return NULL;
521
522   SmallVector<DIE *, 8> Children;
523   DIE *ObjectPointer = NULL;
524
525   // Collect arguments for current function.
526   if (LScopes.isCurrentFunctionScope(Scope))
527     for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
528       if (DbgVariable *ArgDV = CurrentFnArguments[i])
529         if (DIE *Arg =
530             TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
531           Children.push_back(Arg);
532           if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
533         }
534
535   // Collect lexical scope children first.
536   const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
537   for (unsigned i = 0, N = Variables.size(); i < N; ++i)
538     if (DIE *Variable =
539         TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
540       Children.push_back(Variable);
541       if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
542     }
543   const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
544   for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
545     if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
546       Children.push_back(Nested);
547   DIScope DS(Scope->getScopeNode());
548   DIE *ScopeDIE = NULL;
549   if (Scope->getInlinedAt())
550     ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
551   else if (DS.isSubprogram()) {
552     ProcessedSPNodes.insert(DS);
553     if (Scope->isAbstractScope()) {
554       ScopeDIE = TheCU->getDIE(DS);
555       // Note down abstract DIE.
556       if (ScopeDIE)
557         AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
558     }
559     else
560       ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
561   }
562   else {
563     // There is no need to emit empty lexical block DIE.
564     if (Children.empty())
565       return NULL;
566     ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
567   }
568
569   if (!ScopeDIE) return NULL;
570
571   // Add children
572   for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
573          E = Children.end(); I != E; ++I)
574     ScopeDIE->addChild(*I);
575
576   if (DS.isSubprogram() && ObjectPointer != NULL)
577     TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
578                        dwarf::DW_FORM_ref4, ObjectPointer);
579
580   if (DS.isSubprogram())
581     TheCU->addPubTypes(DISubprogram(DS));
582
583   return ScopeDIE;
584 }
585
586 // Look up the source id with the given directory and source file names.
587 // If none currently exists, create a new id and insert it in the
588 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
589 // as well.
590 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
591                                          StringRef DirName) {
592   // If FE did not provide a file name, then assume stdin.
593   if (FileName.empty())
594     return getOrCreateSourceID("<stdin>", StringRef());
595
596   // TODO: this might not belong here. See if we can factor this better.
597   if (DirName == CompilationDir)
598     DirName = "";
599
600   unsigned SrcId = SourceIdMap.size()+1;
601
602   // We look up the file/dir pair by concatenating them with a zero byte.
603   SmallString<128> NamePair;
604   NamePair += DirName;
605   NamePair += '\0'; // Zero bytes are not allowed in paths.
606   NamePair += FileName;
607
608   StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
609   if (Ent.getValue() != SrcId)
610     return Ent.getValue();
611
612   // Print out a .file directive to specify files for .loc directives.
613   Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
614
615   return SrcId;
616 }
617
618 // Create new CompileUnit for the given metadata node with tag
619 // DW_TAG_compile_unit.
620 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
621   DICompileUnit DIUnit(N);
622   StringRef FN = DIUnit.getFilename();
623   CompilationDir = DIUnit.getDirectory();
624   // Call this to emit a .file directive if it wasn't emitted for the source
625   // file this CU comes from yet.
626   getOrCreateSourceID(FN, CompilationDir);
627
628   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
629   CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
630                                        DIUnit.getLanguage(), Die, Asm,
631                                        this, &InfoHolder);
632   NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
633   NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
634                  DIUnit.getLanguage());
635   NewCU->addString(Die, dwarf::DW_AT_name, FN);
636   // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
637   // into an entity.
638   NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
639   // DW_AT_stmt_list is a offset of line number information for this
640   // compile unit in debug_line section.
641   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
642     NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
643                     Asm->GetTempSymbol("section_line"));
644   else
645     NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
646
647   if (!CompilationDir.empty())
648     NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
649   if (DIUnit.isOptimized())
650     NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
651
652   StringRef Flags = DIUnit.getFlags();
653   if (!Flags.empty())
654     NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
655
656   if (unsigned RVer = DIUnit.getRunTimeVersion())
657     NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
658             dwarf::DW_FORM_data1, RVer);
659
660   if (!FirstCU)
661     FirstCU = NewCU;
662   if (useSplitDwarf() && !SkeletonCU)
663     SkeletonCU = constructSkeletonCU(N);
664
665   InfoHolder.addUnit(NewCU);
666
667   CUMap.insert(std::make_pair(N, NewCU));
668   return NewCU;
669 }
670
671 // Construct subprogram DIE.
672 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
673                                         const MDNode *N) {
674   CompileUnit *&CURef = SPMap[N];
675   if (CURef)
676     return;
677   CURef = TheCU;
678
679   DISubprogram SP(N);
680   if (!SP.isDefinition())
681     // This is a method declaration which will be handled while constructing
682     // class type.
683     return;
684
685   DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
686
687   // Add to map.
688   TheCU->insertDIE(N, SubprogramDie);
689
690   // Add to context owner.
691   TheCU->addToContextOwner(SubprogramDie, SP.getContext());
692
693   return;
694 }
695
696 // Collect debug info from named mdnodes such as llvm.dbg.enum and llvm.dbg.ty.
697 void DwarfDebug::collectInfoFromNamedMDNodes(const Module *M) {
698   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
699     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
700       const MDNode *N = NMD->getOperand(i);
701       if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
702         constructSubprogramDIE(CU, N);
703     }
704
705   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
706     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
707       const MDNode *N = NMD->getOperand(i);
708       if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
709         CU->createGlobalVariableDIE(N);
710     }
711
712   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
713     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
714       DIType Ty(NMD->getOperand(i));
715       if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
716         CU->getOrCreateTypeDIE(Ty);
717     }
718
719   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
720     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
721       DIType Ty(NMD->getOperand(i));
722       if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
723         CU->getOrCreateTypeDIE(Ty);
724     }
725 }
726
727 // Collect debug info using DebugInfoFinder.
728 // FIXME - Remove this when dragonegg switches to DIBuilder.
729 bool DwarfDebug::collectLegacyDebugInfo(const Module *M) {
730   DebugInfoFinder DbgFinder;
731   DbgFinder.processModule(*M);
732
733   bool HasDebugInfo = false;
734   // Scan all the compile-units to see if there are any marked as the main
735   // unit. If not, we do not generate debug info.
736   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
737          E = DbgFinder.compile_unit_end(); I != E; ++I) {
738     if (DICompileUnit(*I).isMain()) {
739       HasDebugInfo = true;
740       break;
741     }
742   }
743   if (!HasDebugInfo) return false;
744
745   // Create all the compile unit DIEs.
746   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
747          E = DbgFinder.compile_unit_end(); I != E; ++I)
748     constructCompileUnit(*I);
749
750   // Create DIEs for each global variable.
751   for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
752          E = DbgFinder.global_variable_end(); I != E; ++I) {
753     const MDNode *N = *I;
754     if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
755       CU->createGlobalVariableDIE(N);
756   }
757
758   // Create DIEs for each subprogram.
759   for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
760          E = DbgFinder.subprogram_end(); I != E; ++I) {
761     const MDNode *N = *I;
762     if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
763       constructSubprogramDIE(CU, N);
764   }
765
766   return HasDebugInfo;
767 }
768
769 // Emit all Dwarf sections that should come prior to the content. Create
770 // global DIEs and emit initial debug info sections. This is invoked by
771 // the target AsmPrinter.
772 void DwarfDebug::beginModule() {
773   if (DisableDebugInfoPrinting)
774     return;
775
776   const Module *M = MMI->getModule();
777
778   // If module has named metadata anchors then use them, otherwise scan the
779   // module using debug info finder to collect debug info.
780   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
781   if (CU_Nodes) {
782     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
783       DICompileUnit CUNode(CU_Nodes->getOperand(i));
784       CompileUnit *CU = constructCompileUnit(CUNode);
785       DIArray GVs = CUNode.getGlobalVariables();
786       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
787         CU->createGlobalVariableDIE(GVs.getElement(i));
788       DIArray SPs = CUNode.getSubprograms();
789       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
790         constructSubprogramDIE(CU, SPs.getElement(i));
791       DIArray EnumTypes = CUNode.getEnumTypes();
792       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
793         CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
794       DIArray RetainedTypes = CUNode.getRetainedTypes();
795       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
796         CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
797     }
798   } else if (!collectLegacyDebugInfo(M))
799     return;
800
801   collectInfoFromNamedMDNodes(M);
802
803   // Tell MMI that we have debug info.
804   MMI->setDebugInfoAvailability(true);
805
806   // Prime section data.
807   SectionMap.insert(Asm->getObjFileLowering().getTextSection());
808 }
809
810 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
811 void DwarfDebug::computeInlinedDIEs() {
812   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
813   for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
814          AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
815     DIE *ISP = *AI;
816     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
817   }
818   for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
819          AE = AbstractSPDies.end(); AI != AE; ++AI) {
820     DIE *ISP = AI->second;
821     if (InlinedSubprogramDIEs.count(ISP))
822       continue;
823     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
824   }
825 }
826
827 // Collect info for variables that were optimized out.
828 void DwarfDebug::collectDeadVariables() {
829   const Module *M = MMI->getModule();
830   DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
831
832   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
833     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
834       DICompileUnit TheCU(CU_Nodes->getOperand(i));
835       DIArray Subprograms = TheCU.getSubprograms();
836       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
837         DISubprogram SP(Subprograms.getElement(i));
838         if (ProcessedSPNodes.count(SP) != 0) continue;
839         if (!SP.Verify()) continue;
840         if (!SP.isDefinition()) continue;
841         DIArray Variables = SP.getVariables();
842         if (Variables.getNumElements() == 0) continue;
843
844         LexicalScope *Scope =
845           new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
846         DeadFnScopeMap[SP] = Scope;
847
848         // Construct subprogram DIE and add variables DIEs.
849         CompileUnit *SPCU = CUMap.lookup(TheCU);
850         assert(SPCU && "Unable to find Compile Unit!");
851         constructSubprogramDIE(SPCU, SP);
852         DIE *ScopeDIE = SPCU->getDIE(SP);
853         for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
854           DIVariable DV(Variables.getElement(vi));
855           if (!DV.Verify()) continue;
856           DbgVariable *NewVar = new DbgVariable(DV, NULL);
857           if (DIE *VariableDIE =
858               SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
859             ScopeDIE->addChild(VariableDIE);
860         }
861       }
862     }
863   }
864   DeleteContainerSeconds(DeadFnScopeMap);
865 }
866
867 void DwarfDebug::finalizeModuleInfo() {
868   // Collect info for variables that were optimized out.
869   collectDeadVariables();
870
871   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
872   computeInlinedDIEs();
873
874   // Emit DW_AT_containing_type attribute to connect types with their
875   // vtable holding type.
876   for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
877          CUE = CUMap.end(); CUI != CUE; ++CUI) {
878     CompileUnit *TheCU = CUI->second;
879     TheCU->constructContainingTypeDIEs();
880   }
881
882    // Compute DIE offsets and sizes.
883   InfoHolder.computeSizeAndOffsets();
884   if (useSplitDwarf())
885     SkeletonHolder.computeSizeAndOffsets();
886 }
887
888 void DwarfDebug::endSections() {
889   // Standard sections final addresses.
890   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
891   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
892   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
893   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
894
895   // End text sections.
896   for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
897     Asm->OutStreamer.SwitchSection(SectionMap[I]);
898     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
899   }
900 }
901
902 // Emit all Dwarf sections that should come after the content.
903 void DwarfDebug::endModule() {
904
905   if (!FirstCU) return;
906
907   // End any existing sections.
908   // TODO: Does this need to happen?
909   endSections();
910
911   // Finalize the debug info for the module.
912   finalizeModuleInfo();
913
914   // Emit initial sections.
915   emitSectionLabels();
916
917   if (!useSplitDwarf()) {
918     // Emit all the DIEs into a debug info section.
919     emitDebugInfo();
920
921     // Corresponding abbreviations into a abbrev section.
922     emitAbbreviations();
923
924     // Emit info into a debug loc section.
925     emitDebugLoc();
926
927     // Emit info into a debug aranges section.
928     emitDebugARanges();
929
930     // Emit info into a debug ranges section.
931     emitDebugRanges();
932
933     // Emit info into a debug macinfo section.
934     emitDebugMacInfo();
935
936     // Emit inline info.
937     // TODO: When we don't need the option anymore we
938     // can remove all of the code that this section
939     // depends upon.
940     if (useDarwinGDBCompat())
941       emitDebugInlineInfo();
942   } else {
943     // TODO: Fill this in for separated debug sections and separate
944     // out information into new sections.
945
946     // Emit the debug info section and compile units.
947     emitDebugInfo();
948     emitDebugInfoDWO();
949
950     // Corresponding abbreviations into a abbrev section.
951     emitAbbreviations();
952     emitDebugAbbrevDWO();
953
954     // Emit info into a debug loc section.
955     emitDebugLoc();
956
957     // Emit info into a debug aranges section.
958     emitDebugARanges();
959
960     // Emit info into a debug ranges section.
961     emitDebugRanges();
962
963     // Emit info into a debug macinfo section.
964     emitDebugMacInfo();
965
966     // Emit inline info.
967     // TODO: When we don't need the option anymore we
968     // can remove all of the code that this section
969     // depends upon.
970     if (useDarwinGDBCompat())
971       emitDebugInlineInfo();
972   }
973
974   // Emit info into the dwarf accelerator table sections.
975   if (useDwarfAccelTables()) {
976     emitAccelNames();
977     emitAccelObjC();
978     emitAccelNamespaces();
979     emitAccelTypes();
980   }
981
982   // Emit info into a debug pubtypes section.
983   // TODO: When we don't need the option anymore we can
984   // remove all of the code that adds to the table.
985   if (useDarwinGDBCompat())
986     emitDebugPubTypes();
987
988   // Finally emit string information into a string table.
989   emitDebugStr();
990
991   // clean up.
992   SPMap.clear();
993   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
994          E = CUMap.end(); I != E; ++I)
995     delete I->second;
996
997   delete SkeletonCU;
998
999   // Reset these for the next Module if we have one.
1000   FirstCU = NULL;
1001   SkeletonCU = NULL;
1002 }
1003
1004 // Find abstract variable, if any, associated with Var.
1005 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1006                                               DebugLoc ScopeLoc) {
1007   LLVMContext &Ctx = DV->getContext();
1008   // More then one inlined variable corresponds to one abstract variable.
1009   DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1010   DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1011   if (AbsDbgVariable)
1012     return AbsDbgVariable;
1013
1014   LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1015   if (!Scope)
1016     return NULL;
1017
1018   AbsDbgVariable = new DbgVariable(Var, NULL);
1019   addScopeVariable(Scope, AbsDbgVariable);
1020   AbstractVariables[Var] = AbsDbgVariable;
1021   return AbsDbgVariable;
1022 }
1023
1024 // If Var is a current function argument then add it to CurrentFnArguments list.
1025 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1026                                       DbgVariable *Var, LexicalScope *Scope) {
1027   if (!LScopes.isCurrentFunctionScope(Scope))
1028     return false;
1029   DIVariable DV = Var->getVariable();
1030   if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1031     return false;
1032   unsigned ArgNo = DV.getArgNumber();
1033   if (ArgNo == 0)
1034     return false;
1035
1036   size_t Size = CurrentFnArguments.size();
1037   if (Size == 0)
1038     CurrentFnArguments.resize(MF->getFunction()->arg_size());
1039   // llvm::Function argument size is not good indicator of how many
1040   // arguments does the function have at source level.
1041   if (ArgNo > Size)
1042     CurrentFnArguments.resize(ArgNo * 2);
1043   CurrentFnArguments[ArgNo - 1] = Var;
1044   return true;
1045 }
1046
1047 // Collect variable information from side table maintained by MMI.
1048 void
1049 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1050                                    SmallPtrSet<const MDNode *, 16> &Processed) {
1051   MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1052   for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1053          VE = VMap.end(); VI != VE; ++VI) {
1054     const MDNode *Var = VI->first;
1055     if (!Var) continue;
1056     Processed.insert(Var);
1057     DIVariable DV(Var);
1058     const std::pair<unsigned, DebugLoc> &VP = VI->second;
1059
1060     LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1061
1062     // If variable scope is not found then skip this variable.
1063     if (Scope == 0)
1064       continue;
1065
1066     DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1067     DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1068     RegVar->setFrameIndex(VP.first);
1069     if (!addCurrentFnArgument(MF, RegVar, Scope))
1070       addScopeVariable(Scope, RegVar);
1071     if (AbsDbgVariable)
1072       AbsDbgVariable->setFrameIndex(VP.first);
1073   }
1074 }
1075
1076 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1077 // defined reg.
1078 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1079   assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1080   return MI->getNumOperands() == 3 &&
1081          MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1082          MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1083 }
1084
1085 // Get .debug_loc entry for the instruction range starting at MI.
1086 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1087                                          const MCSymbol *FLabel,
1088                                          const MCSymbol *SLabel,
1089                                          const MachineInstr *MI) {
1090   const MDNode *Var =  MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1091
1092   if (MI->getNumOperands() != 3) {
1093     MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1094     return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1095   }
1096   if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1097     MachineLocation MLoc;
1098     MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1099     return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1100   }
1101   if (MI->getOperand(0).isImm())
1102     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1103   if (MI->getOperand(0).isFPImm())
1104     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1105   if (MI->getOperand(0).isCImm())
1106     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1107
1108   llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1109 }
1110
1111 // Find variables for each lexical scope.
1112 void
1113 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1114                                 SmallPtrSet<const MDNode *, 16> &Processed) {
1115
1116   // collection info from MMI table.
1117   collectVariableInfoFromMMITable(MF, Processed);
1118
1119   for (SmallVectorImpl<const MDNode*>::const_iterator
1120          UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1121          ++UVI) {
1122     const MDNode *Var = *UVI;
1123     if (Processed.count(Var))
1124       continue;
1125
1126     // History contains relevant DBG_VALUE instructions for Var and instructions
1127     // clobbering it.
1128     SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1129     if (History.empty())
1130       continue;
1131     const MachineInstr *MInsn = History.front();
1132
1133     DIVariable DV(Var);
1134     LexicalScope *Scope = NULL;
1135     if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1136         DISubprogram(DV.getContext()).describes(MF->getFunction()))
1137       Scope = LScopes.getCurrentFunctionScope();
1138     else {
1139       if (DV.getVersion() <= LLVMDebugVersion9)
1140         Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1141       else {
1142         if (MDNode *IA = DV.getInlinedAt())
1143           Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1144         else
1145           Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1146       }
1147     }
1148     // If variable scope is not found then skip this variable.
1149     if (!Scope)
1150       continue;
1151
1152     Processed.insert(DV);
1153     assert(MInsn->isDebugValue() && "History must begin with debug value");
1154     DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1155     DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1156     if (!addCurrentFnArgument(MF, RegVar, Scope))
1157       addScopeVariable(Scope, RegVar);
1158     if (AbsVar)
1159       AbsVar->setMInsn(MInsn);
1160
1161     // Simplify ranges that are fully coalesced.
1162     if (History.size() <= 1 || (History.size() == 2 &&
1163                                 MInsn->isIdenticalTo(History.back()))) {
1164       RegVar->setMInsn(MInsn);
1165       continue;
1166     }
1167
1168     // handle multiple DBG_VALUE instructions describing one variable.
1169     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1170
1171     for (SmallVectorImpl<const MachineInstr*>::const_iterator
1172            HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1173       const MachineInstr *Begin = *HI;
1174       assert(Begin->isDebugValue() && "Invalid History entry");
1175
1176       // Check if DBG_VALUE is truncating a range.
1177       if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1178           && !Begin->getOperand(0).getReg())
1179         continue;
1180
1181       // Compute the range for a register location.
1182       const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1183       const MCSymbol *SLabel = 0;
1184
1185       if (HI + 1 == HE)
1186         // If Begin is the last instruction in History then its value is valid
1187         // until the end of the function.
1188         SLabel = FunctionEndSym;
1189       else {
1190         const MachineInstr *End = HI[1];
1191         DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1192               << "\t" << *Begin << "\t" << *End << "\n");
1193         if (End->isDebugValue())
1194           SLabel = getLabelBeforeInsn(End);
1195         else {
1196           // End is a normal instruction clobbering the range.
1197           SLabel = getLabelAfterInsn(End);
1198           assert(SLabel && "Forgot label after clobber instruction");
1199           ++HI;
1200         }
1201       }
1202
1203       // The value is valid until the next DBG_VALUE or clobber.
1204       DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1205                                                     Begin));
1206     }
1207     DotDebugLocEntries.push_back(DotDebugLocEntry());
1208   }
1209
1210   // Collect info for variables that were optimized out.
1211   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1212   DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1213   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1214     DIVariable DV(Variables.getElement(i));
1215     if (!DV || !DV.Verify() || !Processed.insert(DV))
1216       continue;
1217     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1218       addScopeVariable(Scope, new DbgVariable(DV, NULL));
1219   }
1220 }
1221
1222 // Return Label preceding the instruction.
1223 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1224   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1225   assert(Label && "Didn't insert label before instruction");
1226   return Label;
1227 }
1228
1229 // Return Label immediately following the instruction.
1230 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1231   return LabelsAfterInsn.lookup(MI);
1232 }
1233
1234 // Process beginning of an instruction.
1235 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1236   // Check if source location changes, but ignore DBG_VALUE locations.
1237   if (!MI->isDebugValue()) {
1238     DebugLoc DL = MI->getDebugLoc();
1239     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1240       unsigned Flags = 0;
1241       PrevInstLoc = DL;
1242       if (DL == PrologEndLoc) {
1243         Flags |= DWARF2_FLAG_PROLOGUE_END;
1244         PrologEndLoc = DebugLoc();
1245       }
1246       if (PrologEndLoc.isUnknown())
1247         Flags |= DWARF2_FLAG_IS_STMT;
1248
1249       if (!DL.isUnknown()) {
1250         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1251         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1252       } else
1253         recordSourceLine(0, 0, 0, 0);
1254     }
1255   }
1256
1257   // Insert labels where requested.
1258   DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1259     LabelsBeforeInsn.find(MI);
1260
1261   // No label needed.
1262   if (I == LabelsBeforeInsn.end())
1263     return;
1264
1265   // Label already assigned.
1266   if (I->second)
1267     return;
1268
1269   if (!PrevLabel) {
1270     PrevLabel = MMI->getContext().CreateTempSymbol();
1271     Asm->OutStreamer.EmitLabel(PrevLabel);
1272   }
1273   I->second = PrevLabel;
1274 }
1275
1276 // Process end of an instruction.
1277 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1278   // Don't create a new label after DBG_VALUE instructions.
1279   // They don't generate code.
1280   if (!MI->isDebugValue())
1281     PrevLabel = 0;
1282
1283   DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1284     LabelsAfterInsn.find(MI);
1285
1286   // No label needed.
1287   if (I == LabelsAfterInsn.end())
1288     return;
1289
1290   // Label already assigned.
1291   if (I->second)
1292     return;
1293
1294   // We need a label after this instruction.
1295   if (!PrevLabel) {
1296     PrevLabel = MMI->getContext().CreateTempSymbol();
1297     Asm->OutStreamer.EmitLabel(PrevLabel);
1298   }
1299   I->second = PrevLabel;
1300 }
1301
1302 // Each LexicalScope has first instruction and last instruction to mark
1303 // beginning and end of a scope respectively. Create an inverse map that list
1304 // scopes starts (and ends) with an instruction. One instruction may start (or
1305 // end) multiple scopes. Ignore scopes that are not reachable.
1306 void DwarfDebug::identifyScopeMarkers() {
1307   SmallVector<LexicalScope *, 4> WorkList;
1308   WorkList.push_back(LScopes.getCurrentFunctionScope());
1309   while (!WorkList.empty()) {
1310     LexicalScope *S = WorkList.pop_back_val();
1311
1312     const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1313     if (!Children.empty())
1314       for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1315              SE = Children.end(); SI != SE; ++SI)
1316         WorkList.push_back(*SI);
1317
1318     if (S->isAbstractScope())
1319       continue;
1320
1321     const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1322     if (Ranges.empty())
1323       continue;
1324     for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1325            RE = Ranges.end(); RI != RE; ++RI) {
1326       assert(RI->first && "InsnRange does not have first instruction!");
1327       assert(RI->second && "InsnRange does not have second instruction!");
1328       requestLabelBeforeInsn(RI->first);
1329       requestLabelAfterInsn(RI->second);
1330     }
1331   }
1332 }
1333
1334 // Get MDNode for DebugLoc's scope.
1335 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1336   if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1337     return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1338   return DL.getScope(Ctx);
1339 }
1340
1341 // Walk up the scope chain of given debug loc and find line number info
1342 // for the function.
1343 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1344   const MDNode *Scope = getScopeNode(DL, Ctx);
1345   DISubprogram SP = getDISubprogram(Scope);
1346   if (SP.Verify()) {
1347     // Check for number of operands since the compatibility is
1348     // cheap here.
1349     if (SP->getNumOperands() > 19)
1350       return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1351     else
1352       return DebugLoc::get(SP.getLineNumber(), 0, SP);
1353   }
1354
1355   return DebugLoc();
1356 }
1357
1358 // Gather pre-function debug information.  Assumes being called immediately
1359 // after the function entry point has been emitted.
1360 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1361   if (!MMI->hasDebugInfo()) return;
1362   LScopes.initialize(*MF);
1363   if (LScopes.empty()) return;
1364   identifyScopeMarkers();
1365
1366   FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1367                                         Asm->getFunctionNumber());
1368   // Assumes in correct section after the entry point.
1369   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1370
1371   assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1372
1373   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1374   // LiveUserVar - Map physreg numbers to the MDNode they contain.
1375   std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1376
1377   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1378        I != E; ++I) {
1379     bool AtBlockEntry = true;
1380     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1381          II != IE; ++II) {
1382       const MachineInstr *MI = II;
1383
1384       if (MI->isDebugValue()) {
1385         assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1386
1387         // Keep track of user variables.
1388         const MDNode *Var =
1389           MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1390
1391         // Variable is in a register, we need to check for clobbers.
1392         if (isDbgValueInDefinedReg(MI))
1393           LiveUserVar[MI->getOperand(0).getReg()] = Var;
1394
1395         // Check the history of this variable.
1396         SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1397         if (History.empty()) {
1398           UserVariables.push_back(Var);
1399           // The first mention of a function argument gets the FunctionBeginSym
1400           // label, so arguments are visible when breaking at function entry.
1401           DIVariable DV(Var);
1402           if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1403               DISubprogram(getDISubprogram(DV.getContext()))
1404                 .describes(MF->getFunction()))
1405             LabelsBeforeInsn[MI] = FunctionBeginSym;
1406         } else {
1407           // We have seen this variable before. Try to coalesce DBG_VALUEs.
1408           const MachineInstr *Prev = History.back();
1409           if (Prev->isDebugValue()) {
1410             // Coalesce identical entries at the end of History.
1411             if (History.size() >= 2 &&
1412                 Prev->isIdenticalTo(History[History.size() - 2])) {
1413               DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1414                     << "\t" << *Prev
1415                     << "\t" << *History[History.size() - 2] << "\n");
1416               History.pop_back();
1417             }
1418
1419             // Terminate old register assignments that don't reach MI;
1420             MachineFunction::const_iterator PrevMBB = Prev->getParent();
1421             if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1422                 isDbgValueInDefinedReg(Prev)) {
1423               // Previous register assignment needs to terminate at the end of
1424               // its basic block.
1425               MachineBasicBlock::const_iterator LastMI =
1426                 PrevMBB->getLastNonDebugInstr();
1427               if (LastMI == PrevMBB->end()) {
1428                 // Drop DBG_VALUE for empty range.
1429                 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1430                       << "\t" << *Prev << "\n");
1431                 History.pop_back();
1432               }
1433               else {
1434                 // Terminate after LastMI.
1435                 History.push_back(LastMI);
1436               }
1437             }
1438           }
1439         }
1440         History.push_back(MI);
1441       } else {
1442         // Not a DBG_VALUE instruction.
1443         if (!MI->isLabel())
1444           AtBlockEntry = false;
1445
1446         // First known non-DBG_VALUE and non-frame setup location marks
1447         // the beginning of the function body.
1448         if (!MI->getFlag(MachineInstr::FrameSetup) &&
1449             (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1450           PrologEndLoc = MI->getDebugLoc();
1451
1452         // Check if the instruction clobbers any registers with debug vars.
1453         for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1454                MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1455           if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1456             continue;
1457           for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1458                AI.isValid(); ++AI) {
1459             unsigned Reg = *AI;
1460             const MDNode *Var = LiveUserVar[Reg];
1461             if (!Var)
1462               continue;
1463             // Reg is now clobbered.
1464             LiveUserVar[Reg] = 0;
1465
1466             // Was MD last defined by a DBG_VALUE referring to Reg?
1467             DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1468             if (HistI == DbgValues.end())
1469               continue;
1470             SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1471             if (History.empty())
1472               continue;
1473             const MachineInstr *Prev = History.back();
1474             // Sanity-check: Register assignments are terminated at the end of
1475             // their block.
1476             if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1477               continue;
1478             // Is the variable still in Reg?
1479             if (!isDbgValueInDefinedReg(Prev) ||
1480                 Prev->getOperand(0).getReg() != Reg)
1481               continue;
1482             // Var is clobbered. Make sure the next instruction gets a label.
1483             History.push_back(MI);
1484           }
1485         }
1486       }
1487     }
1488   }
1489
1490   for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1491        I != E; ++I) {
1492     SmallVectorImpl<const MachineInstr*> &History = I->second;
1493     if (History.empty())
1494       continue;
1495
1496     // Make sure the final register assignments are terminated.
1497     const MachineInstr *Prev = History.back();
1498     if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1499       const MachineBasicBlock *PrevMBB = Prev->getParent();
1500       MachineBasicBlock::const_iterator LastMI =
1501         PrevMBB->getLastNonDebugInstr();
1502       if (LastMI == PrevMBB->end())
1503         // Drop DBG_VALUE for empty range.
1504         History.pop_back();
1505       else {
1506         // Terminate after LastMI.
1507         History.push_back(LastMI);
1508       }
1509     }
1510     // Request labels for the full history.
1511     for (unsigned i = 0, e = History.size(); i != e; ++i) {
1512       const MachineInstr *MI = History[i];
1513       if (MI->isDebugValue())
1514         requestLabelBeforeInsn(MI);
1515       else
1516         requestLabelAfterInsn(MI);
1517     }
1518   }
1519
1520   PrevInstLoc = DebugLoc();
1521   PrevLabel = FunctionBeginSym;
1522
1523   // Record beginning of function.
1524   if (!PrologEndLoc.isUnknown()) {
1525     DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1526                                        MF->getFunction()->getContext());
1527     recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1528                      FnStartDL.getScope(MF->getFunction()->getContext()),
1529     // We'd like to list the prologue as "not statements" but GDB behaves
1530     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1531                      DWARF2_FLAG_IS_STMT);
1532   }
1533 }
1534
1535 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1536 //  SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1537   ScopeVariables[LS].push_back(Var);
1538 //  Vars.push_back(Var);
1539 }
1540
1541 // Gather and emit post-function debug information.
1542 void DwarfDebug::endFunction(const MachineFunction *MF) {
1543   if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1544
1545   // Define end label for subprogram.
1546   FunctionEndSym = Asm->GetTempSymbol("func_end",
1547                                       Asm->getFunctionNumber());
1548   // Assumes in correct section after the entry point.
1549   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1550
1551   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1552   collectVariableInfo(MF, ProcessedVars);
1553
1554   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1555   CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1556   assert(TheCU && "Unable to find compile unit!");
1557
1558   // Construct abstract scopes.
1559   ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1560   for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1561     LexicalScope *AScope = AList[i];
1562     DISubprogram SP(AScope->getScopeNode());
1563     if (SP.Verify()) {
1564       // Collect info for variables that were optimized out.
1565       DIArray Variables = SP.getVariables();
1566       for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1567         DIVariable DV(Variables.getElement(i));
1568         if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1569           continue;
1570         // Check that DbgVariable for DV wasn't created earlier, when
1571         // findAbstractVariable() was called for inlined instance of DV.
1572         LLVMContext &Ctx = DV->getContext();
1573         DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1574         if (AbstractVariables.lookup(CleanDV))
1575           continue;
1576         if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1577           addScopeVariable(Scope, new DbgVariable(DV, NULL));
1578       }
1579     }
1580     if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1581       constructScopeDIE(TheCU, AScope);
1582   }
1583
1584   DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1585
1586   if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1587     TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1588
1589   DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1590                                                MMI->getFrameMoves()));
1591
1592   // Clear debug info
1593   for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1594          I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1595     DeleteContainerPointers(I->second);
1596   ScopeVariables.clear();
1597   DeleteContainerPointers(CurrentFnArguments);
1598   UserVariables.clear();
1599   DbgValues.clear();
1600   AbstractVariables.clear();
1601   LabelsBeforeInsn.clear();
1602   LabelsAfterInsn.clear();
1603   PrevLabel = NULL;
1604 }
1605
1606 // Register a source line with debug info. Returns the  unique label that was
1607 // emitted and which provides correspondence to the source line list.
1608 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1609                                   unsigned Flags) {
1610   StringRef Fn;
1611   StringRef Dir;
1612   unsigned Src = 1;
1613   if (S) {
1614     DIDescriptor Scope(S);
1615
1616     if (Scope.isCompileUnit()) {
1617       DICompileUnit CU(S);
1618       Fn = CU.getFilename();
1619       Dir = CU.getDirectory();
1620     } else if (Scope.isFile()) {
1621       DIFile F(S);
1622       Fn = F.getFilename();
1623       Dir = F.getDirectory();
1624     } else if (Scope.isSubprogram()) {
1625       DISubprogram SP(S);
1626       Fn = SP.getFilename();
1627       Dir = SP.getDirectory();
1628     } else if (Scope.isLexicalBlockFile()) {
1629       DILexicalBlockFile DBF(S);
1630       Fn = DBF.getFilename();
1631       Dir = DBF.getDirectory();
1632     } else if (Scope.isLexicalBlock()) {
1633       DILexicalBlock DB(S);
1634       Fn = DB.getFilename();
1635       Dir = DB.getDirectory();
1636     } else
1637       llvm_unreachable("Unexpected scope info");
1638
1639     Src = getOrCreateSourceID(Fn, Dir);
1640   }
1641   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1642 }
1643
1644 //===----------------------------------------------------------------------===//
1645 // Emit Methods
1646 //===----------------------------------------------------------------------===//
1647
1648 // Compute the size and offset of a DIE.
1649 unsigned
1650 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1651   // Get the children.
1652   const std::vector<DIE *> &Children = Die->getChildren();
1653
1654   // Record the abbreviation.
1655   assignAbbrevNumber(Die->getAbbrev());
1656
1657   // Get the abbreviation for this DIE.
1658   unsigned AbbrevNumber = Die->getAbbrevNumber();
1659   const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1660
1661   // Set DIE offset
1662   Die->setOffset(Offset);
1663
1664   // Start the size with the size of abbreviation code.
1665   Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1666
1667   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1668   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1669
1670   // Size the DIE attribute values.
1671   for (unsigned i = 0, N = Values.size(); i < N; ++i)
1672     // Size attribute value.
1673     Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1674
1675   // Size the DIE children if any.
1676   if (!Children.empty()) {
1677     assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1678            "Children flag not set");
1679
1680     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1681       Offset = computeSizeAndOffset(Children[j], Offset);
1682
1683     // End of children marker.
1684     Offset += sizeof(int8_t);
1685   }
1686
1687   Die->setSize(Offset - Die->getOffset());
1688   return Offset;
1689 }
1690
1691 // Compute the size and offset of all the DIEs.
1692 void DwarfUnits::computeSizeAndOffsets() {
1693   for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1694          E = CUs.end(); I != E; ++I) {
1695     unsigned Offset =
1696       sizeof(int32_t) + // Length of Compilation Unit Info
1697       sizeof(int16_t) + // DWARF version number
1698       sizeof(int32_t) + // Offset Into Abbrev. Section
1699       sizeof(int8_t);   // Pointer Size (in bytes)
1700
1701     computeSizeAndOffset((*I)->getCUDie(), Offset);
1702   }
1703 }
1704
1705 // Emit initial Dwarf sections with a label at the start of each one.
1706 void DwarfDebug::emitSectionLabels() {
1707   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1708
1709   // Dwarf sections base addresses.
1710   DwarfInfoSectionSym =
1711     emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1712   DwarfAbbrevSectionSym =
1713     emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1714   if (useSplitDwarf())
1715     DwarfAbbrevDWOSectionSym =
1716       emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1717                      "section_abbrev_dwo");
1718   emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1719
1720   if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1721     emitSectionSym(Asm, MacroInfo);
1722
1723   emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1724   emitSectionSym(Asm, TLOF.getDwarfLocSection());
1725   emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1726   DwarfStrSectionSym =
1727     emitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1728   DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1729                                              "debug_range");
1730
1731   DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1732                                            "section_debug_loc");
1733
1734   TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1735   emitSectionSym(Asm, TLOF.getDataSection());
1736 }
1737
1738 // Recursively emits a debug information entry.
1739 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1740   // Get the abbreviation for this DIE.
1741   unsigned AbbrevNumber = Die->getAbbrevNumber();
1742   const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1743
1744   // Emit the code (index) for the abbreviation.
1745   if (Asm->isVerbose())
1746     Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1747                                 Twine::utohexstr(Die->getOffset()) + ":0x" +
1748                                 Twine::utohexstr(Die->getSize()) + " " +
1749                                 dwarf::TagString(Abbrev->getTag()));
1750   Asm->EmitULEB128(AbbrevNumber);
1751
1752   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1753   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1754
1755   // Emit the DIE attribute values.
1756   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1757     unsigned Attr = AbbrevData[i].getAttribute();
1758     unsigned Form = AbbrevData[i].getForm();
1759     assert(Form && "Too many attributes for DIE (check abbreviation)");
1760
1761     if (Asm->isVerbose())
1762       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1763
1764     switch (Attr) {
1765     case dwarf::DW_AT_abstract_origin: {
1766       DIEEntry *E = cast<DIEEntry>(Values[i]);
1767       DIE *Origin = E->getEntry();
1768       unsigned Addr = Origin->getOffset();
1769       Asm->EmitInt32(Addr);
1770       break;
1771     }
1772     case dwarf::DW_AT_ranges: {
1773       // DW_AT_range Value encodes offset in debug_range section.
1774       DIEInteger *V = cast<DIEInteger>(Values[i]);
1775
1776       if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1777         Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1778                                  V->getValue(),
1779                                  4);
1780       } else {
1781         Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1782                                        V->getValue(),
1783                                        DwarfDebugRangeSectionSym,
1784                                        4);
1785       }
1786       break;
1787     }
1788     case dwarf::DW_AT_location: {
1789       if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1790         if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1791           Asm->EmitLabelReference(L->getValue(), 4);
1792         else
1793           Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1794       } else {
1795         Values[i]->EmitValue(Asm, Form);
1796       }
1797       break;
1798     }
1799     case dwarf::DW_AT_accessibility: {
1800       if (Asm->isVerbose()) {
1801         DIEInteger *V = cast<DIEInteger>(Values[i]);
1802         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1803       }
1804       Values[i]->EmitValue(Asm, Form);
1805       break;
1806     }
1807     default:
1808       // Emit an attribute using the defined form.
1809       Values[i]->EmitValue(Asm, Form);
1810       break;
1811     }
1812   }
1813
1814   // Emit the DIE children if any.
1815   if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1816     const std::vector<DIE *> &Children = Die->getChildren();
1817
1818     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1819       emitDIE(Children[j], Abbrevs);
1820
1821     if (Asm->isVerbose())
1822       Asm->OutStreamer.AddComment("End Of Children Mark");
1823     Asm->EmitInt8(0);
1824   }
1825 }
1826
1827 // Emit the various dwarf units to the unit section USection with
1828 // the abbreviations going into ASection.
1829 void DwarfUnits::emitUnits(DwarfDebug *DD,
1830                            const MCSection *USection,
1831                            const MCSection *ASection,
1832                            const MCSymbol *ASectionSym) {
1833   Asm->OutStreamer.SwitchSection(USection);
1834   for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1835          E = CUs.end(); I != E; ++I) {
1836     CompileUnit *TheCU = *I;
1837     DIE *Die = TheCU->getCUDie();
1838
1839     // Emit the compile units header.
1840     Asm->OutStreamer
1841       .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1842                                     TheCU->getUniqueID()));
1843
1844     // Emit size of content not including length itself
1845     unsigned ContentSize = Die->getSize() +
1846       sizeof(int16_t) + // DWARF version number
1847       sizeof(int32_t) + // Offset Into Abbrev. Section
1848       sizeof(int8_t);   // Pointer Size (in bytes)
1849
1850     Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1851     Asm->EmitInt32(ContentSize);
1852     Asm->OutStreamer.AddComment("DWARF version number");
1853     Asm->EmitInt16(dwarf::DWARF_VERSION);
1854     Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1855     Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1856                            ASectionSym);
1857     Asm->OutStreamer.AddComment("Address Size (in bytes)");
1858     Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1859
1860     DD->emitDIE(Die, Abbreviations);
1861     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1862                                                   TheCU->getUniqueID()));
1863   }
1864 }
1865
1866 // Emit the debug info section.
1867 void DwarfDebug::emitDebugInfo() {
1868   DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1869
1870   Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1871                    Asm->getObjFileLowering().getDwarfAbbrevSection(),
1872                    DwarfAbbrevSectionSym);
1873 }
1874
1875 // Emit the abbreviation section.
1876 void DwarfDebug::emitAbbreviations() {
1877   if (!useSplitDwarf())
1878     emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1879                 &Abbreviations);
1880   else
1881     emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1882 }
1883
1884 void DwarfDebug::emitAbbrevs(const MCSection *Section,
1885                              std::vector<DIEAbbrev *> *Abbrevs) {
1886   // Check to see if it is worth the effort.
1887   if (!Abbrevs->empty()) {
1888     // Start the debug abbrev section.
1889     Asm->OutStreamer.SwitchSection(Section);
1890
1891     MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1892     Asm->OutStreamer.EmitLabel(Begin);
1893
1894     // For each abbrevation.
1895     for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1896       // Get abbreviation data
1897       const DIEAbbrev *Abbrev = Abbrevs->at(i);
1898
1899       // Emit the abbrevations code (base 1 index.)
1900       Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1901
1902       // Emit the abbreviations data.
1903       Abbrev->Emit(Asm);
1904     }
1905
1906     // Mark end of abbreviations.
1907     Asm->EmitULEB128(0, "EOM(3)");
1908
1909     MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1910     Asm->OutStreamer.EmitLabel(End);
1911   }
1912 }
1913
1914 // Emit the last address of the section and the end of the line matrix.
1915 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1916   // Define last address of section.
1917   Asm->OutStreamer.AddComment("Extended Op");
1918   Asm->EmitInt8(0);
1919
1920   Asm->OutStreamer.AddComment("Op size");
1921   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1922   Asm->OutStreamer.AddComment("DW_LNE_set_address");
1923   Asm->EmitInt8(dwarf::DW_LNE_set_address);
1924
1925   Asm->OutStreamer.AddComment("Section end label");
1926
1927   Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1928                                    Asm->getDataLayout().getPointerSize(),
1929                                    0/*AddrSpace*/);
1930
1931   // Mark end of matrix.
1932   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1933   Asm->EmitInt8(0);
1934   Asm->EmitInt8(1);
1935   Asm->EmitInt8(1);
1936 }
1937
1938 // Emit visible names into a hashed accelerator table section.
1939 void DwarfDebug::emitAccelNames() {
1940   DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1941                                            dwarf::DW_FORM_data4));
1942   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1943          E = CUMap.end(); I != E; ++I) {
1944     CompileUnit *TheCU = I->second;
1945     const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1946     for (StringMap<std::vector<DIE*> >::const_iterator
1947            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1948       const char *Name = GI->getKeyData();
1949       const std::vector<DIE *> &Entities = GI->second;
1950       for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1951              DE = Entities.end(); DI != DE; ++DI)
1952         AT.AddName(Name, (*DI));
1953     }
1954   }
1955
1956   AT.FinalizeTable(Asm, "Names");
1957   Asm->OutStreamer.SwitchSection(
1958     Asm->getObjFileLowering().getDwarfAccelNamesSection());
1959   MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1960   Asm->OutStreamer.EmitLabel(SectionBegin);
1961
1962   // Emit the full data.
1963   AT.Emit(Asm, SectionBegin, &InfoHolder);
1964 }
1965
1966 // Emit objective C classes and categories into a hashed accelerator table
1967 // section.
1968 void DwarfDebug::emitAccelObjC() {
1969   DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1970                                            dwarf::DW_FORM_data4));
1971   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1972          E = CUMap.end(); I != E; ++I) {
1973     CompileUnit *TheCU = I->second;
1974     const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1975     for (StringMap<std::vector<DIE*> >::const_iterator
1976            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1977       const char *Name = GI->getKeyData();
1978       const std::vector<DIE *> &Entities = GI->second;
1979       for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1980              DE = Entities.end(); DI != DE; ++DI)
1981         AT.AddName(Name, (*DI));
1982     }
1983   }
1984
1985   AT.FinalizeTable(Asm, "ObjC");
1986   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1987                                  .getDwarfAccelObjCSection());
1988   MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1989   Asm->OutStreamer.EmitLabel(SectionBegin);
1990
1991   // Emit the full data.
1992   AT.Emit(Asm, SectionBegin, &InfoHolder);
1993 }
1994
1995 // Emit namespace dies into a hashed accelerator table.
1996 void DwarfDebug::emitAccelNamespaces() {
1997   DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1998                                            dwarf::DW_FORM_data4));
1999   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2000          E = CUMap.end(); I != E; ++I) {
2001     CompileUnit *TheCU = I->second;
2002     const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2003     for (StringMap<std::vector<DIE*> >::const_iterator
2004            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2005       const char *Name = GI->getKeyData();
2006       const std::vector<DIE *> &Entities = GI->second;
2007       for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2008              DE = Entities.end(); DI != DE; ++DI)
2009         AT.AddName(Name, (*DI));
2010     }
2011   }
2012
2013   AT.FinalizeTable(Asm, "namespac");
2014   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2015                                  .getDwarfAccelNamespaceSection());
2016   MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2017   Asm->OutStreamer.EmitLabel(SectionBegin);
2018
2019   // Emit the full data.
2020   AT.Emit(Asm, SectionBegin, &InfoHolder);
2021 }
2022
2023 // Emit type dies into a hashed accelerator table.
2024 void DwarfDebug::emitAccelTypes() {
2025   std::vector<DwarfAccelTable::Atom> Atoms;
2026   Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2027                                         dwarf::DW_FORM_data4));
2028   Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2029                                         dwarf::DW_FORM_data2));
2030   Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2031                                         dwarf::DW_FORM_data1));
2032   DwarfAccelTable AT(Atoms);
2033   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2034          E = CUMap.end(); I != E; ++I) {
2035     CompileUnit *TheCU = I->second;
2036     const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2037       = TheCU->getAccelTypes();
2038     for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2039            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2040       const char *Name = GI->getKeyData();
2041       const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2042       for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2043              = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2044         AT.AddName(Name, (*DI).first, (*DI).second);
2045     }
2046   }
2047
2048   AT.FinalizeTable(Asm, "types");
2049   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2050                                  .getDwarfAccelTypesSection());
2051   MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2052   Asm->OutStreamer.EmitLabel(SectionBegin);
2053
2054   // Emit the full data.
2055   AT.Emit(Asm, SectionBegin, &InfoHolder);
2056 }
2057
2058 void DwarfDebug::emitDebugPubTypes() {
2059   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2060          E = CUMap.end(); I != E; ++I) {
2061     CompileUnit *TheCU = I->second;
2062     // Start the dwarf pubtypes section.
2063     Asm->OutStreamer.SwitchSection(
2064       Asm->getObjFileLowering().getDwarfPubTypesSection());
2065     Asm->OutStreamer.AddComment("Length of Public Types Info");
2066     Asm->EmitLabelDifference(
2067       Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2068       Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2069
2070     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2071                                                   TheCU->getUniqueID()));
2072
2073     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2074     Asm->EmitInt16(dwarf::DWARF_VERSION);
2075
2076     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2077     const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2078     Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2079                                               TheCU->getUniqueID()),
2080                            DwarfInfoSectionSym);
2081
2082     Asm->OutStreamer.AddComment("Compilation Unit Length");
2083     Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2084                                                 TheCU->getUniqueID()),
2085                              Asm->GetTempSymbol(ISec->getLabelBeginName(),
2086                                                 TheCU->getUniqueID()),
2087                              4);
2088
2089     const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2090     for (StringMap<DIE*>::const_iterator
2091            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2092       const char *Name = GI->getKeyData();
2093       DIE *Entity = GI->second;
2094
2095       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2096       Asm->EmitInt32(Entity->getOffset());
2097
2098       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2099       // Emit the name with a terminating null byte.
2100       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2101     }
2102
2103     Asm->OutStreamer.AddComment("End Mark");
2104     Asm->EmitInt32(0);
2105     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2106                                                   TheCU->getUniqueID()));
2107   }
2108 }
2109
2110 // Emit visible names into a debug str section.
2111 void DwarfDebug::emitDebugStr() {
2112   // Check to see if it is worth the effort.
2113   if (InfoHolder.getStringPool()->empty()) return;
2114
2115   // Start the dwarf str section.
2116   Asm->OutStreamer.SwitchSection(
2117                                 Asm->getObjFileLowering().getDwarfStrSection());
2118
2119   // Get all of the string pool entries and put them in an array by their ID so
2120   // we can sort them.
2121   SmallVector<std::pair<unsigned,
2122       StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2123
2124   for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2125        I = InfoHolder.getStringPool()->begin(),
2126          E = InfoHolder.getStringPool()->end();
2127        I != E; ++I)
2128     Entries.push_back(std::make_pair(I->second.second, &*I));
2129
2130   array_pod_sort(Entries.begin(), Entries.end());
2131
2132   for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2133     // Emit a label for reference from debug information entries.
2134     Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2135
2136     // Emit the string itself with a terminating null byte.
2137     Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2138                                          Entries[i].second->getKeyLength()+1),
2139                                0/*addrspace*/);
2140   }
2141 }
2142
2143 // Emit visible names into a debug loc section.
2144 void DwarfDebug::emitDebugLoc() {
2145   if (DotDebugLocEntries.empty())
2146     return;
2147
2148   for (SmallVector<DotDebugLocEntry, 4>::iterator
2149          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2150        I != E; ++I) {
2151     DotDebugLocEntry &Entry = *I;
2152     if (I + 1 != DotDebugLocEntries.end())
2153       Entry.Merge(I+1);
2154   }
2155
2156   // Start the dwarf loc section.
2157   Asm->OutStreamer.SwitchSection(
2158     Asm->getObjFileLowering().getDwarfLocSection());
2159   unsigned char Size = Asm->getDataLayout().getPointerSize();
2160   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2161   unsigned index = 1;
2162   for (SmallVector<DotDebugLocEntry, 4>::iterator
2163          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2164        I != E; ++I, ++index) {
2165     DotDebugLocEntry &Entry = *I;
2166     if (Entry.isMerged()) continue;
2167     if (Entry.isEmpty()) {
2168       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2169       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2170       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2171     } else {
2172       Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2173       Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2174       DIVariable DV(Entry.Variable);
2175       Asm->OutStreamer.AddComment("Loc expr size");
2176       MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2177       MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2178       Asm->EmitLabelDifference(end, begin, 2);
2179       Asm->OutStreamer.EmitLabel(begin);
2180       if (Entry.isInt()) {
2181         DIBasicType BTy(DV.getType());
2182         if (BTy.Verify() &&
2183             (BTy.getEncoding()  == dwarf::DW_ATE_signed
2184              || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2185           Asm->OutStreamer.AddComment("DW_OP_consts");
2186           Asm->EmitInt8(dwarf::DW_OP_consts);
2187           Asm->EmitSLEB128(Entry.getInt());
2188         } else {
2189           Asm->OutStreamer.AddComment("DW_OP_constu");
2190           Asm->EmitInt8(dwarf::DW_OP_constu);
2191           Asm->EmitULEB128(Entry.getInt());
2192         }
2193       } else if (Entry.isLocation()) {
2194         if (!DV.hasComplexAddress())
2195           // Regular entry.
2196           Asm->EmitDwarfRegOp(Entry.Loc);
2197         else {
2198           // Complex address entry.
2199           unsigned N = DV.getNumAddrElements();
2200           unsigned i = 0;
2201           if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2202             if (Entry.Loc.getOffset()) {
2203               i = 2;
2204               Asm->EmitDwarfRegOp(Entry.Loc);
2205               Asm->OutStreamer.AddComment("DW_OP_deref");
2206               Asm->EmitInt8(dwarf::DW_OP_deref);
2207               Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2208               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2209               Asm->EmitSLEB128(DV.getAddrElement(1));
2210             } else {
2211               // If first address element is OpPlus then emit
2212               // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2213               MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2214               Asm->EmitDwarfRegOp(Loc);
2215               i = 2;
2216             }
2217           } else {
2218             Asm->EmitDwarfRegOp(Entry.Loc);
2219           }
2220
2221           // Emit remaining complex address elements.
2222           for (; i < N; ++i) {
2223             uint64_t Element = DV.getAddrElement(i);
2224             if (Element == DIBuilder::OpPlus) {
2225               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2226               Asm->EmitULEB128(DV.getAddrElement(++i));
2227             } else if (Element == DIBuilder::OpDeref) {
2228               if (!Entry.Loc.isReg())
2229                 Asm->EmitInt8(dwarf::DW_OP_deref);
2230             } else
2231               llvm_unreachable("unknown Opcode found in complex address");
2232           }
2233         }
2234       }
2235       // else ... ignore constant fp. There is not any good way to
2236       // to represent them here in dwarf.
2237       Asm->OutStreamer.EmitLabel(end);
2238     }
2239   }
2240 }
2241
2242 // Emit visible names into a debug aranges section.
2243 void DwarfDebug::emitDebugARanges() {
2244   // Start the dwarf aranges section.
2245   Asm->OutStreamer.SwitchSection(
2246                           Asm->getObjFileLowering().getDwarfARangesSection());
2247 }
2248
2249 // Emit visible names into a debug ranges section.
2250 void DwarfDebug::emitDebugRanges() {
2251   // Start the dwarf ranges section.
2252   Asm->OutStreamer.SwitchSection(
2253     Asm->getObjFileLowering().getDwarfRangesSection());
2254   unsigned char Size = Asm->getDataLayout().getPointerSize();
2255   for (SmallVector<const MCSymbol *, 8>::iterator
2256          I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2257        I != E; ++I) {
2258     if (*I)
2259       Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2260     else
2261       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2262   }
2263 }
2264
2265 // Emit visible names into a debug macinfo section.
2266 void DwarfDebug::emitDebugMacInfo() {
2267   if (const MCSection *LineInfo =
2268       Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2269     // Start the dwarf macinfo section.
2270     Asm->OutStreamer.SwitchSection(LineInfo);
2271   }
2272 }
2273
2274 // Emit inline info using following format.
2275 // Section Header:
2276 // 1. length of section
2277 // 2. Dwarf version number
2278 // 3. address size.
2279 //
2280 // Entries (one "entry" for each function that was inlined):
2281 //
2282 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2283 //   otherwise offset into __debug_str for regular function name.
2284 // 2. offset into __debug_str section for regular function name.
2285 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2286 // instances for the function.
2287 //
2288 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2289 // inlined instance; the die_offset points to the inlined_subroutine die in the
2290 // __debug_info section, and the low_pc is the starting address for the
2291 // inlining instance.
2292 void DwarfDebug::emitDebugInlineInfo() {
2293   if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2294     return;
2295
2296   if (!FirstCU)
2297     return;
2298
2299   Asm->OutStreamer.SwitchSection(
2300                         Asm->getObjFileLowering().getDwarfDebugInlineSection());
2301
2302   Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2303   Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2304                            Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2305
2306   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2307
2308   Asm->OutStreamer.AddComment("Dwarf Version");
2309   Asm->EmitInt16(dwarf::DWARF_VERSION);
2310   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2311   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2312
2313   for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2314          E = InlinedSPNodes.end(); I != E; ++I) {
2315
2316     const MDNode *Node = *I;
2317     DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2318       = InlineInfo.find(Node);
2319     SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2320     DISubprogram SP(Node);
2321     StringRef LName = SP.getLinkageName();
2322     StringRef Name = SP.getName();
2323
2324     Asm->OutStreamer.AddComment("MIPS linkage name");
2325     if (LName.empty())
2326       Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2327                              DwarfStrSectionSym);
2328     else
2329       Asm->EmitSectionOffset(InfoHolder
2330                              .getStringPoolEntry(getRealLinkageName(LName)),
2331                              DwarfStrSectionSym);
2332
2333     Asm->OutStreamer.AddComment("Function name");
2334     Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2335                            DwarfStrSectionSym);
2336     Asm->EmitULEB128(Labels.size(), "Inline count");
2337
2338     for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2339            LE = Labels.end(); LI != LE; ++LI) {
2340       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2341       Asm->EmitInt32(LI->second->getOffset());
2342
2343       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2344       Asm->OutStreamer.EmitSymbolValue(LI->first,
2345                                        Asm->getDataLayout().getPointerSize(),0);
2346     }
2347   }
2348
2349   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2350 }
2351
2352 // DWARF5 Experimental Separate Dwarf emitters.
2353
2354 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2355 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2356 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2357 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2358 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2359   DICompileUnit DIUnit(N);
2360   StringRef FN = DIUnit.getFilename();
2361   CompilationDir = DIUnit.getDirectory();
2362
2363   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2364   CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2365                                        DIUnit.getLanguage(), Die, Asm,
2366                                        this, &InfoHolder);
2367   // FIXME: This should be the .dwo file.
2368   NewCU->addString(Die, dwarf::DW_AT_GNU_dwo_name, FN);
2369
2370   // FIXME: We also need DW_AT_addr_base and DW_AT_dwo_id.
2371
2372   // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2373   // into an entity.
2374   NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2375   // DW_AT_stmt_list is a offset of line number information for this
2376   // compile unit in debug_line section.
2377   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2378     NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
2379                     Asm->GetTempSymbol("section_line"));
2380   else
2381     NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
2382
2383   if (!CompilationDir.empty())
2384     NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2385
2386   SkeletonHolder.addUnit(NewCU);
2387
2388   return NewCU;
2389 }
2390
2391 void DwarfDebug::emitSkeletonCU(const MCSection *Section) {
2392   Asm->OutStreamer.SwitchSection(Section);
2393   DIE *Die = SkeletonCU->getCUDie();
2394
2395   // Emit the compile units header.
2396   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelBeginName(),
2397                                                 SkeletonCU->getUniqueID()));
2398
2399   // Emit size of content not including length itself
2400   unsigned ContentSize = Die->getSize() +
2401     sizeof(int16_t) + // DWARF version number
2402     sizeof(int32_t) + // Offset Into Abbrev. Section
2403     sizeof(int8_t);   // Pointer Size (in bytes)
2404
2405   Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2406   Asm->EmitInt32(ContentSize);
2407   Asm->OutStreamer.AddComment("DWARF version number");
2408   Asm->EmitInt16(dwarf::DWARF_VERSION);
2409   Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2410
2411   const MCSection *ASec = Asm->getObjFileLowering().getDwarfAbbrevSection();
2412   Asm->EmitSectionOffset(Asm->GetTempSymbol(ASec->getLabelBeginName()),
2413                          DwarfAbbrevSectionSym);
2414   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2415   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2416
2417   emitDIE(Die, &SkeletonAbbrevs);
2418   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelEndName(),
2419                                                 SkeletonCU->getUniqueID()));
2420 }
2421
2422 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2423   assert(useSplitDwarf() && "No split dwarf debug info?");
2424   emitAbbrevs(Section, &SkeletonAbbrevs);
2425 }
2426
2427 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2428 // compile units that would normally be in debug_info.
2429 void DwarfDebug::emitDebugInfoDWO() {
2430   assert(useSplitDwarf() && "No split dwarf debug info?");
2431   InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2432                        Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2433                        DwarfAbbrevDWOSectionSym);
2434 }
2435
2436 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2437 // abbreviations for the .debug_info.dwo section.
2438 void DwarfDebug::emitDebugAbbrevDWO() {
2439   assert(useSplitDwarf() && "No split dwarf?");
2440   emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2441               &Abbreviations);
2442 }