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