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