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