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