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