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