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