Split out abbreviations for the skeleton info from the rest of
[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), StringPool(DIEValueAllocator),
159     PrevLabel(NULL), GlobalCUIndexCount(0),
160     InfoHolder(A, &AbbreviationsSet, &Abbreviations),
161     SkeletonCU(0),
162     SkeletonAbbrevSet(InitAbbreviationsSetSize),
163     SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs) {
164   NextStringPoolNumber = 0;
165
166   DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
167   DwarfStrSectionSym = TextSectionSym = 0;
168   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
169   DwarfAbbrevDWOSectionSym = 0;
170   FunctionBeginSym = FunctionEndSym = 0;
171
172   // Turn on accelerator tables and older gdb compatibility
173   // for Darwin.
174   bool IsDarwin = Triple(M->getTargetTriple()).isOSDarwin();
175   if (DarwinGDBCompat == Default) {
176     if (IsDarwin)
177       IsDarwinGDBCompat = true;
178     else
179       IsDarwinGDBCompat = false;
180   } else
181     IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
182
183   if (DwarfAccelTables == Default) {
184     if (IsDarwin)
185       HasDwarfAccelTables = true;
186     else
187       HasDwarfAccelTables = false;
188   } else
189     HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
190
191   if (SplitDwarf == Default)
192     HasSplitDwarf = false;
193   else
194     HasSplitDwarf = SplitDwarf == Enable ? true : false;
195
196   {
197     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
198     beginModule();
199   }
200 }
201 DwarfDebug::~DwarfDebug() {
202 }
203
204 // Switch to the specified MCSection and emit an assembler
205 // temporary label to it if SymbolStem is specified.
206 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
207                                 const char *SymbolStem = 0) {
208   Asm->OutStreamer.SwitchSection(Section);
209   if (!SymbolStem) return 0;
210
211   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
212   Asm->OutStreamer.EmitLabel(TmpSym);
213   return TmpSym;
214 }
215
216 MCSymbol *DwarfDebug::getStringPool() {
217   return Asm->GetTempSymbol("section_str");
218 }
219
220 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
221   std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
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 DW_TAG_compile_unit.
619 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
620   DICompileUnit DIUnit(N);
621   StringRef FN = DIUnit.getFilename();
622   CompilationDir = DIUnit.getDirectory();
623   // Call this to emit a .file directive if it wasn't emitted for the source
624   // file this CU comes from yet.
625   getOrCreateSourceID(FN, CompilationDir);
626
627   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
628   CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
629                                        DIUnit.getLanguage(), Die, Asm, this);
630   NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
631   NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
632                  DIUnit.getLanguage());
633   NewCU->addString(Die, dwarf::DW_AT_name, FN);
634   // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
635   // into an entity.
636   NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
637   // DW_AT_stmt_list is a offset of line number information for this
638   // compile unit in debug_line section.
639   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
640     NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
641                     Asm->GetTempSymbol("section_line"));
642   else
643     NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
644
645   if (!CompilationDir.empty())
646     NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
647   if (DIUnit.isOptimized())
648     NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
649
650   StringRef Flags = DIUnit.getFlags();
651   if (!Flags.empty())
652     NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
653
654   if (unsigned RVer = DIUnit.getRunTimeVersion())
655     NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
656             dwarf::DW_FORM_data1, RVer);
657
658   if (!FirstCU)
659     FirstCU = NewCU;
660   if (useSplitDwarf() && !SkeletonCU)
661     SkeletonCU = constructSkeletonCU(N);
662
663   InfoHolder.addUnit(NewCU);
664
665   CUMap.insert(std::make_pair(N, NewCU));
666   return NewCU;
667 }
668
669 // Construct subprogram DIE.
670 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
671                                         const MDNode *N) {
672   CompileUnit *&CURef = SPMap[N];
673   if (CURef)
674     return;
675   CURef = TheCU;
676
677   DISubprogram SP(N);
678   if (!SP.isDefinition())
679     // This is a method declaration which will be handled while constructing
680     // class type.
681     return;
682
683   DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
684
685   // Add to map.
686   TheCU->insertDIE(N, SubprogramDie);
687
688   // Add to context owner.
689   TheCU->addToContextOwner(SubprogramDie, SP.getContext());
690
691   return;
692 }
693
694 // Collect debug info from named mdnodes such as llvm.dbg.enum and llvm.dbg.ty.
695 void DwarfDebug::collectInfoFromNamedMDNodes(const Module *M) {
696   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
697     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
698       const MDNode *N = NMD->getOperand(i);
699       if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
700         constructSubprogramDIE(CU, N);
701     }
702
703   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
704     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
705       const MDNode *N = NMD->getOperand(i);
706       if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
707         CU->createGlobalVariableDIE(N);
708     }
709
710   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
711     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
712       DIType Ty(NMD->getOperand(i));
713       if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
714         CU->getOrCreateTypeDIE(Ty);
715     }
716
717   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
718     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
719       DIType Ty(NMD->getOperand(i));
720       if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
721         CU->getOrCreateTypeDIE(Ty);
722     }
723 }
724
725 // Collect debug info using DebugInfoFinder.
726 // FIXME - Remove this when dragonegg switches to DIBuilder.
727 bool DwarfDebug::collectLegacyDebugInfo(const Module *M) {
728   DebugInfoFinder DbgFinder;
729   DbgFinder.processModule(*M);
730
731   bool HasDebugInfo = false;
732   // Scan all the compile-units to see if there are any marked as the main
733   // unit. If not, we do not generate debug info.
734   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
735          E = DbgFinder.compile_unit_end(); I != E; ++I) {
736     if (DICompileUnit(*I).isMain()) {
737       HasDebugInfo = true;
738       break;
739     }
740   }
741   if (!HasDebugInfo) return false;
742
743   // Create all the compile unit DIEs.
744   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
745          E = DbgFinder.compile_unit_end(); I != E; ++I)
746     constructCompileUnit(*I);
747
748   // Create DIEs for each global variable.
749   for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
750          E = DbgFinder.global_variable_end(); I != E; ++I) {
751     const MDNode *N = *I;
752     if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
753       CU->createGlobalVariableDIE(N);
754   }
755
756   // Create DIEs for each subprogram.
757   for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
758          E = DbgFinder.subprogram_end(); I != E; ++I) {
759     const MDNode *N = *I;
760     if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
761       constructSubprogramDIE(CU, N);
762   }
763
764   return HasDebugInfo;
765 }
766
767 // Emit all Dwarf sections that should come prior to the content. Create
768 // global DIEs and emit initial debug info sections. This is invoked by
769 // the target AsmPrinter.
770 void DwarfDebug::beginModule() {
771   if (DisableDebugInfoPrinting)
772     return;
773
774   const Module *M = MMI->getModule();
775
776   // If module has named metadata anchors then use them, otherwise scan the
777   // module using debug info finder to collect debug info.
778   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
779   if (CU_Nodes) {
780     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
781       DICompileUnit CUNode(CU_Nodes->getOperand(i));
782       CompileUnit *CU = constructCompileUnit(CUNode);
783       DIArray GVs = CUNode.getGlobalVariables();
784       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
785         CU->createGlobalVariableDIE(GVs.getElement(i));
786       DIArray SPs = CUNode.getSubprograms();
787       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
788         constructSubprogramDIE(CU, SPs.getElement(i));
789       DIArray EnumTypes = CUNode.getEnumTypes();
790       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
791         CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
792       DIArray RetainedTypes = CUNode.getRetainedTypes();
793       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
794         CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
795     }
796   } else if (!collectLegacyDebugInfo(M))
797     return;
798
799   collectInfoFromNamedMDNodes(M);
800
801   // Tell MMI that we have debug info.
802   MMI->setDebugInfoAvailability(true);
803
804   // Prime section data.
805   SectionMap.insert(Asm->getObjFileLowering().getTextSection());
806 }
807
808 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
809 void DwarfDebug::computeInlinedDIEs() {
810   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
811   for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
812          AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
813     DIE *ISP = *AI;
814     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
815   }
816   for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
817          AE = AbstractSPDies.end(); AI != AE; ++AI) {
818     DIE *ISP = AI->second;
819     if (InlinedSubprogramDIEs.count(ISP))
820       continue;
821     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
822   }
823 }
824
825 // Collect info for variables that were optimized out.
826 void DwarfDebug::collectDeadVariables() {
827   const Module *M = MMI->getModule();
828   DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
829
830   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
831     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
832       DICompileUnit TheCU(CU_Nodes->getOperand(i));
833       DIArray Subprograms = TheCU.getSubprograms();
834       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
835         DISubprogram SP(Subprograms.getElement(i));
836         if (ProcessedSPNodes.count(SP) != 0) continue;
837         if (!SP.Verify()) continue;
838         if (!SP.isDefinition()) continue;
839         DIArray Variables = SP.getVariables();
840         if (Variables.getNumElements() == 0) continue;
841
842         LexicalScope *Scope =
843           new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
844         DeadFnScopeMap[SP] = Scope;
845
846         // Construct subprogram DIE and add variables DIEs.
847         CompileUnit *SPCU = CUMap.lookup(TheCU);
848         assert(SPCU && "Unable to find Compile Unit!");
849         constructSubprogramDIE(SPCU, SP);
850         DIE *ScopeDIE = SPCU->getDIE(SP);
851         for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
852           DIVariable DV(Variables.getElement(vi));
853           if (!DV.Verify()) continue;
854           DbgVariable *NewVar = new DbgVariable(DV, NULL);
855           if (DIE *VariableDIE =
856               SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
857             ScopeDIE->addChild(VariableDIE);
858         }
859       }
860     }
861   }
862   DeleteContainerSeconds(DeadFnScopeMap);
863 }
864
865 void DwarfDebug::finalizeModuleInfo() {
866   // Collect info for variables that were optimized out.
867   collectDeadVariables();
868
869   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
870   computeInlinedDIEs();
871
872   // Emit DW_AT_containing_type attribute to connect types with their
873   // vtable holding type.
874   for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
875          CUE = CUMap.end(); CUI != CUE; ++CUI) {
876     CompileUnit *TheCU = CUI->second;
877     TheCU->constructContainingTypeDIEs();
878   }
879
880    // Compute DIE offsets and sizes.
881   InfoHolder.computeSizeAndOffsets();
882   if (useSplitDwarf())
883     SkeletonHolder.computeSizeAndOffsets();
884 }
885
886 void DwarfDebug::endSections() {
887   // Standard sections final addresses.
888   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
889   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
890   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
891   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
892
893   // End text sections.
894   for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
895     Asm->OutStreamer.SwitchSection(SectionMap[I]);
896     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
897   }
898 }
899
900 // Emit all Dwarf sections that should come after the content.
901 void DwarfDebug::endModule() {
902
903   if (!FirstCU) return;
904
905   // End any existing sections.
906   // TODO: Does this need to happen?
907   endSections();
908
909   // Finalize the debug info for the module.
910   finalizeModuleInfo();
911
912   // Emit initial sections.
913   emitSectionLabels();
914
915   if (!useSplitDwarf()) {
916     // Emit all the DIEs into a debug info section.
917     emitDebugInfo();
918
919     // Corresponding abbreviations into a abbrev section.
920     emitAbbreviations();
921
922     // Emit info into a debug loc section.
923     emitDebugLoc();
924
925     // Emit info into a debug aranges section.
926     emitDebugARanges();
927
928     // Emit info into a debug ranges section.
929     emitDebugRanges();
930
931     // Emit info into a debug macinfo section.
932     emitDebugMacInfo();
933
934     // Emit inline info.
935     // TODO: When we don't need the option anymore we
936     // can remove all of the code that this section
937     // depends upon.
938     if (useDarwinGDBCompat())
939       emitDebugInlineInfo();
940   } else {
941     // TODO: Fill this in for separated debug sections and separate
942     // out information into new sections.
943
944     // Emit the debug info section and compile units.
945     emitDebugInfo();
946     emitDebugInfoDWO();
947
948     // Corresponding abbreviations into a abbrev section.
949     emitAbbreviations();
950     emitDebugAbbrevDWO();
951
952     // Emit info into a debug loc section.
953     emitDebugLoc();
954
955     // Emit info into a debug aranges section.
956     emitDebugARanges();
957
958     // Emit info into a debug ranges section.
959     emitDebugRanges();
960
961     // Emit info into a debug macinfo section.
962     emitDebugMacInfo();
963
964     // Emit inline info.
965     // TODO: When we don't need the option anymore we
966     // can remove all of the code that this section
967     // depends upon.
968     if (useDarwinGDBCompat())
969       emitDebugInlineInfo();
970   }
971
972   // Emit info into the dwarf accelerator table sections.
973   if (useDwarfAccelTables()) {
974     emitAccelNames();
975     emitAccelObjC();
976     emitAccelNamespaces();
977     emitAccelTypes();
978   }
979
980   // Emit info into a debug pubtypes section.
981   // TODO: When we don't need the option anymore we can
982   // remove all of the code that adds to the table.
983   if (useDarwinGDBCompat())
984     emitDebugPubTypes();
985
986   // Finally emit string information into a string table.
987   emitDebugStr();
988
989   // clean up.
990   SPMap.clear();
991   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
992          E = CUMap.end(); I != E; ++I)
993     delete I->second;
994
995   delete SkeletonCU;
996
997   // Reset these for the next Module if we have one.
998   FirstCU = NULL;
999   SkeletonCU = NULL;
1000 }
1001
1002 // Find abstract variable, if any, associated with Var.
1003 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1004                                               DebugLoc ScopeLoc) {
1005   LLVMContext &Ctx = DV->getContext();
1006   // More then one inlined variable corresponds to one abstract variable.
1007   DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1008   DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1009   if (AbsDbgVariable)
1010     return AbsDbgVariable;
1011
1012   LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1013   if (!Scope)
1014     return NULL;
1015
1016   AbsDbgVariable = new DbgVariable(Var, NULL);
1017   addScopeVariable(Scope, AbsDbgVariable);
1018   AbstractVariables[Var] = AbsDbgVariable;
1019   return AbsDbgVariable;
1020 }
1021
1022 // If Var is a current function argument then add it to CurrentFnArguments list.
1023 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1024                                       DbgVariable *Var, LexicalScope *Scope) {
1025   if (!LScopes.isCurrentFunctionScope(Scope))
1026     return false;
1027   DIVariable DV = Var->getVariable();
1028   if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1029     return false;
1030   unsigned ArgNo = DV.getArgNumber();
1031   if (ArgNo == 0)
1032     return false;
1033
1034   size_t Size = CurrentFnArguments.size();
1035   if (Size == 0)
1036     CurrentFnArguments.resize(MF->getFunction()->arg_size());
1037   // llvm::Function argument size is not good indicator of how many
1038   // arguments does the function have at source level.
1039   if (ArgNo > Size)
1040     CurrentFnArguments.resize(ArgNo * 2);
1041   CurrentFnArguments[ArgNo - 1] = Var;
1042   return true;
1043 }
1044
1045 // Collect variable information from side table maintained by MMI.
1046 void
1047 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1048                                    SmallPtrSet<const MDNode *, 16> &Processed) {
1049   MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1050   for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1051          VE = VMap.end(); VI != VE; ++VI) {
1052     const MDNode *Var = VI->first;
1053     if (!Var) continue;
1054     Processed.insert(Var);
1055     DIVariable DV(Var);
1056     const std::pair<unsigned, DebugLoc> &VP = VI->second;
1057
1058     LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1059
1060     // If variable scope is not found then skip this variable.
1061     if (Scope == 0)
1062       continue;
1063
1064     DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1065     DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1066     RegVar->setFrameIndex(VP.first);
1067     if (!addCurrentFnArgument(MF, RegVar, Scope))
1068       addScopeVariable(Scope, RegVar);
1069     if (AbsDbgVariable)
1070       AbsDbgVariable->setFrameIndex(VP.first);
1071   }
1072 }
1073
1074 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1075 // defined reg.
1076 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1077   assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1078   return MI->getNumOperands() == 3 &&
1079          MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1080          MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1081 }
1082
1083 // Get .debug_loc entry for the instruction range starting at MI.
1084 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1085                                          const MCSymbol *FLabel,
1086                                          const MCSymbol *SLabel,
1087                                          const MachineInstr *MI) {
1088   const MDNode *Var =  MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1089
1090   if (MI->getNumOperands() != 3) {
1091     MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1092     return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1093   }
1094   if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1095     MachineLocation MLoc;
1096     MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1097     return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1098   }
1099   if (MI->getOperand(0).isImm())
1100     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1101   if (MI->getOperand(0).isFPImm())
1102     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1103   if (MI->getOperand(0).isCImm())
1104     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1105
1106   llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1107 }
1108
1109 // Find variables for each lexical scope.
1110 void
1111 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1112                                 SmallPtrSet<const MDNode *, 16> &Processed) {
1113
1114   // collection info from MMI table.
1115   collectVariableInfoFromMMITable(MF, Processed);
1116
1117   for (SmallVectorImpl<const MDNode*>::const_iterator
1118          UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1119          ++UVI) {
1120     const MDNode *Var = *UVI;
1121     if (Processed.count(Var))
1122       continue;
1123
1124     // History contains relevant DBG_VALUE instructions for Var and instructions
1125     // clobbering it.
1126     SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1127     if (History.empty())
1128       continue;
1129     const MachineInstr *MInsn = History.front();
1130
1131     DIVariable DV(Var);
1132     LexicalScope *Scope = NULL;
1133     if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1134         DISubprogram(DV.getContext()).describes(MF->getFunction()))
1135       Scope = LScopes.getCurrentFunctionScope();
1136     else {
1137       if (DV.getVersion() <= LLVMDebugVersion9)
1138         Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1139       else {
1140         if (MDNode *IA = DV.getInlinedAt())
1141           Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1142         else
1143           Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1144       }
1145     }
1146     // If variable scope is not found then skip this variable.
1147     if (!Scope)
1148       continue;
1149
1150     Processed.insert(DV);
1151     assert(MInsn->isDebugValue() && "History must begin with debug value");
1152     DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1153     DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1154     if (!addCurrentFnArgument(MF, RegVar, Scope))
1155       addScopeVariable(Scope, RegVar);
1156     if (AbsVar)
1157       AbsVar->setMInsn(MInsn);
1158
1159     // Simplify ranges that are fully coalesced.
1160     if (History.size() <= 1 || (History.size() == 2 &&
1161                                 MInsn->isIdenticalTo(History.back()))) {
1162       RegVar->setMInsn(MInsn);
1163       continue;
1164     }
1165
1166     // handle multiple DBG_VALUE instructions describing one variable.
1167     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1168
1169     for (SmallVectorImpl<const MachineInstr*>::const_iterator
1170            HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1171       const MachineInstr *Begin = *HI;
1172       assert(Begin->isDebugValue() && "Invalid History entry");
1173
1174       // Check if DBG_VALUE is truncating a range.
1175       if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1176           && !Begin->getOperand(0).getReg())
1177         continue;
1178
1179       // Compute the range for a register location.
1180       const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1181       const MCSymbol *SLabel = 0;
1182
1183       if (HI + 1 == HE)
1184         // If Begin is the last instruction in History then its value is valid
1185         // until the end of the function.
1186         SLabel = FunctionEndSym;
1187       else {
1188         const MachineInstr *End = HI[1];
1189         DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1190               << "\t" << *Begin << "\t" << *End << "\n");
1191         if (End->isDebugValue())
1192           SLabel = getLabelBeforeInsn(End);
1193         else {
1194           // End is a normal instruction clobbering the range.
1195           SLabel = getLabelAfterInsn(End);
1196           assert(SLabel && "Forgot label after clobber instruction");
1197           ++HI;
1198         }
1199       }
1200
1201       // The value is valid until the next DBG_VALUE or clobber.
1202       DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1203                                                     Begin));
1204     }
1205     DotDebugLocEntries.push_back(DotDebugLocEntry());
1206   }
1207
1208   // Collect info for variables that were optimized out.
1209   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1210   DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1211   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1212     DIVariable DV(Variables.getElement(i));
1213     if (!DV || !DV.Verify() || !Processed.insert(DV))
1214       continue;
1215     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1216       addScopeVariable(Scope, new DbgVariable(DV, NULL));
1217   }
1218 }
1219
1220 // Return Label preceding the instruction.
1221 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1222   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1223   assert(Label && "Didn't insert label before instruction");
1224   return Label;
1225 }
1226
1227 // Return Label immediately following the instruction.
1228 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1229   return LabelsAfterInsn.lookup(MI);
1230 }
1231
1232 // Process beginning of an instruction.
1233 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1234   // Check if source location changes, but ignore DBG_VALUE locations.
1235   if (!MI->isDebugValue()) {
1236     DebugLoc DL = MI->getDebugLoc();
1237     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1238       unsigned Flags = 0;
1239       PrevInstLoc = DL;
1240       if (DL == PrologEndLoc) {
1241         Flags |= DWARF2_FLAG_PROLOGUE_END;
1242         PrologEndLoc = DebugLoc();
1243       }
1244       if (PrologEndLoc.isUnknown())
1245         Flags |= DWARF2_FLAG_IS_STMT;
1246
1247       if (!DL.isUnknown()) {
1248         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1249         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1250       } else
1251         recordSourceLine(0, 0, 0, 0);
1252     }
1253   }
1254
1255   // Insert labels where requested.
1256   DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1257     LabelsBeforeInsn.find(MI);
1258
1259   // No label needed.
1260   if (I == LabelsBeforeInsn.end())
1261     return;
1262
1263   // Label already assigned.
1264   if (I->second)
1265     return;
1266
1267   if (!PrevLabel) {
1268     PrevLabel = MMI->getContext().CreateTempSymbol();
1269     Asm->OutStreamer.EmitLabel(PrevLabel);
1270   }
1271   I->second = PrevLabel;
1272 }
1273
1274 // Process end of an instruction.
1275 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1276   // Don't create a new label after DBG_VALUE instructions.
1277   // They don't generate code.
1278   if (!MI->isDebugValue())
1279     PrevLabel = 0;
1280
1281   DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1282     LabelsAfterInsn.find(MI);
1283
1284   // No label needed.
1285   if (I == LabelsAfterInsn.end())
1286     return;
1287
1288   // Label already assigned.
1289   if (I->second)
1290     return;
1291
1292   // We need a label after this instruction.
1293   if (!PrevLabel) {
1294     PrevLabel = MMI->getContext().CreateTempSymbol();
1295     Asm->OutStreamer.EmitLabel(PrevLabel);
1296   }
1297   I->second = PrevLabel;
1298 }
1299
1300 // Each LexicalScope has first instruction and last instruction to mark
1301 // beginning and end of a scope respectively. Create an inverse map that list
1302 // scopes starts (and ends) with an instruction. One instruction may start (or
1303 // end) multiple scopes. Ignore scopes that are not reachable.
1304 void DwarfDebug::identifyScopeMarkers() {
1305   SmallVector<LexicalScope *, 4> WorkList;
1306   WorkList.push_back(LScopes.getCurrentFunctionScope());
1307   while (!WorkList.empty()) {
1308     LexicalScope *S = WorkList.pop_back_val();
1309
1310     const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1311     if (!Children.empty())
1312       for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1313              SE = Children.end(); SI != SE; ++SI)
1314         WorkList.push_back(*SI);
1315
1316     if (S->isAbstractScope())
1317       continue;
1318
1319     const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1320     if (Ranges.empty())
1321       continue;
1322     for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1323            RE = Ranges.end(); RI != RE; ++RI) {
1324       assert(RI->first && "InsnRange does not have first instruction!");
1325       assert(RI->second && "InsnRange does not have second instruction!");
1326       requestLabelBeforeInsn(RI->first);
1327       requestLabelAfterInsn(RI->second);
1328     }
1329   }
1330 }
1331
1332 // Get MDNode for DebugLoc's scope.
1333 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1334   if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1335     return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1336   return DL.getScope(Ctx);
1337 }
1338
1339 // Walk up the scope chain of given debug loc and find line number info
1340 // for the function.
1341 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1342   const MDNode *Scope = getScopeNode(DL, Ctx);
1343   DISubprogram SP = getDISubprogram(Scope);
1344   if (SP.Verify()) {
1345     // Check for number of operands since the compatibility is
1346     // cheap here.
1347     if (SP->getNumOperands() > 19)
1348       return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1349     else
1350       return DebugLoc::get(SP.getLineNumber(), 0, SP);
1351   }
1352
1353   return DebugLoc();
1354 }
1355
1356 // Gather pre-function debug information.  Assumes being called immediately
1357 // after the function entry point has been emitted.
1358 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1359   if (!MMI->hasDebugInfo()) return;
1360   LScopes.initialize(*MF);
1361   if (LScopes.empty()) return;
1362   identifyScopeMarkers();
1363
1364   FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1365                                         Asm->getFunctionNumber());
1366   // Assumes in correct section after the entry point.
1367   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1368
1369   assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1370
1371   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1372   // LiveUserVar - Map physreg numbers to the MDNode they contain.
1373   std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1374
1375   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1376        I != E; ++I) {
1377     bool AtBlockEntry = true;
1378     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1379          II != IE; ++II) {
1380       const MachineInstr *MI = II;
1381
1382       if (MI->isDebugValue()) {
1383         assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1384
1385         // Keep track of user variables.
1386         const MDNode *Var =
1387           MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1388
1389         // Variable is in a register, we need to check for clobbers.
1390         if (isDbgValueInDefinedReg(MI))
1391           LiveUserVar[MI->getOperand(0).getReg()] = Var;
1392
1393         // Check the history of this variable.
1394         SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1395         if (History.empty()) {
1396           UserVariables.push_back(Var);
1397           // The first mention of a function argument gets the FunctionBeginSym
1398           // label, so arguments are visible when breaking at function entry.
1399           DIVariable DV(Var);
1400           if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1401               DISubprogram(getDISubprogram(DV.getContext()))
1402                 .describes(MF->getFunction()))
1403             LabelsBeforeInsn[MI] = FunctionBeginSym;
1404         } else {
1405           // We have seen this variable before. Try to coalesce DBG_VALUEs.
1406           const MachineInstr *Prev = History.back();
1407           if (Prev->isDebugValue()) {
1408             // Coalesce identical entries at the end of History.
1409             if (History.size() >= 2 &&
1410                 Prev->isIdenticalTo(History[History.size() - 2])) {
1411               DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1412                     << "\t" << *Prev
1413                     << "\t" << *History[History.size() - 2] << "\n");
1414               History.pop_back();
1415             }
1416
1417             // Terminate old register assignments that don't reach MI;
1418             MachineFunction::const_iterator PrevMBB = Prev->getParent();
1419             if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1420                 isDbgValueInDefinedReg(Prev)) {
1421               // Previous register assignment needs to terminate at the end of
1422               // its basic block.
1423               MachineBasicBlock::const_iterator LastMI =
1424                 PrevMBB->getLastNonDebugInstr();
1425               if (LastMI == PrevMBB->end()) {
1426                 // Drop DBG_VALUE for empty range.
1427                 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1428                       << "\t" << *Prev << "\n");
1429                 History.pop_back();
1430               }
1431               else {
1432                 // Terminate after LastMI.
1433                 History.push_back(LastMI);
1434               }
1435             }
1436           }
1437         }
1438         History.push_back(MI);
1439       } else {
1440         // Not a DBG_VALUE instruction.
1441         if (!MI->isLabel())
1442           AtBlockEntry = false;
1443
1444         // First known non-DBG_VALUE and non-frame setup location marks
1445         // the beginning of the function body.
1446         if (!MI->getFlag(MachineInstr::FrameSetup) &&
1447             (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1448           PrologEndLoc = MI->getDebugLoc();
1449
1450         // Check if the instruction clobbers any registers with debug vars.
1451         for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1452                MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1453           if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1454             continue;
1455           for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1456                AI.isValid(); ++AI) {
1457             unsigned Reg = *AI;
1458             const MDNode *Var = LiveUserVar[Reg];
1459             if (!Var)
1460               continue;
1461             // Reg is now clobbered.
1462             LiveUserVar[Reg] = 0;
1463
1464             // Was MD last defined by a DBG_VALUE referring to Reg?
1465             DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1466             if (HistI == DbgValues.end())
1467               continue;
1468             SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1469             if (History.empty())
1470               continue;
1471             const MachineInstr *Prev = History.back();
1472             // Sanity-check: Register assignments are terminated at the end of
1473             // their block.
1474             if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1475               continue;
1476             // Is the variable still in Reg?
1477             if (!isDbgValueInDefinedReg(Prev) ||
1478                 Prev->getOperand(0).getReg() != Reg)
1479               continue;
1480             // Var is clobbered. Make sure the next instruction gets a label.
1481             History.push_back(MI);
1482           }
1483         }
1484       }
1485     }
1486   }
1487
1488   for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1489        I != E; ++I) {
1490     SmallVectorImpl<const MachineInstr*> &History = I->second;
1491     if (History.empty())
1492       continue;
1493
1494     // Make sure the final register assignments are terminated.
1495     const MachineInstr *Prev = History.back();
1496     if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1497       const MachineBasicBlock *PrevMBB = Prev->getParent();
1498       MachineBasicBlock::const_iterator LastMI =
1499         PrevMBB->getLastNonDebugInstr();
1500       if (LastMI == PrevMBB->end())
1501         // Drop DBG_VALUE for empty range.
1502         History.pop_back();
1503       else {
1504         // Terminate after LastMI.
1505         History.push_back(LastMI);
1506       }
1507     }
1508     // Request labels for the full history.
1509     for (unsigned i = 0, e = History.size(); i != e; ++i) {
1510       const MachineInstr *MI = History[i];
1511       if (MI->isDebugValue())
1512         requestLabelBeforeInsn(MI);
1513       else
1514         requestLabelAfterInsn(MI);
1515     }
1516   }
1517
1518   PrevInstLoc = DebugLoc();
1519   PrevLabel = FunctionBeginSym;
1520
1521   // Record beginning of function.
1522   if (!PrologEndLoc.isUnknown()) {
1523     DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1524                                        MF->getFunction()->getContext());
1525     recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1526                      FnStartDL.getScope(MF->getFunction()->getContext()),
1527     // We'd like to list the prologue as "not statements" but GDB behaves
1528     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1529                      DWARF2_FLAG_IS_STMT);
1530   }
1531 }
1532
1533 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1534 //  SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1535   ScopeVariables[LS].push_back(Var);
1536 //  Vars.push_back(Var);
1537 }
1538
1539 // Gather and emit post-function debug information.
1540 void DwarfDebug::endFunction(const MachineFunction *MF) {
1541   if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1542
1543   // Define end label for subprogram.
1544   FunctionEndSym = Asm->GetTempSymbol("func_end",
1545                                       Asm->getFunctionNumber());
1546   // Assumes in correct section after the entry point.
1547   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1548
1549   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1550   collectVariableInfo(MF, ProcessedVars);
1551
1552   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1553   CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1554   assert(TheCU && "Unable to find compile unit!");
1555
1556   // Construct abstract scopes.
1557   ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1558   for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1559     LexicalScope *AScope = AList[i];
1560     DISubprogram SP(AScope->getScopeNode());
1561     if (SP.Verify()) {
1562       // Collect info for variables that were optimized out.
1563       DIArray Variables = SP.getVariables();
1564       for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1565         DIVariable DV(Variables.getElement(i));
1566         if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1567           continue;
1568         // Check that DbgVariable for DV wasn't created earlier, when
1569         // findAbstractVariable() was called for inlined instance of DV.
1570         LLVMContext &Ctx = DV->getContext();
1571         DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1572         if (AbstractVariables.lookup(CleanDV))
1573           continue;
1574         if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1575           addScopeVariable(Scope, new DbgVariable(DV, NULL));
1576       }
1577     }
1578     if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1579       constructScopeDIE(TheCU, AScope);
1580   }
1581
1582   DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1583
1584   if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1585     TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1586
1587   DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1588                                                MMI->getFrameMoves()));
1589
1590   // Clear debug info
1591   for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1592          I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1593     DeleteContainerPointers(I->second);
1594   ScopeVariables.clear();
1595   DeleteContainerPointers(CurrentFnArguments);
1596   UserVariables.clear();
1597   DbgValues.clear();
1598   AbstractVariables.clear();
1599   LabelsBeforeInsn.clear();
1600   LabelsAfterInsn.clear();
1601   PrevLabel = NULL;
1602 }
1603
1604 // Register a source line with debug info. Returns the  unique label that was
1605 // emitted and which provides correspondence to the source line list.
1606 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1607                                   unsigned Flags) {
1608   StringRef Fn;
1609   StringRef Dir;
1610   unsigned Src = 1;
1611   if (S) {
1612     DIDescriptor Scope(S);
1613
1614     if (Scope.isCompileUnit()) {
1615       DICompileUnit CU(S);
1616       Fn = CU.getFilename();
1617       Dir = CU.getDirectory();
1618     } else if (Scope.isFile()) {
1619       DIFile F(S);
1620       Fn = F.getFilename();
1621       Dir = F.getDirectory();
1622     } else if (Scope.isSubprogram()) {
1623       DISubprogram SP(S);
1624       Fn = SP.getFilename();
1625       Dir = SP.getDirectory();
1626     } else if (Scope.isLexicalBlockFile()) {
1627       DILexicalBlockFile DBF(S);
1628       Fn = DBF.getFilename();
1629       Dir = DBF.getDirectory();
1630     } else if (Scope.isLexicalBlock()) {
1631       DILexicalBlock DB(S);
1632       Fn = DB.getFilename();
1633       Dir = DB.getDirectory();
1634     } else
1635       llvm_unreachable("Unexpected scope info");
1636
1637     Src = getOrCreateSourceID(Fn, Dir);
1638   }
1639   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1640 }
1641
1642 //===----------------------------------------------------------------------===//
1643 // Emit Methods
1644 //===----------------------------------------------------------------------===//
1645
1646 // Compute the size and offset of a DIE.
1647 unsigned
1648 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1649   // Get the children.
1650   const std::vector<DIE *> &Children = Die->getChildren();
1651
1652   // Record the abbreviation.
1653   assignAbbrevNumber(Die->getAbbrev());
1654
1655   // Get the abbreviation for this DIE.
1656   unsigned AbbrevNumber = Die->getAbbrevNumber();
1657   const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1658
1659   // Set DIE offset
1660   Die->setOffset(Offset);
1661
1662   // Start the size with the size of abbreviation code.
1663   Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1664
1665   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1666   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1667
1668   // Size the DIE attribute values.
1669   for (unsigned i = 0, N = Values.size(); i < N; ++i)
1670     // Size attribute value.
1671     Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1672
1673   // Size the DIE children if any.
1674   if (!Children.empty()) {
1675     assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1676            "Children flag not set");
1677
1678     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1679       Offset = computeSizeAndOffset(Children[j], Offset);
1680
1681     // End of children marker.
1682     Offset += sizeof(int8_t);
1683   }
1684
1685   Die->setSize(Offset - Die->getOffset());
1686   return Offset;
1687 }
1688
1689 // Compute the size and offset of all the DIEs.
1690 void DwarfUnits::computeSizeAndOffsets() {
1691   for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1692          E = CUs.end(); I != E; ++I) {
1693     unsigned Offset =
1694       sizeof(int32_t) + // Length of Compilation Unit Info
1695       sizeof(int16_t) + // DWARF version number
1696       sizeof(int32_t) + // Offset Into Abbrev. Section
1697       sizeof(int8_t);   // Pointer Size (in bytes)
1698
1699     computeSizeAndOffset((*I)->getCUDie(), Offset);
1700   }
1701 }
1702
1703 // Emit initial Dwarf sections with a label at the start of each one.
1704 void DwarfDebug::emitSectionLabels() {
1705   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1706
1707   // Dwarf sections base addresses.
1708   DwarfInfoSectionSym =
1709     emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1710   DwarfAbbrevSectionSym =
1711     emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1712   if (useSplitDwarf())
1713     DwarfAbbrevDWOSectionSym =
1714       emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1715                      "section_abbrev_dwo");
1716   emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1717
1718   if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1719     emitSectionSym(Asm, MacroInfo);
1720
1721   emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1722   emitSectionSym(Asm, TLOF.getDwarfLocSection());
1723   emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1724   DwarfStrSectionSym =
1725     emitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1726   DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1727                                              "debug_range");
1728
1729   DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1730                                            "section_debug_loc");
1731
1732   TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1733   emitSectionSym(Asm, TLOF.getDataSection());
1734 }
1735
1736 // Recursively emits a debug information entry.
1737 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1738   // Get the abbreviation for this DIE.
1739   unsigned AbbrevNumber = Die->getAbbrevNumber();
1740   const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1741
1742   // Emit the code (index) for the abbreviation.
1743   if (Asm->isVerbose())
1744     Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1745                                 Twine::utohexstr(Die->getOffset()) + ":0x" +
1746                                 Twine::utohexstr(Die->getSize()) + " " +
1747                                 dwarf::TagString(Abbrev->getTag()));
1748   Asm->EmitULEB128(AbbrevNumber);
1749
1750   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1751   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1752
1753   // Emit the DIE attribute values.
1754   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1755     unsigned Attr = AbbrevData[i].getAttribute();
1756     unsigned Form = AbbrevData[i].getForm();
1757     assert(Form && "Too many attributes for DIE (check abbreviation)");
1758
1759     if (Asm->isVerbose())
1760       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1761
1762     switch (Attr) {
1763     case dwarf::DW_AT_abstract_origin: {
1764       DIEEntry *E = cast<DIEEntry>(Values[i]);
1765       DIE *Origin = E->getEntry();
1766       unsigned Addr = Origin->getOffset();
1767       Asm->EmitInt32(Addr);
1768       break;
1769     }
1770     case dwarf::DW_AT_ranges: {
1771       // DW_AT_range Value encodes offset in debug_range section.
1772       DIEInteger *V = cast<DIEInteger>(Values[i]);
1773
1774       if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1775         Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1776                                  V->getValue(),
1777                                  4);
1778       } else {
1779         Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1780                                        V->getValue(),
1781                                        DwarfDebugRangeSectionSym,
1782                                        4);
1783       }
1784       break;
1785     }
1786     case dwarf::DW_AT_location: {
1787       if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1788         if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1789           Asm->EmitLabelReference(L->getValue(), 4);
1790         else
1791           Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1792       } else {
1793         Values[i]->EmitValue(Asm, Form);
1794       }
1795       break;
1796     }
1797     case dwarf::DW_AT_accessibility: {
1798       if (Asm->isVerbose()) {
1799         DIEInteger *V = cast<DIEInteger>(Values[i]);
1800         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1801       }
1802       Values[i]->EmitValue(Asm, Form);
1803       break;
1804     }
1805     default:
1806       // Emit an attribute using the defined form.
1807       Values[i]->EmitValue(Asm, Form);
1808       break;
1809     }
1810   }
1811
1812   // Emit the DIE children if any.
1813   if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1814     const std::vector<DIE *> &Children = Die->getChildren();
1815
1816     for (unsigned j = 0, M = Children.size(); j < M; ++j)
1817       emitDIE(Children[j], Abbrevs);
1818
1819     if (Asm->isVerbose())
1820       Asm->OutStreamer.AddComment("End Of Children Mark");
1821     Asm->EmitInt8(0);
1822   }
1823 }
1824
1825 // Emit the various dwarf units to the unit section USection with
1826 // the abbreviations going into ASection.
1827 void DwarfUnits::emitUnits(DwarfDebug *DD,
1828                            const MCSection *USection,
1829                            const MCSection *ASection,
1830                            const MCSymbol *ASectionSym) {
1831   Asm->OutStreamer.SwitchSection(USection);
1832   for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1833          E = CUs.end(); I != E; ++I) {
1834     CompileUnit *TheCU = *I;
1835     DIE *Die = TheCU->getCUDie();
1836
1837     // Emit the compile units header.
1838     Asm->OutStreamer
1839       .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1840                                     TheCU->getUniqueID()));
1841
1842     // Emit size of content not including length itself
1843     unsigned ContentSize = Die->getSize() +
1844       sizeof(int16_t) + // DWARF version number
1845       sizeof(int32_t) + // Offset Into Abbrev. Section
1846       sizeof(int8_t);   // Pointer Size (in bytes)
1847
1848     Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1849     Asm->EmitInt32(ContentSize);
1850     Asm->OutStreamer.AddComment("DWARF version number");
1851     Asm->EmitInt16(dwarf::DWARF_VERSION);
1852     Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1853     Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1854                            ASectionSym);
1855     Asm->OutStreamer.AddComment("Address Size (in bytes)");
1856     Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1857
1858     DD->emitDIE(Die, Abbreviations);
1859     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1860                                                   TheCU->getUniqueID()));
1861   }
1862 }
1863
1864 // Emit the debug info section.
1865 void DwarfDebug::emitDebugInfo() {
1866   DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1867
1868   Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1869                    Asm->getObjFileLowering().getDwarfAbbrevSection(),
1870                    DwarfAbbrevSectionSym);
1871 }
1872
1873 // Emit the abbreviation section.
1874 void DwarfDebug::emitAbbreviations() {
1875   if (!useSplitDwarf())
1876     emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1877                 &Abbreviations);
1878   else
1879     emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1880 }
1881
1882 void DwarfDebug::emitAbbrevs(const MCSection *Section,
1883                              std::vector<DIEAbbrev *> *Abbrevs) {
1884   // Check to see if it is worth the effort.
1885   if (!Abbrevs->empty()) {
1886     // Start the debug abbrev section.
1887     Asm->OutStreamer.SwitchSection(Section);
1888
1889     MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1890     Asm->OutStreamer.EmitLabel(Begin);
1891
1892     // For each abbrevation.
1893     for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1894       // Get abbreviation data
1895       const DIEAbbrev *Abbrev = Abbrevs->at(i);
1896
1897       // Emit the abbrevations code (base 1 index.)
1898       Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1899
1900       // Emit the abbreviations data.
1901       Abbrev->Emit(Asm);
1902     }
1903
1904     // Mark end of abbreviations.
1905     Asm->EmitULEB128(0, "EOM(3)");
1906
1907     MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1908     Asm->OutStreamer.EmitLabel(End);
1909   }
1910 }
1911
1912 // Emit the last address of the section and the end of the line matrix.
1913 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1914   // Define last address of section.
1915   Asm->OutStreamer.AddComment("Extended Op");
1916   Asm->EmitInt8(0);
1917
1918   Asm->OutStreamer.AddComment("Op size");
1919   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1920   Asm->OutStreamer.AddComment("DW_LNE_set_address");
1921   Asm->EmitInt8(dwarf::DW_LNE_set_address);
1922
1923   Asm->OutStreamer.AddComment("Section end label");
1924
1925   Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1926                                    Asm->getDataLayout().getPointerSize(),
1927                                    0/*AddrSpace*/);
1928
1929   // Mark end of matrix.
1930   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1931   Asm->EmitInt8(0);
1932   Asm->EmitInt8(1);
1933   Asm->EmitInt8(1);
1934 }
1935
1936 // Emit visible names into a hashed accelerator table section.
1937 void DwarfDebug::emitAccelNames() {
1938   DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1939                                            dwarf::DW_FORM_data4));
1940   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1941          E = CUMap.end(); I != E; ++I) {
1942     CompileUnit *TheCU = I->second;
1943     const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1944     for (StringMap<std::vector<DIE*> >::const_iterator
1945            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1946       const char *Name = GI->getKeyData();
1947       const std::vector<DIE *> &Entities = GI->second;
1948       for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1949              DE = Entities.end(); DI != DE; ++DI)
1950         AT.AddName(Name, (*DI));
1951     }
1952   }
1953
1954   AT.FinalizeTable(Asm, "Names");
1955   Asm->OutStreamer.SwitchSection(
1956     Asm->getObjFileLowering().getDwarfAccelNamesSection());
1957   MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1958   Asm->OutStreamer.EmitLabel(SectionBegin);
1959
1960   // Emit the full data.
1961   AT.Emit(Asm, SectionBegin, this);
1962 }
1963
1964 // Emit objective C classes and categories into a hashed accelerator table section.
1965 void DwarfDebug::emitAccelObjC() {
1966   DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1967                                            dwarf::DW_FORM_data4));
1968   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1969          E = CUMap.end(); I != E; ++I) {
1970     CompileUnit *TheCU = I->second;
1971     const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1972     for (StringMap<std::vector<DIE*> >::const_iterator
1973            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1974       const char *Name = GI->getKeyData();
1975       const std::vector<DIE *> &Entities = GI->second;
1976       for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1977              DE = Entities.end(); DI != DE; ++DI)
1978         AT.AddName(Name, (*DI));
1979     }
1980   }
1981
1982   AT.FinalizeTable(Asm, "ObjC");
1983   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1984                                  .getDwarfAccelObjCSection());
1985   MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1986   Asm->OutStreamer.EmitLabel(SectionBegin);
1987
1988   // Emit the full data.
1989   AT.Emit(Asm, SectionBegin, this);
1990 }
1991
1992 // Emit namespace dies into a hashed accelerator table.
1993 void DwarfDebug::emitAccelNamespaces() {
1994   DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1995                                            dwarf::DW_FORM_data4));
1996   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1997          E = CUMap.end(); I != E; ++I) {
1998     CompileUnit *TheCU = I->second;
1999     const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2000     for (StringMap<std::vector<DIE*> >::const_iterator
2001            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2002       const char *Name = GI->getKeyData();
2003       const std::vector<DIE *> &Entities = GI->second;
2004       for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2005              DE = Entities.end(); DI != DE; ++DI)
2006         AT.AddName(Name, (*DI));
2007     }
2008   }
2009
2010   AT.FinalizeTable(Asm, "namespac");
2011   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2012                                  .getDwarfAccelNamespaceSection());
2013   MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2014   Asm->OutStreamer.EmitLabel(SectionBegin);
2015
2016   // Emit the full data.
2017   AT.Emit(Asm, SectionBegin, this);
2018 }
2019
2020 // Emit type dies into a hashed accelerator table.
2021 void DwarfDebug::emitAccelTypes() {
2022   std::vector<DwarfAccelTable::Atom> Atoms;
2023   Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2024                                         dwarf::DW_FORM_data4));
2025   Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2026                                         dwarf::DW_FORM_data2));
2027   Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2028                                         dwarf::DW_FORM_data1));
2029   DwarfAccelTable AT(Atoms);
2030   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2031          E = CUMap.end(); I != E; ++I) {
2032     CompileUnit *TheCU = I->second;
2033     const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2034       = TheCU->getAccelTypes();
2035     for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2036            GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2037       const char *Name = GI->getKeyData();
2038       const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2039       for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2040              = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2041         AT.AddName(Name, (*DI).first, (*DI).second);
2042     }
2043   }
2044
2045   AT.FinalizeTable(Asm, "types");
2046   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2047                                  .getDwarfAccelTypesSection());
2048   MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2049   Asm->OutStreamer.EmitLabel(SectionBegin);
2050
2051   // Emit the full data.
2052   AT.Emit(Asm, SectionBegin, this);
2053 }
2054
2055 void DwarfDebug::emitDebugPubTypes() {
2056   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2057          E = CUMap.end(); I != E; ++I) {
2058     CompileUnit *TheCU = I->second;
2059     // Start the dwarf pubtypes section.
2060     Asm->OutStreamer.SwitchSection(
2061       Asm->getObjFileLowering().getDwarfPubTypesSection());
2062     Asm->OutStreamer.AddComment("Length of Public Types Info");
2063     Asm->EmitLabelDifference(
2064       Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2065       Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2066
2067     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2068                                                   TheCU->getUniqueID()));
2069
2070     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2071     Asm->EmitInt16(dwarf::DWARF_VERSION);
2072
2073     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2074     const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2075     Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2076                                               TheCU->getUniqueID()),
2077                            DwarfInfoSectionSym);
2078
2079     Asm->OutStreamer.AddComment("Compilation Unit Length");
2080     Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2081                                                 TheCU->getUniqueID()),
2082                              Asm->GetTempSymbol(ISec->getLabelBeginName(),
2083                                                 TheCU->getUniqueID()),
2084                              4);
2085
2086     const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2087     for (StringMap<DIE*>::const_iterator
2088            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2089       const char *Name = GI->getKeyData();
2090       DIE *Entity = GI->second;
2091
2092       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2093       Asm->EmitInt32(Entity->getOffset());
2094
2095       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2096       // Emit the name with a terminating null byte.
2097       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2098     }
2099
2100     Asm->OutStreamer.AddComment("End Mark");
2101     Asm->EmitInt32(0);
2102     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2103                                                   TheCU->getUniqueID()));
2104   }
2105 }
2106
2107 // Emit visible names into a debug str section.
2108 void DwarfDebug::emitDebugStr() {
2109   // Check to see if it is worth the effort.
2110   if (StringPool.empty()) return;
2111
2112   // Start the dwarf str section.
2113   Asm->OutStreamer.SwitchSection(
2114                                 Asm->getObjFileLowering().getDwarfStrSection());
2115
2116   // Get all of the string pool entries and put them in an array by their ID so
2117   // we can sort them.
2118   SmallVector<std::pair<unsigned,
2119       StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2120
2121   for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2122        I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2123     Entries.push_back(std::make_pair(I->second.second, &*I));
2124
2125   array_pod_sort(Entries.begin(), Entries.end());
2126
2127   for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2128     // Emit a label for reference from debug information entries.
2129     Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2130
2131     // Emit the string itself with a terminating null byte.
2132     Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2133                                          Entries[i].second->getKeyLength()+1),
2134                                0/*addrspace*/);
2135   }
2136 }
2137
2138 // Emit visible names into a debug loc section.
2139 void DwarfDebug::emitDebugLoc() {
2140   if (DotDebugLocEntries.empty())
2141     return;
2142
2143   for (SmallVector<DotDebugLocEntry, 4>::iterator
2144          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2145        I != E; ++I) {
2146     DotDebugLocEntry &Entry = *I;
2147     if (I + 1 != DotDebugLocEntries.end())
2148       Entry.Merge(I+1);
2149   }
2150
2151   // Start the dwarf loc section.
2152   Asm->OutStreamer.SwitchSection(
2153     Asm->getObjFileLowering().getDwarfLocSection());
2154   unsigned char Size = Asm->getDataLayout().getPointerSize();
2155   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2156   unsigned index = 1;
2157   for (SmallVector<DotDebugLocEntry, 4>::iterator
2158          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2159        I != E; ++I, ++index) {
2160     DotDebugLocEntry &Entry = *I;
2161     if (Entry.isMerged()) continue;
2162     if (Entry.isEmpty()) {
2163       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2164       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2165       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2166     } else {
2167       Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2168       Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2169       DIVariable DV(Entry.Variable);
2170       Asm->OutStreamer.AddComment("Loc expr size");
2171       MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2172       MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2173       Asm->EmitLabelDifference(end, begin, 2);
2174       Asm->OutStreamer.EmitLabel(begin);
2175       if (Entry.isInt()) {
2176         DIBasicType BTy(DV.getType());
2177         if (BTy.Verify() &&
2178             (BTy.getEncoding()  == dwarf::DW_ATE_signed
2179              || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2180           Asm->OutStreamer.AddComment("DW_OP_consts");
2181           Asm->EmitInt8(dwarf::DW_OP_consts);
2182           Asm->EmitSLEB128(Entry.getInt());
2183         } else {
2184           Asm->OutStreamer.AddComment("DW_OP_constu");
2185           Asm->EmitInt8(dwarf::DW_OP_constu);
2186           Asm->EmitULEB128(Entry.getInt());
2187         }
2188       } else if (Entry.isLocation()) {
2189         if (!DV.hasComplexAddress())
2190           // Regular entry.
2191           Asm->EmitDwarfRegOp(Entry.Loc);
2192         else {
2193           // Complex address entry.
2194           unsigned N = DV.getNumAddrElements();
2195           unsigned i = 0;
2196           if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2197             if (Entry.Loc.getOffset()) {
2198               i = 2;
2199               Asm->EmitDwarfRegOp(Entry.Loc);
2200               Asm->OutStreamer.AddComment("DW_OP_deref");
2201               Asm->EmitInt8(dwarf::DW_OP_deref);
2202               Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2203               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2204               Asm->EmitSLEB128(DV.getAddrElement(1));
2205             } else {
2206               // If first address element is OpPlus then emit
2207               // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2208               MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2209               Asm->EmitDwarfRegOp(Loc);
2210               i = 2;
2211             }
2212           } else {
2213             Asm->EmitDwarfRegOp(Entry.Loc);
2214           }
2215
2216           // Emit remaining complex address elements.
2217           for (; i < N; ++i) {
2218             uint64_t Element = DV.getAddrElement(i);
2219             if (Element == DIBuilder::OpPlus) {
2220               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2221               Asm->EmitULEB128(DV.getAddrElement(++i));
2222             } else if (Element == DIBuilder::OpDeref) {
2223               if (!Entry.Loc.isReg())
2224                 Asm->EmitInt8(dwarf::DW_OP_deref);
2225             } else
2226               llvm_unreachable("unknown Opcode found in complex address");
2227           }
2228         }
2229       }
2230       // else ... ignore constant fp. There is not any good way to
2231       // to represent them here in dwarf.
2232       Asm->OutStreamer.EmitLabel(end);
2233     }
2234   }
2235 }
2236
2237 // Emit visible names into a debug aranges section.
2238 void DwarfDebug::emitDebugARanges() {
2239   // Start the dwarf aranges section.
2240   Asm->OutStreamer.SwitchSection(
2241                           Asm->getObjFileLowering().getDwarfARangesSection());
2242 }
2243
2244 // Emit visible names into a debug ranges section.
2245 void DwarfDebug::emitDebugRanges() {
2246   // Start the dwarf ranges section.
2247   Asm->OutStreamer.SwitchSection(
2248     Asm->getObjFileLowering().getDwarfRangesSection());
2249   unsigned char Size = Asm->getDataLayout().getPointerSize();
2250   for (SmallVector<const MCSymbol *, 8>::iterator
2251          I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2252        I != E; ++I) {
2253     if (*I)
2254       Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2255     else
2256       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2257   }
2258 }
2259
2260 // Emit visible names into a debug macinfo section.
2261 void DwarfDebug::emitDebugMacInfo() {
2262   if (const MCSection *LineInfo =
2263       Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2264     // Start the dwarf macinfo section.
2265     Asm->OutStreamer.SwitchSection(LineInfo);
2266   }
2267 }
2268
2269 // Emit inline info using following format.
2270 // Section Header:
2271 // 1. length of section
2272 // 2. Dwarf version number
2273 // 3. address size.
2274 //
2275 // Entries (one "entry" for each function that was inlined):
2276 //
2277 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2278 //   otherwise offset into __debug_str for regular function name.
2279 // 2. offset into __debug_str section for regular function name.
2280 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2281 // instances for the function.
2282 //
2283 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2284 // inlined instance; the die_offset points to the inlined_subroutine die in the
2285 // __debug_info section, and the low_pc is the starting address for the
2286 // inlining instance.
2287 void DwarfDebug::emitDebugInlineInfo() {
2288   if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2289     return;
2290
2291   if (!FirstCU)
2292     return;
2293
2294   Asm->OutStreamer.SwitchSection(
2295                         Asm->getObjFileLowering().getDwarfDebugInlineSection());
2296
2297   Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2298   Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2299                            Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2300
2301   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2302
2303   Asm->OutStreamer.AddComment("Dwarf Version");
2304   Asm->EmitInt16(dwarf::DWARF_VERSION);
2305   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2306   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2307
2308   for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2309          E = InlinedSPNodes.end(); I != E; ++I) {
2310
2311     const MDNode *Node = *I;
2312     DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2313       = InlineInfo.find(Node);
2314     SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2315     DISubprogram SP(Node);
2316     StringRef LName = SP.getLinkageName();
2317     StringRef Name = SP.getName();
2318
2319     Asm->OutStreamer.AddComment("MIPS linkage name");
2320     if (LName.empty())
2321       Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2322     else
2323       Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2324                              DwarfStrSectionSym);
2325
2326     Asm->OutStreamer.AddComment("Function name");
2327     Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2328     Asm->EmitULEB128(Labels.size(), "Inline count");
2329
2330     for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2331            LE = Labels.end(); LI != LE; ++LI) {
2332       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2333       Asm->EmitInt32(LI->second->getOffset());
2334
2335       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2336       Asm->OutStreamer.EmitSymbolValue(LI->first,
2337                                        Asm->getDataLayout().getPointerSize(),0);
2338     }
2339   }
2340
2341   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2342 }
2343
2344 // DWARF5 Experimental Separate Dwarf emitters.
2345
2346 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2347 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2348 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2349 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2350 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2351   DICompileUnit DIUnit(N);
2352   StringRef FN = DIUnit.getFilename();
2353   CompilationDir = DIUnit.getDirectory();
2354
2355   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2356   CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2357                                        DIUnit.getLanguage(), Die, Asm, this);
2358   // FIXME: This should be the .dwo file.
2359   NewCU->addString(Die, dwarf::DW_AT_GNU_dwo_name, FN);
2360
2361   // FIXME: We also need DW_AT_addr_base and DW_AT_dwo_id.
2362
2363   // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2364   // into an entity.
2365   NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2366   // DW_AT_stmt_list is a offset of line number information for this
2367   // compile unit in debug_line section.
2368   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2369     NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
2370                     Asm->GetTempSymbol("section_line"));
2371   else
2372     NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
2373
2374   if (!CompilationDir.empty())
2375     NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2376
2377   SkeletonHolder.addUnit(NewCU);
2378
2379   return NewCU;
2380 }
2381
2382 void DwarfDebug::emitSkeletonCU(const MCSection *Section) {
2383   Asm->OutStreamer.SwitchSection(Section);
2384   DIE *Die = SkeletonCU->getCUDie();
2385
2386   // Emit the compile units header.
2387   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelBeginName(),
2388                                                 SkeletonCU->getUniqueID()));
2389
2390   // Emit size of content not including length itself
2391   unsigned ContentSize = Die->getSize() +
2392     sizeof(int16_t) + // DWARF version number
2393     sizeof(int32_t) + // Offset Into Abbrev. Section
2394     sizeof(int8_t);   // Pointer Size (in bytes)
2395
2396   Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2397   Asm->EmitInt32(ContentSize);
2398   Asm->OutStreamer.AddComment("DWARF version number");
2399   Asm->EmitInt16(dwarf::DWARF_VERSION);
2400   Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2401
2402   const MCSection *ASec = Asm->getObjFileLowering().getDwarfAbbrevSection();
2403   Asm->EmitSectionOffset(Asm->GetTempSymbol(ASec->getLabelBeginName()),
2404                          DwarfAbbrevSectionSym);
2405   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2406   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2407
2408   emitDIE(Die, &SkeletonAbbrevs);
2409   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelEndName(),
2410                                                 SkeletonCU->getUniqueID()));
2411 }
2412
2413 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2414   assert(useSplitDwarf() && "No split dwarf debug info?");
2415   emitAbbrevs(Section, &SkeletonAbbrevs);
2416 }
2417
2418 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2419 // compile units that would normally be in debug_info.
2420 void DwarfDebug::emitDebugInfoDWO() {
2421   assert(useSplitDwarf() && "No split dwarf debug info?");
2422   InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2423                        Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2424                        DwarfAbbrevDWOSectionSym);
2425 }
2426
2427 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2428 // abbreviations for the .debug_info.dwo section.
2429 void DwarfDebug::emitDebugAbbrevDWO() {
2430   assert(useSplitDwarf() && "No split dwarf?");
2431   emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(), &Abbreviations);
2432 }