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