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