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 "DwarfDebug.h"
15 #include "ByteStreamer.h"
16 #include "DIEHash.h"
17 #include "DebugLocEntry.h"
18 #include "DwarfCompileUnit.h"
19 #include "DwarfExpression.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/DIE.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCDwarf.h"
36 #include "llvm/MC/MCSection.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Dwarf.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/LEB128.h"
46 #include "llvm/Support/MD5.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Timer.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetFrameLowering.h"
51 #include "llvm/Target/TargetLoweringObjectFile.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Target/TargetSubtargetInfo.h"
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "dwarfdebug"
60 
61 static cl::opt<bool>
62 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
63                          cl::desc("Disable debug info printing"));
64 
65 static cl::opt<bool> UnknownLocations(
66     "use-unknown-locations", cl::Hidden,
67     cl::desc("Make an absence of debug location information explicit."),
68     cl::init(false));
69 
70 static cl::opt<bool>
71 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
72                        cl::desc("Generate GNU-style pubnames and pubtypes"),
73                        cl::init(false));
74 
75 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
76                                            cl::Hidden,
77                                            cl::desc("Generate dwarf aranges"),
78                                            cl::init(false));
79 
80 namespace {
81 enum DefaultOnOff { Default, Enable, Disable };
82 }
83 
84 static cl::opt<DefaultOnOff>
85 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
86                  cl::desc("Output prototype dwarf accelerator tables."),
87                  cl::values(clEnumVal(Default, "Default for platform"),
88                             clEnumVal(Enable, "Enabled"),
89                             clEnumVal(Disable, "Disabled")),
90                  cl::init(Default));
91 
92 static cl::opt<DefaultOnOff>
93 SplitDwarf("split-dwarf", cl::Hidden,
94            cl::desc("Output DWARF5 split debug info."),
95            cl::values(clEnumVal(Default, "Default for platform"),
96                       clEnumVal(Enable, "Enabled"),
97                       clEnumVal(Disable, "Disabled")),
98            cl::init(Default));
99 
100 static cl::opt<DefaultOnOff>
101 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
102                  cl::desc("Generate DWARF pubnames and pubtypes sections"),
103                  cl::values(clEnumVal(Default, "Default for platform"),
104                             clEnumVal(Enable, "Enabled"),
105                             clEnumVal(Disable, "Disabled")),
106                  cl::init(Default));
107 
108 enum LinkageNameOption {
109   DefaultLinkageNames,
110   AllLinkageNames,
111   AbstractLinkageNames
112 };
113 static cl::opt<LinkageNameOption>
114     DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
115                       cl::desc("Which DWARF linkage-name attributes to emit."),
116                       cl::values(clEnumValN(DefaultLinkageNames, "Default",
117                                             "Default for platform"),
118                                  clEnumValN(AllLinkageNames, "All", "All"),
119                                  clEnumValN(AbstractLinkageNames, "Abstract",
120                                             "Abstract subprograms")),
121                       cl::init(DefaultLinkageNames));
122 
123 static const char *const DWARFGroupName = "dwarf";
124 static const char *const DWARFGroupDescription = "DWARF Emission";
125 static const char *const DbgTimerName = "writer";
126 static const char *const DbgTimerDescription = "DWARF Debug Writer";
127 
128 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
129   BS.EmitInt8(
130       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
131                   : dwarf::OperationEncodingString(Op));
132 }
133 
134 void DebugLocDwarfExpression::EmitSigned(int64_t Value) {
135   BS.EmitSLEB128(Value, Twine(Value));
136 }
137 
138 void DebugLocDwarfExpression::EmitUnsigned(uint64_t Value) {
139   BS.EmitULEB128(Value, Twine(Value));
140 }
141 
142 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
143                                               unsigned MachineReg) {
144   // This information is not available while emitting .debug_loc entries.
145   return false;
146 }
147 
148 //===----------------------------------------------------------------------===//
149 
150 bool DbgVariable::isBlockByrefVariable() const {
151   assert(Var && "Invalid complex DbgVariable!");
152   return Var->getType().resolve()->isBlockByrefStruct();
153 }
154 
155 const DIType *DbgVariable::getType() const {
156   DIType *Ty = Var->getType().resolve();
157   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
158   // addresses instead.
159   if (Ty->isBlockByrefStruct()) {
160     /* Byref variables, in Blocks, are declared by the programmer as
161        "SomeType VarName;", but the compiler creates a
162        __Block_byref_x_VarName struct, and gives the variable VarName
163        either the struct, or a pointer to the struct, as its type.  This
164        is necessary for various behind-the-scenes things the compiler
165        needs to do with by-reference variables in blocks.
166 
167        However, as far as the original *programmer* is concerned, the
168        variable should still have type 'SomeType', as originally declared.
169 
170        The following function dives into the __Block_byref_x_VarName
171        struct to find the original type of the variable.  This will be
172        passed back to the code generating the type for the Debug
173        Information Entry for the variable 'VarName'.  'VarName' will then
174        have the original type 'SomeType' in its debug information.
175 
176        The original type 'SomeType' will be the type of the field named
177        'VarName' inside the __Block_byref_x_VarName struct.
178 
179        NOTE: In order for this to not completely fail on the debugger
180        side, the Debug Information Entry for the variable VarName needs to
181        have a DW_AT_location that tells the debugger how to unwind through
182        the pointers and __Block_byref_x_VarName struct to find the actual
183        value of the variable.  The function addBlockByrefType does this.  */
184     DIType *subType = Ty;
185     uint16_t tag = Ty->getTag();
186 
187     if (tag == dwarf::DW_TAG_pointer_type)
188       subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
189 
190     auto Elements = cast<DICompositeType>(subType)->getElements();
191     for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
192       auto *DT = cast<DIDerivedType>(Elements[i]);
193       if (getName() == DT->getName())
194         return resolve(DT->getBaseType());
195     }
196   }
197   return Ty;
198 }
199 
200 static const DwarfAccelTable::Atom TypeAtoms[] = {
201     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
202     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
203     DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
204 
205 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
206     : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
207       InfoHolder(A, "info_string", DIEValueAllocator),
208       SkeletonHolder(A, "skel_string", DIEValueAllocator),
209       IsDarwin(A->TM.getTargetTriple().isOSDarwin()),
210       AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
211                                        dwarf::DW_FORM_data4)),
212       AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
213                                       dwarf::DW_FORM_data4)),
214       AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
215                                            dwarf::DW_FORM_data4)),
216       AccelTypes(TypeAtoms), DebuggerTuning(DebuggerKind::Default) {
217 
218   CurFn = nullptr;
219   const Triple &TT = Asm->TM.getTargetTriple();
220 
221   // Make sure we know our "debugger tuning."  The target option takes
222   // precedence; fall back to triple-based defaults.
223   if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
224     DebuggerTuning = Asm->TM.Options.DebuggerTuning;
225   else if (IsDarwin)
226     DebuggerTuning = DebuggerKind::LLDB;
227   else if (TT.isPS4CPU())
228     DebuggerTuning = DebuggerKind::SCE;
229   else
230     DebuggerTuning = DebuggerKind::GDB;
231 
232   // Turn on accelerator tables for LLDB by default.
233   if (DwarfAccelTables == Default)
234     HasDwarfAccelTables = tuneForLLDB();
235   else
236     HasDwarfAccelTables = DwarfAccelTables == Enable;
237 
238   HasAppleExtensionAttributes = tuneForLLDB();
239 
240   // Handle split DWARF. Off by default for now.
241   if (SplitDwarf == Default)
242     HasSplitDwarf = false;
243   else
244     HasSplitDwarf = SplitDwarf == Enable;
245 
246   // Pubnames/pubtypes on by default for GDB.
247   if (DwarfPubSections == Default)
248     HasDwarfPubSections = tuneForGDB();
249   else
250     HasDwarfPubSections = DwarfPubSections == Enable;
251 
252   // SCE defaults to linkage names only for abstract subprograms.
253   if (DwarfLinkageNames == DefaultLinkageNames)
254     UseAllLinkageNames = !tuneForSCE();
255   else
256     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
257 
258   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
259   DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
260                                     : MMI->getModule()->getDwarfVersion();
261   // Use dwarf 4 by default if nothing is requested.
262   DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION;
263 
264   // Work around a GDB bug. GDB doesn't support the standard opcode;
265   // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
266   // is defined as of DWARF 3.
267   // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
268   // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
269   UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
270 
271   // GDB does not fully support the DWARF 4 representation for bitfields.
272   UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
273 
274   Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
275 }
276 
277 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
278 DwarfDebug::~DwarfDebug() { }
279 
280 static bool isObjCClass(StringRef Name) {
281   return Name.startswith("+") || Name.startswith("-");
282 }
283 
284 static bool hasObjCCategory(StringRef Name) {
285   if (!isObjCClass(Name))
286     return false;
287 
288   return Name.find(") ") != StringRef::npos;
289 }
290 
291 static void getObjCClassCategory(StringRef In, StringRef &Class,
292                                  StringRef &Category) {
293   if (!hasObjCCategory(In)) {
294     Class = In.slice(In.find('[') + 1, In.find(' '));
295     Category = "";
296     return;
297   }
298 
299   Class = In.slice(In.find('[') + 1, In.find('('));
300   Category = In.slice(In.find('[') + 1, In.find(' '));
301 }
302 
303 static StringRef getObjCMethodName(StringRef In) {
304   return In.slice(In.find(' ') + 1, In.find(']'));
305 }
306 
307 // Add the various names to the Dwarf accelerator table names.
308 // TODO: Determine whether or not we should add names for programs
309 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
310 // is only slightly different than the lookup of non-standard ObjC names.
311 void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
312   if (!SP->isDefinition())
313     return;
314   addAccelName(SP->getName(), Die);
315 
316   // If the linkage name is different than the name, go ahead and output
317   // that as well into the name table.
318   if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
319     addAccelName(SP->getLinkageName(), Die);
320 
321   // If this is an Objective-C selector name add it to the ObjC accelerator
322   // too.
323   if (isObjCClass(SP->getName())) {
324     StringRef Class, Category;
325     getObjCClassCategory(SP->getName(), Class, Category);
326     addAccelObjC(Class, Die);
327     if (Category != "")
328       addAccelObjC(Category, Die);
329     // Also add the base method name to the name table.
330     addAccelName(getObjCMethodName(SP->getName()), Die);
331   }
332 }
333 
334 /// Check whether we should create a DIE for the given Scope, return true
335 /// if we don't create a DIE (the corresponding DIE is null).
336 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
337   if (Scope->isAbstractScope())
338     return false;
339 
340   // We don't create a DIE if there is no Range.
341   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
342   if (Ranges.empty())
343     return true;
344 
345   if (Ranges.size() > 1)
346     return false;
347 
348   // We don't create a DIE if we have a single Range and the end label
349   // is null.
350   return !getLabelAfterInsn(Ranges.front().second);
351 }
352 
353 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
354   F(CU);
355   if (auto *SkelCU = CU.getSkeleton())
356     if (CU.getCUNode()->getSplitDebugInlining())
357       F(*SkelCU);
358 }
359 
360 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
361   assert(Scope && Scope->getScopeNode());
362   assert(Scope->isAbstractScope());
363   assert(!Scope->getInlinedAt());
364 
365   const MDNode *SP = Scope->getScopeNode();
366 
367   ProcessedSPNodes.insert(SP);
368 
369   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
370   // was inlined from another compile unit.
371   auto &CU = *CUMap.lookup(cast<DISubprogram>(SP)->getUnit());
372   forBothCUs(CU, [&](DwarfCompileUnit &CU) {
373     CU.constructAbstractSubprogramScopeDIE(Scope);
374   });
375 }
376 
377 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
378   if (!GenerateGnuPubSections)
379     return;
380 
381   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
382 }
383 
384 // Create new DwarfCompileUnit for the given metadata node with tag
385 // DW_TAG_compile_unit.
386 DwarfCompileUnit &
387 DwarfDebug::constructDwarfCompileUnit(const DICompileUnit *DIUnit) {
388   StringRef FN = DIUnit->getFilename();
389   CompilationDir = DIUnit->getDirectory();
390 
391   auto OwnedUnit = make_unique<DwarfCompileUnit>(
392       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
393   DwarfCompileUnit &NewCU = *OwnedUnit;
394   DIE &Die = NewCU.getUnitDie();
395   InfoHolder.addUnit(std::move(OwnedUnit));
396   if (useSplitDwarf()) {
397     NewCU.setSkeleton(constructSkeletonCU(NewCU));
398     NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
399                     DIUnit->getSplitDebugFilename());
400   }
401 
402   // LTO with assembly output shares a single line table amongst multiple CUs.
403   // To avoid the compilation directory being ambiguous, let the line table
404   // explicitly describe the directory of all files, never relying on the
405   // compilation directory.
406   if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
407     Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
408         NewCU.getUniqueID(), CompilationDir);
409 
410   NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit->getProducer());
411   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
412                 DIUnit->getSourceLanguage());
413   NewCU.addString(Die, dwarf::DW_AT_name, FN);
414 
415   if (!useSplitDwarf()) {
416     NewCU.initStmtList();
417 
418     // If we're using split dwarf the compilation dir is going to be in the
419     // skeleton CU and so we don't need to duplicate it here.
420     if (!CompilationDir.empty())
421       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
422 
423     addGnuPubAttributes(NewCU, Die);
424   }
425 
426   if (useAppleExtensionAttributes()) {
427     if (DIUnit->isOptimized())
428       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
429 
430     StringRef Flags = DIUnit->getFlags();
431     if (!Flags.empty())
432       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
433 
434     if (unsigned RVer = DIUnit->getRuntimeVersion())
435       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
436                     dwarf::DW_FORM_data1, RVer);
437   }
438 
439   if (useSplitDwarf())
440     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
441   else
442     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
443 
444   if (DIUnit->getDWOId()) {
445     // This CU is either a clang module DWO or a skeleton CU.
446     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
447                   DIUnit->getDWOId());
448     if (!DIUnit->getSplitDebugFilename().empty())
449       // This is a prefabricated skeleton CU.
450       NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
451                       DIUnit->getSplitDebugFilename());
452   }
453 
454   CUMap.insert({DIUnit, &NewCU});
455   CUDieMap.insert({&Die, &NewCU});
456   return NewCU;
457 }
458 
459 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
460                                                   const DIImportedEntity *N) {
461   if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
462     D->addChild(TheCU.constructImportedEntityDIE(N));
463 }
464 
465 // Emit all Dwarf sections that should come prior to the content. Create
466 // global DIEs and emit initial debug info sections. This is invoked by
467 // the target AsmPrinter.
468 void DwarfDebug::beginModule() {
469   NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
470                      DWARFGroupDescription, TimePassesIsEnabled);
471   if (DisableDebugInfoPrinting)
472     return;
473 
474   const Module *M = MMI->getModule();
475 
476   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
477                                        M->debug_compile_units_end());
478   // Tell MMI whether we have debug info.
479   MMI->setDebugInfoAvailability(NumDebugCUs > 0);
480   SingleCU = NumDebugCUs == 1;
481 
482   DenseMap<DIGlobalVariable *, const GlobalVariable *> GVMap;
483   for (const GlobalVariable &Global : M->globals()) {
484     SmallVector<DIGlobalVariable *, 1> GVs;
485     Global.getDebugInfo(GVs);
486     for (auto &GV : GVs)
487       GVMap[GV] = &Global;
488   }
489 
490   for (DICompileUnit *CUNode : M->debug_compile_units()) {
491     DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
492     for (auto *IE : CUNode->getImportedEntities())
493       CU.addImportedEntity(IE);
494     for (auto *GV : CUNode->getGlobalVariables())
495       CU.getOrCreateGlobalVariableDIE(GV, GVMap.lookup(GV));
496     for (auto *Ty : CUNode->getEnumTypes()) {
497       // The enum types array by design contains pointers to
498       // MDNodes rather than DIRefs. Unique them here.
499       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
500     }
501     for (auto *Ty : CUNode->getRetainedTypes()) {
502       // The retained types array by design contains pointers to
503       // MDNodes rather than DIRefs. Unique them here.
504       if (DIType *RT = dyn_cast<DIType>(Ty))
505         if (!RT->isExternalTypeRef())
506           // There is no point in force-emitting a forward declaration.
507           CU.getOrCreateTypeDIE(RT);
508     }
509     // Emit imported_modules last so that the relevant context is already
510     // available.
511     for (auto *IE : CUNode->getImportedEntities())
512       constructAndAddImportedEntityDIE(CU, IE);
513   }
514 }
515 
516 void DwarfDebug::finishVariableDefinitions() {
517   for (const auto &Var : ConcreteVariables) {
518     DIE *VariableDie = Var->getDIE();
519     assert(VariableDie);
520     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
521     // in the ConcreteVariables list, rather than looking it up again here.
522     // DIE::getUnit isn't simple - it walks parent pointers, etc.
523     DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
524     assert(Unit);
525     DbgVariable *AbsVar = getExistingAbstractVariable(
526         InlinedVariable(Var->getVariable(), Var->getInlinedAt()));
527     if (AbsVar && AbsVar->getDIE()) {
528       Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
529                         *AbsVar->getDIE());
530     } else
531       Unit->applyVariableAttributes(*Var, *VariableDie);
532   }
533 }
534 
535 void DwarfDebug::finishSubprogramDefinitions() {
536   for (auto &F : MMI->getModule()->functions())
537     if (auto *SP = F.getSubprogram())
538       if (ProcessedSPNodes.count(SP) &&
539           SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug)
540         forBothCUs(*CUMap.lookup(SP->getUnit()), [&](DwarfCompileUnit &CU) {
541           CU.finishSubprogramDefinition(SP);
542         });
543 }
544 
545 void DwarfDebug::finalizeModuleInfo() {
546   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
547 
548   finishSubprogramDefinitions();
549 
550   finishVariableDefinitions();
551 
552   // Handle anything that needs to be done on a per-unit basis after
553   // all other generation.
554   for (const auto &P : CUMap) {
555     auto &TheCU = *P.second;
556     // Emit DW_AT_containing_type attribute to connect types with their
557     // vtable holding type.
558     TheCU.constructContainingTypeDIEs();
559 
560     // Add CU specific attributes if we need to add any.
561     // If we're splitting the dwarf out now that we've got the entire
562     // CU then add the dwo id to it.
563     auto *SkCU = TheCU.getSkeleton();
564     if (useSplitDwarf()) {
565       // Emit a unique identifier for this CU.
566       uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
567       TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
568                     dwarf::DW_FORM_data8, ID);
569       SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
570                     dwarf::DW_FORM_data8, ID);
571 
572       // We don't keep track of which addresses are used in which CU so this
573       // is a bit pessimistic under LTO.
574       if (!AddrPool.isEmpty()) {
575         const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
576         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
577                               Sym, Sym);
578       }
579       if (!SkCU->getRangeLists().empty()) {
580         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
581         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
582                               Sym, Sym);
583       }
584     }
585 
586     // If we have code split among multiple sections or non-contiguous
587     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
588     // remain in the .o file, otherwise add a DW_AT_low_pc.
589     // FIXME: We should use ranges allow reordering of code ala
590     // .subsections_via_symbols in mach-o. This would mean turning on
591     // ranges for all subprogram DIEs for mach-o.
592     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
593     if (unsigned NumRanges = TheCU.getRanges().size()) {
594       if (NumRanges > 1)
595         // A DW_AT_low_pc attribute may also be specified in combination with
596         // DW_AT_ranges to specify the default base address for use in
597         // location lists (see Section 2.6.2) and range lists (see Section
598         // 2.17.3).
599         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
600       else
601         U.setBaseAddress(TheCU.getRanges().front().getStart());
602       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
603     }
604 
605     auto *CUNode = cast<DICompileUnit>(P.first);
606     // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
607     if (CUNode->getMacros())
608       U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
609                         U.getMacroLabelBegin(),
610                         TLOF.getDwarfMacinfoSection()->getBeginSymbol());
611   }
612 
613   // Compute DIE offsets and sizes.
614   InfoHolder.computeSizeAndOffsets();
615   if (useSplitDwarf())
616     SkeletonHolder.computeSizeAndOffsets();
617 }
618 
619 // Emit all Dwarf sections that should come after the content.
620 void DwarfDebug::endModule() {
621   assert(CurFn == nullptr);
622   assert(CurMI == nullptr);
623 
624   // If we aren't actually generating debug info (check beginModule -
625   // conditionalized on !DisableDebugInfoPrinting and the presence of the
626   // llvm.dbg.cu metadata node)
627   if (!MMI->hasDebugInfo())
628     return;
629 
630   // Finalize the debug info for the module.
631   finalizeModuleInfo();
632 
633   emitDebugStr();
634 
635   if (useSplitDwarf())
636     emitDebugLocDWO();
637   else
638     // Emit info into a debug loc section.
639     emitDebugLoc();
640 
641   // Corresponding abbreviations into a abbrev section.
642   emitAbbreviations();
643 
644   // Emit all the DIEs into a debug info section.
645   emitDebugInfo();
646 
647   // Emit info into a debug aranges section.
648   if (GenerateARangeSection)
649     emitDebugARanges();
650 
651   // Emit info into a debug ranges section.
652   emitDebugRanges();
653 
654   // Emit info into a debug macinfo section.
655   emitDebugMacinfo();
656 
657   if (useSplitDwarf()) {
658     emitDebugStrDWO();
659     emitDebugInfoDWO();
660     emitDebugAbbrevDWO();
661     emitDebugLineDWO();
662     // Emit DWO addresses.
663     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
664   }
665 
666   // Emit info into the dwarf accelerator table sections.
667   if (useDwarfAccelTables()) {
668     emitAccelNames();
669     emitAccelObjC();
670     emitAccelNamespaces();
671     emitAccelTypes();
672   }
673 
674   // Emit the pubnames and pubtypes sections if requested.
675   if (HasDwarfPubSections) {
676     emitDebugPubNames(GenerateGnuPubSections);
677     emitDebugPubTypes(GenerateGnuPubSections);
678   }
679 
680   // clean up.
681   AbstractVariables.clear();
682 }
683 
684 // Find abstract variable, if any, associated with Var.
685 DbgVariable *
686 DwarfDebug::getExistingAbstractVariable(InlinedVariable IV,
687                                         const DILocalVariable *&Cleansed) {
688   // More then one inlined variable corresponds to one abstract variable.
689   Cleansed = IV.first;
690   auto I = AbstractVariables.find(Cleansed);
691   if (I != AbstractVariables.end())
692     return I->second.get();
693   return nullptr;
694 }
695 
696 DbgVariable *DwarfDebug::getExistingAbstractVariable(InlinedVariable IV) {
697   const DILocalVariable *Cleansed;
698   return getExistingAbstractVariable(IV, Cleansed);
699 }
700 
701 void DwarfDebug::createAbstractVariable(const DILocalVariable *Var,
702                                         LexicalScope *Scope) {
703   auto AbsDbgVariable = make_unique<DbgVariable>(Var, /* IA */ nullptr);
704   InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
705   AbstractVariables[Var] = std::move(AbsDbgVariable);
706 }
707 
708 void DwarfDebug::ensureAbstractVariableIsCreated(InlinedVariable IV,
709                                                  const MDNode *ScopeNode) {
710   const DILocalVariable *Cleansed = nullptr;
711   if (getExistingAbstractVariable(IV, Cleansed))
712     return;
713 
714   createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
715                                        cast<DILocalScope>(ScopeNode)));
716 }
717 
718 void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(
719     InlinedVariable IV, const MDNode *ScopeNode) {
720   const DILocalVariable *Cleansed = nullptr;
721   if (getExistingAbstractVariable(IV, Cleansed))
722     return;
723 
724   if (LexicalScope *Scope =
725           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
726     createAbstractVariable(Cleansed, Scope);
727 }
728 
729 // Collect variable information from side table maintained by MMI.
730 void DwarfDebug::collectVariableInfoFromMMITable(
731     DenseSet<InlinedVariable> &Processed) {
732   for (const auto &VI : MMI->getVariableDbgInfo()) {
733     if (!VI.Var)
734       continue;
735     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
736            "Expected inlined-at fields to agree");
737 
738     InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
739     Processed.insert(Var);
740     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
741 
742     // If variable scope is not found then skip this variable.
743     if (!Scope)
744       continue;
745 
746     ensureAbstractVariableIsCreatedIfScoped(Var, Scope->getScopeNode());
747     auto RegVar = make_unique<DbgVariable>(Var.first, Var.second);
748     RegVar->initializeMMI(VI.Expr, VI.Slot);
749     if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
750       ConcreteVariables.push_back(std::move(RegVar));
751   }
752 }
753 
754 // Get .debug_loc entry for the instruction range starting at MI.
755 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
756   const DIExpression *Expr = MI->getDebugExpression();
757 
758   assert(MI->getNumOperands() == 4);
759   if (MI->getOperand(0).isReg()) {
760     MachineLocation MLoc;
761     // If the second operand is an immediate, this is a
762     // register-indirect address.
763     if (!MI->getOperand(1).isImm())
764       MLoc.set(MI->getOperand(0).getReg());
765     else
766       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
767     return DebugLocEntry::Value(Expr, MLoc);
768   }
769   if (MI->getOperand(0).isImm())
770     return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
771   if (MI->getOperand(0).isFPImm())
772     return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
773   if (MI->getOperand(0).isCImm())
774     return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
775 
776   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
777 }
778 
779 /// \brief If this and Next are describing different pieces of the same
780 /// variable, merge them by appending Next's values to the current
781 /// list of values.
782 /// Return true if the merge was successful.
783 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
784   if (Begin == Next.Begin) {
785     auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
786     auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
787     if (!FirstExpr->isBitPiece() || !FirstNextExpr->isBitPiece())
788       return false;
789 
790     // We can only merge entries if none of the pieces overlap any others.
791     // In doing so, we can take advantage of the fact that both lists are
792     // sorted.
793     for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
794       for (; j < Next.Values.size(); ++j) {
795         int res = DebugHandlerBase::pieceCmp(
796             cast<DIExpression>(Values[i].Expression),
797             cast<DIExpression>(Next.Values[j].Expression));
798         if (res == 0) // The two expressions overlap, we can't merge.
799           return false;
800         // Values[i] is entirely before Next.Values[j],
801         // so go back to the next entry of Values.
802         else if (res == -1)
803           break;
804         // Next.Values[j] is entirely before Values[i], so go on to the
805         // next entry of Next.Values.
806       }
807     }
808 
809     addValues(Next.Values);
810     End = Next.End;
811     return true;
812   }
813   return false;
814 }
815 
816 /// Build the location list for all DBG_VALUEs in the function that
817 /// describe the same variable.  If the ranges of several independent
818 /// pieces of the same variable overlap partially, split them up and
819 /// combine the ranges. The resulting DebugLocEntries are will have
820 /// strict monotonically increasing begin addresses and will never
821 /// overlap.
822 //
823 // Input:
824 //
825 //   Ranges History [var, loc, piece ofs size]
826 // 0 |      [x, (reg0, piece 0, 32)]
827 // 1 | |    [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
828 // 2 | |    ...
829 // 3   |    [clobber reg0]
830 // 4        [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
831 //                                     x.
832 //
833 // Output:
834 //
835 // [0-1]    [x, (reg0, piece  0, 32)]
836 // [1-3]    [x, (reg0, piece  0, 32), (reg1, piece 32, 32)]
837 // [3-4]    [x, (reg1, piece 32, 32)]
838 // [4- ]    [x, (mem,  piece  0, 64)]
839 void
840 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
841                               const DbgValueHistoryMap::InstrRanges &Ranges) {
842   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
843 
844   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
845     const MachineInstr *Begin = I->first;
846     const MachineInstr *End = I->second;
847     assert(Begin->isDebugValue() && "Invalid History entry");
848 
849     // Check if a variable is inaccessible in this range.
850     if (Begin->getNumOperands() > 1 &&
851         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
852       OpenRanges.clear();
853       continue;
854     }
855 
856     // If this piece overlaps with any open ranges, truncate them.
857     const DIExpression *DIExpr = Begin->getDebugExpression();
858     auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
859       return piecesOverlap(DIExpr, R.getExpression());
860     });
861     OpenRanges.erase(Last, OpenRanges.end());
862 
863     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
864     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
865 
866     const MCSymbol *EndLabel;
867     if (End != nullptr)
868       EndLabel = getLabelAfterInsn(End);
869     else if (std::next(I) == Ranges.end())
870       EndLabel = Asm->getFunctionEnd();
871     else
872       EndLabel = getLabelBeforeInsn(std::next(I)->first);
873     assert(EndLabel && "Forgot label after instruction ending a range!");
874 
875     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
876 
877     auto Value = getDebugLocValue(Begin);
878     DebugLocEntry Loc(StartLabel, EndLabel, Value);
879     bool couldMerge = false;
880 
881     // If this is a piece, it may belong to the current DebugLocEntry.
882     if (DIExpr->isBitPiece()) {
883       // Add this value to the list of open ranges.
884       OpenRanges.push_back(Value);
885 
886       // Attempt to add the piece to the last entry.
887       if (!DebugLoc.empty())
888         if (DebugLoc.back().MergeValues(Loc))
889           couldMerge = true;
890     }
891 
892     if (!couldMerge) {
893       // Need to add a new DebugLocEntry. Add all values from still
894       // valid non-overlapping pieces.
895       if (OpenRanges.size())
896         Loc.addValues(OpenRanges);
897 
898       DebugLoc.push_back(std::move(Loc));
899     }
900 
901     // Attempt to coalesce the ranges of two otherwise identical
902     // DebugLocEntries.
903     auto CurEntry = DebugLoc.rbegin();
904     DEBUG({
905       dbgs() << CurEntry->getValues().size() << " Values:\n";
906       for (auto &Value : CurEntry->getValues())
907         Value.dump();
908       dbgs() << "-----\n";
909     });
910 
911     auto PrevEntry = std::next(CurEntry);
912     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
913       DebugLoc.pop_back();
914   }
915 }
916 
917 DbgVariable *DwarfDebug::createConcreteVariable(LexicalScope &Scope,
918                                                 InlinedVariable IV) {
919   ensureAbstractVariableIsCreatedIfScoped(IV, Scope.getScopeNode());
920   ConcreteVariables.push_back(make_unique<DbgVariable>(IV.first, IV.second));
921   InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
922   return ConcreteVariables.back().get();
923 }
924 
925 // Determine whether this DBG_VALUE is valid at the beginning of the function.
926 static bool validAtEntry(const MachineInstr *MInsn) {
927   auto MBB = MInsn->getParent();
928   // Is it in the entry basic block?
929   if (!MBB->pred_empty())
930     return false;
931   for (MachineBasicBlock::const_reverse_iterator I(MInsn); I != MBB->rend(); ++I)
932     if (!(I->isDebugValue() || I->getFlag(MachineInstr::FrameSetup)))
933       return false;
934   return true;
935 }
936 
937 // Find variables for each lexical scope.
938 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
939                                      const DISubprogram *SP,
940                                      DenseSet<InlinedVariable> &Processed) {
941   // Grab the variable info that was squirreled away in the MMI side-table.
942   collectVariableInfoFromMMITable(Processed);
943 
944   for (const auto &I : DbgValues) {
945     InlinedVariable IV = I.first;
946     if (Processed.count(IV))
947       continue;
948 
949     // Instruction ranges, specifying where IV is accessible.
950     const auto &Ranges = I.second;
951     if (Ranges.empty())
952       continue;
953 
954     LexicalScope *Scope = nullptr;
955     if (const DILocation *IA = IV.second)
956       Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
957     else
958       Scope = LScopes.findLexicalScope(IV.first->getScope());
959     // If variable scope is not found then skip this variable.
960     if (!Scope)
961       continue;
962 
963     Processed.insert(IV);
964     DbgVariable *RegVar = createConcreteVariable(*Scope, IV);
965 
966     const MachineInstr *MInsn = Ranges.front().first;
967     assert(MInsn->isDebugValue() && "History must begin with debug value");
968 
969     // Check if there is a single DBG_VALUE, valid throughout the function.
970     // A single constant is also considered valid for the entire function.
971     if (Ranges.size() == 1 &&
972         (MInsn->getOperand(0).isImm() ||
973          (validAtEntry(MInsn) && Ranges.front().second == nullptr))) {
974       RegVar->initializeDbgValue(MInsn);
975       continue;
976     }
977 
978     // Handle multiple DBG_VALUE instructions describing one variable.
979     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
980 
981     // Build the location list for this variable.
982     SmallVector<DebugLocEntry, 8> Entries;
983     buildLocationList(Entries, Ranges);
984 
985     // If the variable has a DIBasicType, extract it.  Basic types cannot have
986     // unique identifiers, so don't bother resolving the type with the
987     // identifier map.
988     const DIBasicType *BT = dyn_cast<DIBasicType>(
989         static_cast<const Metadata *>(IV.first->getType()));
990 
991     // Finalize the entry by lowering it into a DWARF bytestream.
992     for (auto &Entry : Entries)
993       Entry.finalize(*Asm, List, BT);
994   }
995 
996   // Collect info for variables that were optimized out.
997   for (const DILocalVariable *DV : SP->getVariables()) {
998     if (Processed.insert(InlinedVariable(DV, nullptr)).second)
999       if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
1000         createConcreteVariable(*Scope, InlinedVariable(DV, nullptr));
1001   }
1002 }
1003 
1004 // Process beginning of an instruction.
1005 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1006   DebugHandlerBase::beginInstruction(MI);
1007   assert(CurMI);
1008 
1009   // Check if source location changes, but ignore DBG_VALUE locations.
1010   if (MI->isDebugValue())
1011     return;
1012   const DebugLoc &DL = MI->getDebugLoc();
1013   if (DL == PrevInstLoc)
1014     return;
1015 
1016   if (!DL) {
1017     // We have an unspecified location, which might want to be line 0.
1018     if (UnknownLocations) {
1019       PrevInstLoc = DL;
1020       recordSourceLine(0, 0, nullptr, 0);
1021     }
1022     return;
1023   }
1024 
1025   // We have a new, explicit location.
1026   unsigned Flags = 0;
1027   PrevInstLoc = DL;
1028   if (DL == PrologEndLoc) {
1029     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1030     PrologEndLoc = DebugLoc();
1031   }
1032   if (DL.getLine() !=
1033       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine())
1034     Flags |= DWARF2_FLAG_IS_STMT;
1035 
1036   const MDNode *Scope = DL.getScope();
1037   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1038 }
1039 
1040 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1041   // First known non-DBG_VALUE and non-frame setup location marks
1042   // the beginning of the function body.
1043   for (const auto &MBB : *MF)
1044     for (const auto &MI : MBB)
1045       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1046           MI.getDebugLoc())
1047         return MI.getDebugLoc();
1048   return DebugLoc();
1049 }
1050 
1051 // Gather pre-function debug information.  Assumes being called immediately
1052 // after the function entry point has been emitted.
1053 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1054   CurFn = MF;
1055 
1056   // If there's no debug info for the function we're not going to do anything.
1057   if (!MMI->hasDebugInfo())
1058     return;
1059 
1060   auto DI = MF->getFunction()->getSubprogram();
1061   if (!DI)
1062     return;
1063 
1064   // Grab the lexical scopes for the function, if we don't have any of those
1065   // then we're not going to be able to do anything.
1066   DebugHandlerBase::beginFunction(MF);
1067   if (LScopes.empty())
1068     return;
1069 
1070   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1071   // belongs to so that we add to the correct per-cu line table in the
1072   // non-asm case.
1073   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1074   // FnScope->getScopeNode() and DI->second should represent the same function,
1075   // though they may not be the same MDNode due to inline functions merged in
1076   // LTO where the debug info metadata still differs (either due to distinct
1077   // written differences - two versions of a linkonce_odr function
1078   // written/copied into two separate files, or some sub-optimal metadata that
1079   // isn't structurally identical (see: file path/name info from clang, which
1080   // includes the directory of the cpp file being built, even when the file name
1081   // is absolute (such as an <> lookup header)))
1082   auto *SP = cast<DISubprogram>(FnScope->getScopeNode());
1083   DwarfCompileUnit *TheCU = CUMap.lookup(SP->getUnit());
1084   if (!TheCU) {
1085     assert(SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug &&
1086            "DICompileUnit missing from llvm.dbg.cu?");
1087     return;
1088   }
1089   if (Asm->OutStreamer->hasRawTextSupport())
1090     // Use a single line table if we are generating assembly.
1091     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1092   else
1093     Asm->OutStreamer->getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1094 
1095   // Record beginning of function.
1096   PrologEndLoc = findPrologueEndLoc(MF);
1097   if (DILocation *L = PrologEndLoc) {
1098     // We'd like to list the prologue as "not statements" but GDB behaves
1099     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1100     auto *SP = L->getInlinedAtScope()->getSubprogram();
1101     recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1102   }
1103 }
1104 
1105 // Gather and emit post-function debug information.
1106 void DwarfDebug::endFunction(const MachineFunction *MF) {
1107   assert(CurFn == MF &&
1108       "endFunction should be called with the same function as beginFunction");
1109 
1110   const DISubprogram *SP = MF->getFunction()->getSubprogram();
1111   if (!MMI->hasDebugInfo() || LScopes.empty() || !SP ||
1112       SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) {
1113     // If we don't have a lexical scope for this function then there will
1114     // be a hole in the range information. Keep note of this by setting the
1115     // previously used section to nullptr.
1116     PrevCU = nullptr;
1117     CurFn = nullptr;
1118     DebugHandlerBase::endFunction(MF);
1119     // Mark functions with no debug info on any instructions, but a
1120     // valid DISubprogram as processed.
1121     if (SP)
1122       ProcessedSPNodes.insert(SP);
1123     return;
1124   }
1125 
1126   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1127   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1128 
1129   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1130   SP = cast<DISubprogram>(FnScope->getScopeNode());
1131   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1132 
1133   DenseSet<InlinedVariable> ProcessedVars;
1134   collectVariableInfo(TheCU, SP, ProcessedVars);
1135 
1136   // Add the range of this function to the list of ranges for the CU.
1137   TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1138 
1139   // Under -gmlt, skip building the subprogram if there are no inlined
1140   // subroutines inside it.
1141   if (TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1142       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1143     assert(InfoHolder.getScopeVariables().empty());
1144     assert(DbgValues.empty());
1145     // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1146     // by a -gmlt CU. Add a test and remove this assertion.
1147     assert(AbstractVariables.empty());
1148     PrevLabel = nullptr;
1149     CurFn = nullptr;
1150     DebugHandlerBase::endFunction(MF);
1151     return;
1152   }
1153 
1154 #ifndef NDEBUG
1155   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1156 #endif
1157   // Construct abstract scopes.
1158   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1159     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1160     // Collect info for variables that were optimized out.
1161     for (const DILocalVariable *DV : SP->getVariables()) {
1162       if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
1163         continue;
1164       ensureAbstractVariableIsCreated(InlinedVariable(DV, nullptr),
1165                                       DV->getScope());
1166       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1167              && "ensureAbstractVariableIsCreated inserted abstract scopes");
1168     }
1169     constructAbstractSubprogramScopeDIE(AScope);
1170   }
1171 
1172   TheCU.constructSubprogramScopeDIE(FnScope);
1173   if (auto *SkelCU = TheCU.getSkeleton())
1174     if (!LScopes.getAbstractScopesList().empty() &&
1175         TheCU.getCUNode()->getSplitDebugInlining())
1176       SkelCU->constructSubprogramScopeDIE(FnScope);
1177 
1178   // Clear debug info
1179   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1180   // DbgVariables except those that are also in AbstractVariables (since they
1181   // can be used cross-function)
1182   InfoHolder.getScopeVariables().clear();
1183   PrevLabel = nullptr;
1184   CurFn = nullptr;
1185   DebugHandlerBase::endFunction(MF);
1186 }
1187 
1188 // Register a source line with debug info. Returns the  unique label that was
1189 // emitted and which provides correspondence to the source line list.
1190 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1191                                   unsigned Flags) {
1192   StringRef Fn;
1193   StringRef Dir;
1194   unsigned Src = 1;
1195   unsigned Discriminator = 0;
1196   if (auto *Scope = cast_or_null<DIScope>(S)) {
1197     Fn = Scope->getFilename();
1198     Dir = Scope->getDirectory();
1199     if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1200       if (DwarfVersion >= 4)
1201         Discriminator = LBF->getDiscriminator();
1202 
1203     unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1204     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1205               .getOrCreateSourceID(Fn, Dir);
1206   }
1207   Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1208                                           Discriminator, Fn);
1209 }
1210 
1211 //===----------------------------------------------------------------------===//
1212 // Emit Methods
1213 //===----------------------------------------------------------------------===//
1214 
1215 // Emit the debug info section.
1216 void DwarfDebug::emitDebugInfo() {
1217   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1218   Holder.emitUnits(/* UseOffsets */ false);
1219 }
1220 
1221 // Emit the abbreviation section.
1222 void DwarfDebug::emitAbbreviations() {
1223   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1224 
1225   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1226 }
1227 
1228 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section,
1229                            StringRef TableName) {
1230   Accel.FinalizeTable(Asm, TableName);
1231   Asm->OutStreamer->SwitchSection(Section);
1232 
1233   // Emit the full data.
1234   Accel.emit(Asm, Section->getBeginSymbol(), this);
1235 }
1236 
1237 // Emit visible names into a hashed accelerator table section.
1238 void DwarfDebug::emitAccelNames() {
1239   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1240             "Names");
1241 }
1242 
1243 // Emit objective C classes and categories into a hashed accelerator table
1244 // section.
1245 void DwarfDebug::emitAccelObjC() {
1246   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1247             "ObjC");
1248 }
1249 
1250 // Emit namespace dies into a hashed accelerator table.
1251 void DwarfDebug::emitAccelNamespaces() {
1252   emitAccel(AccelNamespace,
1253             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1254             "namespac");
1255 }
1256 
1257 // Emit type dies into a hashed accelerator table.
1258 void DwarfDebug::emitAccelTypes() {
1259   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1260             "types");
1261 }
1262 
1263 // Public name handling.
1264 // The format for the various pubnames:
1265 //
1266 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1267 // for the DIE that is named.
1268 //
1269 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1270 // into the CU and the index value is computed according to the type of value
1271 // for the DIE that is named.
1272 //
1273 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1274 // it's the offset within the debug_info/debug_types dwo section, however, the
1275 // reference in the pubname header doesn't change.
1276 
1277 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1278 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1279                                                         const DIE *Die) {
1280   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1281 
1282   // We could have a specification DIE that has our most of our knowledge,
1283   // look for that now.
1284   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1285     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1286     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1287       Linkage = dwarf::GIEL_EXTERNAL;
1288   } else if (Die->findAttribute(dwarf::DW_AT_external))
1289     Linkage = dwarf::GIEL_EXTERNAL;
1290 
1291   switch (Die->getTag()) {
1292   case dwarf::DW_TAG_class_type:
1293   case dwarf::DW_TAG_structure_type:
1294   case dwarf::DW_TAG_union_type:
1295   case dwarf::DW_TAG_enumeration_type:
1296     return dwarf::PubIndexEntryDescriptor(
1297         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1298                               ? dwarf::GIEL_STATIC
1299                               : dwarf::GIEL_EXTERNAL);
1300   case dwarf::DW_TAG_typedef:
1301   case dwarf::DW_TAG_base_type:
1302   case dwarf::DW_TAG_subrange_type:
1303     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1304   case dwarf::DW_TAG_namespace:
1305     return dwarf::GIEK_TYPE;
1306   case dwarf::DW_TAG_subprogram:
1307     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1308   case dwarf::DW_TAG_variable:
1309     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1310   case dwarf::DW_TAG_enumerator:
1311     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1312                                           dwarf::GIEL_STATIC);
1313   default:
1314     return dwarf::GIEK_NONE;
1315   }
1316 }
1317 
1318 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1319 ///
1320 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1321   MCSection *PSec = GnuStyle
1322                         ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1323                         : Asm->getObjFileLowering().getDwarfPubNamesSection();
1324 
1325   emitDebugPubSection(GnuStyle, PSec, "Names",
1326                       &DwarfCompileUnit::getGlobalNames);
1327 }
1328 
1329 void DwarfDebug::emitDebugPubSection(
1330     bool GnuStyle, MCSection *PSec, StringRef Name,
1331     const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1332   for (const auto &NU : CUMap) {
1333     DwarfCompileUnit *TheU = NU.second;
1334 
1335     const auto &Globals = (TheU->*Accessor)();
1336 
1337     if (Globals.empty())
1338       continue;
1339 
1340     if (auto *Skeleton = TheU->getSkeleton())
1341       TheU = Skeleton;
1342 
1343     // Start the dwarf pubnames section.
1344     Asm->OutStreamer->SwitchSection(PSec);
1345 
1346     // Emit the header.
1347     Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1348     MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1349     MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1350     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1351 
1352     Asm->OutStreamer->EmitLabel(BeginLabel);
1353 
1354     Asm->OutStreamer->AddComment("DWARF Version");
1355     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1356 
1357     Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1358     Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
1359 
1360     Asm->OutStreamer->AddComment("Compilation Unit Length");
1361     Asm->EmitInt32(TheU->getLength());
1362 
1363     // Emit the pubnames for this compilation unit.
1364     for (const auto &GI : Globals) {
1365       const char *Name = GI.getKeyData();
1366       const DIE *Entity = GI.second;
1367 
1368       Asm->OutStreamer->AddComment("DIE offset");
1369       Asm->EmitInt32(Entity->getOffset());
1370 
1371       if (GnuStyle) {
1372         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1373         Asm->OutStreamer->AddComment(
1374             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1375             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1376         Asm->EmitInt8(Desc.toBits());
1377       }
1378 
1379       Asm->OutStreamer->AddComment("External Name");
1380       Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1381     }
1382 
1383     Asm->OutStreamer->AddComment("End Mark");
1384     Asm->EmitInt32(0);
1385     Asm->OutStreamer->EmitLabel(EndLabel);
1386   }
1387 }
1388 
1389 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1390   MCSection *PSec = GnuStyle
1391                         ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1392                         : Asm->getObjFileLowering().getDwarfPubTypesSection();
1393 
1394   emitDebugPubSection(GnuStyle, PSec, "Types",
1395                       &DwarfCompileUnit::getGlobalTypes);
1396 }
1397 
1398 /// Emit null-terminated strings into a debug str section.
1399 void DwarfDebug::emitDebugStr() {
1400   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1401   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1402 }
1403 
1404 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1405                                    const DebugLocStream::Entry &Entry) {
1406   auto &&Comments = DebugLocs.getComments(Entry);
1407   auto Comment = Comments.begin();
1408   auto End = Comments.end();
1409   for (uint8_t Byte : DebugLocs.getBytes(Entry))
1410     Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1411 }
1412 
1413 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1414                               ByteStreamer &Streamer,
1415                               const DebugLocEntry::Value &Value,
1416                               unsigned PieceOffsetInBits) {
1417   DIExpressionCursor ExprCursor(Value.getExpression());
1418   DebugLocDwarfExpression DwarfExpr(AP.getDwarfDebug()->getDwarfVersion(),
1419                                     Streamer);
1420   // Regular entry.
1421   if (Value.isInt()) {
1422     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1423                BT->getEncoding() == dwarf::DW_ATE_signed_char))
1424       DwarfExpr.AddSignedConstant(Value.getInt());
1425     else
1426       DwarfExpr.AddUnsignedConstant(Value.getInt());
1427   } else if (Value.isLocation()) {
1428     MachineLocation Loc = Value.getLoc();
1429     if (!ExprCursor)
1430       // Regular entry.
1431       AP.EmitDwarfRegOp(Streamer, Loc);
1432     else {
1433       // Complex address entry.
1434       const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
1435       if (Loc.getOffset())
1436         DwarfExpr.AddMachineRegIndirect(TRI, Loc.getReg(), Loc.getOffset());
1437       else
1438         DwarfExpr.AddMachineRegExpression(TRI, ExprCursor, Loc.getReg(),
1439                                           PieceOffsetInBits);
1440     }
1441   } else if (Value.isConstantFP()) {
1442     APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
1443     DwarfExpr.AddUnsignedConstant(RawBytes);
1444   }
1445   DwarfExpr.AddExpression(std::move(ExprCursor), PieceOffsetInBits);
1446 }
1447 
1448 void DebugLocEntry::finalize(const AsmPrinter &AP,
1449                              DebugLocStream::ListBuilder &List,
1450                              const DIBasicType *BT) {
1451   DebugLocStream::EntryBuilder Entry(List, Begin, End);
1452   BufferByteStreamer Streamer = Entry.getStreamer();
1453   const DebugLocEntry::Value &Value = Values[0];
1454   if (Value.isBitPiece()) {
1455     // Emit all pieces that belong to the same variable and range.
1456     assert(all_of(Values, [](DebugLocEntry::Value P) {
1457           return P.isBitPiece();
1458         }) && "all values are expected to be pieces");
1459     assert(std::is_sorted(Values.begin(), Values.end()) &&
1460            "pieces are expected to be sorted");
1461 
1462     unsigned Offset = 0;
1463     for (auto Piece : Values) {
1464       const DIExpression *Expr = Piece.getExpression();
1465       unsigned PieceOffset = Expr->getBitPieceOffset();
1466       unsigned PieceSize = Expr->getBitPieceSize();
1467       assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1468       if (Offset < PieceOffset) {
1469         // The DWARF spec seriously mandates pieces with no locations for gaps.
1470         DebugLocDwarfExpression Expr(AP.getDwarfDebug()->getDwarfVersion(),
1471                                      Streamer);
1472         Expr.AddOpPiece(PieceOffset-Offset, 0);
1473         Offset += PieceOffset-Offset;
1474       }
1475       Offset += PieceSize;
1476 
1477       emitDebugLocValue(AP, BT, Streamer, Piece, PieceOffset);
1478     }
1479   } else {
1480     assert(Values.size() == 1 && "only pieces may have >1 value");
1481     emitDebugLocValue(AP, BT, Streamer, Value, 0);
1482   }
1483 }
1484 
1485 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1486   // Emit the size.
1487   Asm->OutStreamer->AddComment("Loc expr size");
1488   Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
1489 
1490   // Emit the entry.
1491   APByteStreamer Streamer(*Asm);
1492   emitDebugLocEntry(Streamer, Entry);
1493 }
1494 
1495 // Emit locations into the debug loc section.
1496 void DwarfDebug::emitDebugLoc() {
1497   // Start the dwarf loc section.
1498   Asm->OutStreamer->SwitchSection(
1499       Asm->getObjFileLowering().getDwarfLocSection());
1500   unsigned char Size = Asm->getDataLayout().getPointerSize();
1501   for (const auto &List : DebugLocs.getLists()) {
1502     Asm->OutStreamer->EmitLabel(List.Label);
1503     const DwarfCompileUnit *CU = List.CU;
1504     for (const auto &Entry : DebugLocs.getEntries(List)) {
1505       // Set up the range. This range is relative to the entry point of the
1506       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1507       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1508       if (auto *Base = CU->getBaseAddress()) {
1509         Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
1510         Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
1511       } else {
1512         Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
1513         Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
1514       }
1515 
1516       emitDebugLocEntryLocation(Entry);
1517     }
1518     Asm->OutStreamer->EmitIntValue(0, Size);
1519     Asm->OutStreamer->EmitIntValue(0, Size);
1520   }
1521 }
1522 
1523 void DwarfDebug::emitDebugLocDWO() {
1524   Asm->OutStreamer->SwitchSection(
1525       Asm->getObjFileLowering().getDwarfLocDWOSection());
1526   for (const auto &List : DebugLocs.getLists()) {
1527     Asm->OutStreamer->EmitLabel(List.Label);
1528     for (const auto &Entry : DebugLocs.getEntries(List)) {
1529       // Just always use start_length for now - at least that's one address
1530       // rather than two. We could get fancier and try to, say, reuse an
1531       // address we know we've emitted elsewhere (the start of the function?
1532       // The start of the CU or CU subrange that encloses this range?)
1533       Asm->EmitInt8(dwarf::DW_LLE_startx_length);
1534       unsigned idx = AddrPool.getIndex(Entry.BeginSym);
1535       Asm->EmitULEB128(idx);
1536       Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
1537 
1538       emitDebugLocEntryLocation(Entry);
1539     }
1540     Asm->EmitInt8(dwarf::DW_LLE_end_of_list);
1541   }
1542 }
1543 
1544 struct ArangeSpan {
1545   const MCSymbol *Start, *End;
1546 };
1547 
1548 // Emit a debug aranges section, containing a CU lookup for any
1549 // address we can tie back to a CU.
1550 void DwarfDebug::emitDebugARanges() {
1551   // Provides a unique id per text section.
1552   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1553 
1554   // Filter labels by section.
1555   for (const SymbolCU &SCU : ArangeLabels) {
1556     if (SCU.Sym->isInSection()) {
1557       // Make a note of this symbol and it's section.
1558       MCSection *Section = &SCU.Sym->getSection();
1559       if (!Section->getKind().isMetadata())
1560         SectionMap[Section].push_back(SCU);
1561     } else {
1562       // Some symbols (e.g. common/bss on mach-o) can have no section but still
1563       // appear in the output. This sucks as we rely on sections to build
1564       // arange spans. We can do it without, but it's icky.
1565       SectionMap[nullptr].push_back(SCU);
1566     }
1567   }
1568 
1569   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1570 
1571   for (auto &I : SectionMap) {
1572     MCSection *Section = I.first;
1573     SmallVector<SymbolCU, 8> &List = I.second;
1574     if (List.size() < 1)
1575       continue;
1576 
1577     // If we have no section (e.g. common), just write out
1578     // individual spans for each symbol.
1579     if (!Section) {
1580       for (const SymbolCU &Cur : List) {
1581         ArangeSpan Span;
1582         Span.Start = Cur.Sym;
1583         Span.End = nullptr;
1584         assert(Cur.CU);
1585         Spans[Cur.CU].push_back(Span);
1586       }
1587       continue;
1588     }
1589 
1590     // Sort the symbols by offset within the section.
1591     std::sort(
1592         List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
1593           unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
1594           unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
1595 
1596           // Symbols with no order assigned should be placed at the end.
1597           // (e.g. section end labels)
1598           if (IA == 0)
1599             return false;
1600           if (IB == 0)
1601             return true;
1602           return IA < IB;
1603         });
1604 
1605     // Insert a final terminator.
1606     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
1607 
1608     // Build spans between each label.
1609     const MCSymbol *StartSym = List[0].Sym;
1610     for (size_t n = 1, e = List.size(); n < e; n++) {
1611       const SymbolCU &Prev = List[n - 1];
1612       const SymbolCU &Cur = List[n];
1613 
1614       // Try and build the longest span we can within the same CU.
1615       if (Cur.CU != Prev.CU) {
1616         ArangeSpan Span;
1617         Span.Start = StartSym;
1618         Span.End = Cur.Sym;
1619         assert(Prev.CU);
1620         Spans[Prev.CU].push_back(Span);
1621         StartSym = Cur.Sym;
1622       }
1623     }
1624   }
1625 
1626   // Start the dwarf aranges section.
1627   Asm->OutStreamer->SwitchSection(
1628       Asm->getObjFileLowering().getDwarfARangesSection());
1629 
1630   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1631 
1632   // Build a list of CUs used.
1633   std::vector<DwarfCompileUnit *> CUs;
1634   for (const auto &it : Spans) {
1635     DwarfCompileUnit *CU = it.first;
1636     CUs.push_back(CU);
1637   }
1638 
1639   // Sort the CU list (again, to ensure consistent output order).
1640   std::sort(CUs.begin(), CUs.end(),
1641             [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
1642               return A->getUniqueID() < B->getUniqueID();
1643             });
1644 
1645   // Emit an arange table for each CU we used.
1646   for (DwarfCompileUnit *CU : CUs) {
1647     std::vector<ArangeSpan> &List = Spans[CU];
1648 
1649     // Describe the skeleton CU's offset and length, not the dwo file's.
1650     if (auto *Skel = CU->getSkeleton())
1651       CU = Skel;
1652 
1653     // Emit size of content not including length itself.
1654     unsigned ContentSize =
1655         sizeof(int16_t) + // DWARF ARange version number
1656         sizeof(int32_t) + // Offset of CU in the .debug_info section
1657         sizeof(int8_t) +  // Pointer Size (in bytes)
1658         sizeof(int8_t);   // Segment Size (in bytes)
1659 
1660     unsigned TupleSize = PtrSize * 2;
1661 
1662     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1663     unsigned Padding =
1664         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1665 
1666     ContentSize += Padding;
1667     ContentSize += (List.size() + 1) * TupleSize;
1668 
1669     // For each compile unit, write the list of spans it covers.
1670     Asm->OutStreamer->AddComment("Length of ARange Set");
1671     Asm->EmitInt32(ContentSize);
1672     Asm->OutStreamer->AddComment("DWARF Arange version number");
1673     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1674     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
1675     Asm->emitDwarfSymbolReference(CU->getLabelBegin());
1676     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1677     Asm->EmitInt8(PtrSize);
1678     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
1679     Asm->EmitInt8(0);
1680 
1681     Asm->OutStreamer->emitFill(Padding, 0xff);
1682 
1683     for (const ArangeSpan &Span : List) {
1684       Asm->EmitLabelReference(Span.Start, PtrSize);
1685 
1686       // Calculate the size as being from the span start to it's end.
1687       if (Span.End) {
1688         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1689       } else {
1690         // For symbols without an end marker (e.g. common), we
1691         // write a single arange entry containing just that one symbol.
1692         uint64_t Size = SymSize[Span.Start];
1693         if (Size == 0)
1694           Size = 1;
1695 
1696         Asm->OutStreamer->EmitIntValue(Size, PtrSize);
1697       }
1698     }
1699 
1700     Asm->OutStreamer->AddComment("ARange terminator");
1701     Asm->OutStreamer->EmitIntValue(0, PtrSize);
1702     Asm->OutStreamer->EmitIntValue(0, PtrSize);
1703   }
1704 }
1705 
1706 /// Emit address ranges into a debug ranges section.
1707 void DwarfDebug::emitDebugRanges() {
1708   // Start the dwarf ranges section.
1709   Asm->OutStreamer->SwitchSection(
1710       Asm->getObjFileLowering().getDwarfRangesSection());
1711 
1712   // Size for our labels.
1713   unsigned char Size = Asm->getDataLayout().getPointerSize();
1714 
1715   // Grab the specific ranges for the compile units in the module.
1716   for (const auto &I : CUMap) {
1717     DwarfCompileUnit *TheCU = I.second;
1718 
1719     if (auto *Skel = TheCU->getSkeleton())
1720       TheCU = Skel;
1721 
1722     // Iterate over the misc ranges for the compile units in the module.
1723     for (const RangeSpanList &List : TheCU->getRangeLists()) {
1724       // Emit our symbol so we can find the beginning of the range.
1725       Asm->OutStreamer->EmitLabel(List.getSym());
1726 
1727       for (const RangeSpan &Range : List.getRanges()) {
1728         const MCSymbol *Begin = Range.getStart();
1729         const MCSymbol *End = Range.getEnd();
1730         assert(Begin && "Range without a begin symbol?");
1731         assert(End && "Range without an end symbol?");
1732         if (auto *Base = TheCU->getBaseAddress()) {
1733           Asm->EmitLabelDifference(Begin, Base, Size);
1734           Asm->EmitLabelDifference(End, Base, Size);
1735         } else {
1736           Asm->OutStreamer->EmitSymbolValue(Begin, Size);
1737           Asm->OutStreamer->EmitSymbolValue(End, Size);
1738         }
1739       }
1740 
1741       // And terminate the list with two 0 values.
1742       Asm->OutStreamer->EmitIntValue(0, Size);
1743       Asm->OutStreamer->EmitIntValue(0, Size);
1744     }
1745   }
1746 }
1747 
1748 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
1749   for (auto *MN : Nodes) {
1750     if (auto *M = dyn_cast<DIMacro>(MN))
1751       emitMacro(*M);
1752     else if (auto *F = dyn_cast<DIMacroFile>(MN))
1753       emitMacroFile(*F, U);
1754     else
1755       llvm_unreachable("Unexpected DI type!");
1756   }
1757 }
1758 
1759 void DwarfDebug::emitMacro(DIMacro &M) {
1760   Asm->EmitULEB128(M.getMacinfoType());
1761   Asm->EmitULEB128(M.getLine());
1762   StringRef Name = M.getName();
1763   StringRef Value = M.getValue();
1764   Asm->OutStreamer->EmitBytes(Name);
1765   if (!Value.empty()) {
1766     // There should be one space between macro name and macro value.
1767     Asm->EmitInt8(' ');
1768     Asm->OutStreamer->EmitBytes(Value);
1769   }
1770   Asm->EmitInt8('\0');
1771 }
1772 
1773 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
1774   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
1775   Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
1776   Asm->EmitULEB128(F.getLine());
1777   DIFile *File = F.getFile();
1778   unsigned FID =
1779       U.getOrCreateSourceID(File->getFilename(), File->getDirectory());
1780   Asm->EmitULEB128(FID);
1781   handleMacroNodes(F.getElements(), U);
1782   Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
1783 }
1784 
1785 /// Emit macros into a debug macinfo section.
1786 void DwarfDebug::emitDebugMacinfo() {
1787   // Start the dwarf macinfo section.
1788   Asm->OutStreamer->SwitchSection(
1789       Asm->getObjFileLowering().getDwarfMacinfoSection());
1790 
1791   for (const auto &P : CUMap) {
1792     auto &TheCU = *P.second;
1793     auto *SkCU = TheCU.getSkeleton();
1794     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1795     auto *CUNode = cast<DICompileUnit>(P.first);
1796     Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
1797     handleMacroNodes(CUNode->getMacros(), U);
1798   }
1799   Asm->OutStreamer->AddComment("End Of Macro List Mark");
1800   Asm->EmitInt8(0);
1801 }
1802 
1803 // DWARF5 Experimental Separate Dwarf emitters.
1804 
1805 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1806                                   std::unique_ptr<DwarfCompileUnit> NewU) {
1807   NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1808                   U.getCUNode()->getSplitDebugFilename());
1809 
1810   if (!CompilationDir.empty())
1811     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1812 
1813   addGnuPubAttributes(*NewU, Die);
1814 
1815   SkeletonHolder.addUnit(std::move(NewU));
1816 }
1817 
1818 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1819 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1820 // DW_AT_addr_base, DW_AT_ranges_base.
1821 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1822 
1823   auto OwnedUnit = make_unique<DwarfCompileUnit>(
1824       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1825   DwarfCompileUnit &NewCU = *OwnedUnit;
1826   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1827 
1828   NewCU.initStmtList();
1829 
1830   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1831 
1832   return NewCU;
1833 }
1834 
1835 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1836 // compile units that would normally be in debug_info.
1837 void DwarfDebug::emitDebugInfoDWO() {
1838   assert(useSplitDwarf() && "No split dwarf debug info?");
1839   // Don't emit relocations into the dwo file.
1840   InfoHolder.emitUnits(/* UseOffsets */ true);
1841 }
1842 
1843 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1844 // abbreviations for the .debug_info.dwo section.
1845 void DwarfDebug::emitDebugAbbrevDWO() {
1846   assert(useSplitDwarf() && "No split dwarf?");
1847   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1848 }
1849 
1850 void DwarfDebug::emitDebugLineDWO() {
1851   assert(useSplitDwarf() && "No split dwarf?");
1852   Asm->OutStreamer->SwitchSection(
1853       Asm->getObjFileLowering().getDwarfLineDWOSection());
1854   SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams());
1855 }
1856 
1857 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1858 // string section and is identical in format to traditional .debug_str
1859 // sections.
1860 void DwarfDebug::emitDebugStrDWO() {
1861   assert(useSplitDwarf() && "No split dwarf?");
1862   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1863   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1864                          OffSec);
1865 }
1866 
1867 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1868   if (!useSplitDwarf())
1869     return nullptr;
1870   if (SingleCU)
1871     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
1872   return &SplitTypeUnitFileTable;
1873 }
1874 
1875 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
1876   MD5 Hash;
1877   Hash.update(Identifier);
1878   // ... take the least significant 8 bytes and return those. Our MD5
1879   // implementation always returns its results in little endian, swap bytes
1880   // appropriately.
1881   MD5::MD5Result Result;
1882   Hash.final(Result);
1883   return support::endian::read64le(Result + 8);
1884 }
1885 
1886 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
1887                                       StringRef Identifier, DIE &RefDie,
1888                                       const DICompositeType *CTy) {
1889   // Fast path if we're building some type units and one has already used the
1890   // address pool we know we're going to throw away all this work anyway, so
1891   // don't bother building dependent types.
1892   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
1893     return;
1894 
1895   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
1896   if (!Ins.second) {
1897     CU.addDIETypeSignature(RefDie, Ins.first->second);
1898     return;
1899   }
1900 
1901   bool TopLevelType = TypeUnitsUnderConstruction.empty();
1902   AddrPool.resetUsedFlag();
1903 
1904   auto OwnedUnit = make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
1905                                               getDwoLineTable(CU));
1906   DwarfTypeUnit &NewTU = *OwnedUnit;
1907   DIE &UnitDie = NewTU.getUnitDie();
1908   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
1909 
1910   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1911                 CU.getLanguage());
1912 
1913   uint64_t Signature = makeTypeSignature(Identifier);
1914   NewTU.setTypeSignature(Signature);
1915   Ins.first->second = Signature;
1916 
1917   if (useSplitDwarf())
1918     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
1919   else {
1920     CU.applyStmtList(UnitDie);
1921     NewTU.initSection(
1922         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
1923   }
1924 
1925   NewTU.setType(NewTU.createTypeDIE(CTy));
1926 
1927   if (TopLevelType) {
1928     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
1929     TypeUnitsUnderConstruction.clear();
1930 
1931     // Types referencing entries in the address table cannot be placed in type
1932     // units.
1933     if (AddrPool.hasBeenUsed()) {
1934 
1935       // Remove all the types built while building this type.
1936       // This is pessimistic as some of these types might not be dependent on
1937       // the type that used an address.
1938       for (const auto &TU : TypeUnitsToAdd)
1939         TypeSignatures.erase(TU.second);
1940 
1941       // Construct this type in the CU directly.
1942       // This is inefficient because all the dependent types will be rebuilt
1943       // from scratch, including building them in type units, discovering that
1944       // they depend on addresses, throwing them out and rebuilding them.
1945       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
1946       return;
1947     }
1948 
1949     // If the type wasn't dependent on fission addresses, finish adding the type
1950     // and all its dependent types.
1951     for (auto &TU : TypeUnitsToAdd) {
1952       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
1953       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
1954     }
1955   }
1956   CU.addDIETypeSignature(RefDie, Signature);
1957 }
1958 
1959 // Accelerator table mutators - add each name along with its companion
1960 // DIE to the proper table while ensuring that the name that we're going
1961 // to reference is in the string table. We do this since the names we
1962 // add may not only be identical to the names in the DIE.
1963 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
1964   if (!useDwarfAccelTables())
1965     return;
1966   AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
1967 }
1968 
1969 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
1970   if (!useDwarfAccelTables())
1971     return;
1972   AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
1973 }
1974 
1975 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
1976   if (!useDwarfAccelTables())
1977     return;
1978   AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
1979 }
1980 
1981 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
1982   if (!useDwarfAccelTables())
1983     return;
1984   AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
1985 }
1986