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