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