LLVM  9.0.0svn
DwarfDebug.cpp
Go to the documentation of this file.
1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for writing dwarf debug info into asm files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DwarfDebug.h"
14 #include "ByteStreamer.h"
15 #include "DIEHash.h"
16 #include "DebugLocEntry.h"
17 #include "DebugLocStream.h"
18 #include "DwarfCompileUnit.h"
19 #include "DwarfExpression.h"
20 #include "DwarfFile.h"
21 #include "DwarfUnit.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/MapVector.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/ADT/Twine.h"
34 #include "llvm/CodeGen/DIE.h"
46 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DebugLoc.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/GlobalVariable.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/MC/MCAsmInfo.h"
53 #include "llvm/MC/MCContext.h"
54 #include "llvm/MC/MCDwarf.h"
55 #include "llvm/MC/MCSection.h"
56 #include "llvm/MC/MCStreamer.h"
57 #include "llvm/MC/MCSymbol.h"
60 #include "llvm/MC/SectionKind.h"
61 #include "llvm/Pass.h"
62 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/MD5.h"
68 #include "llvm/Support/Timer.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstddef>
76 #include <cstdint>
77 #include <iterator>
78 #include <string>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 #define DEBUG_TYPE "dwarfdebug"
85 
86 static cl::opt<bool>
87 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
88  cl::desc("Disable debug info printing"));
89 
91  "use-dwarf-ranges-base-address-specifier", cl::Hidden,
92  cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
93 
94 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
95  cl::Hidden,
96  cl::desc("Generate dwarf aranges"),
97  cl::init(false));
98 
99 static cl::opt<bool>
100  GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
101  cl::desc("Generate DWARF4 type units."),
102  cl::init(false));
103 
105  "split-dwarf-cross-cu-references", cl::Hidden,
106  cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
107 
108 enum DefaultOnOff { Default, Enable, Disable };
109 
111  "use-unknown-locations", cl::Hidden,
112  cl::desc("Make an absence of debug location information explicit."),
113  cl::values(clEnumVal(Default, "At top of block or after label"),
114  clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
115  cl::init(Default));
116 
118  "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
120  "Default for platform"),
121  clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
122  clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
123  clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
125 
127 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
128  cl::desc("Use inlined strings rather than string section."),
129  cl::values(clEnumVal(Default, "Default for platform"),
130  clEnumVal(Enable, "Enabled"),
131  clEnumVal(Disable, "Disabled")),
132  cl::init(Default));
133 
134 static cl::opt<bool>
135  NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
136  cl::desc("Disable emission .debug_ranges section."),
137  cl::init(false));
138 
140  "dwarf-sections-as-references", cl::Hidden,
141  cl::desc("Use sections+offset as references rather than labels."),
142  cl::values(clEnumVal(Default, "Default for platform"),
143  clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
144  cl::init(Default));
145 
150 };
151 
153  DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
154  cl::desc("Which DWARF linkage-name attributes to emit."),
156  "Default for platform"),
157  clEnumValN(AllLinkageNames, "All", "All"),
158  clEnumValN(AbstractLinkageNames, "Abstract",
159  "Abstract subprograms")),
161 
162 static const char *const DWARFGroupName = "dwarf";
163 static const char *const DWARFGroupDescription = "DWARF Emission";
164 static const char *const DbgTimerName = "writer";
165 static const char *const DbgTimerDescription = "DWARF Debug Writer";
166 static constexpr unsigned ULEB128PadSize = 4;
167 
168 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
169  BS.EmitInt8(
170  Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
172 }
173 
174 void DebugLocDwarfExpression::emitSigned(int64_t Value) {
175  BS.EmitSLEB128(Value, Twine(Value));
176 }
177 
178 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
179  BS.EmitULEB128(Value, Twine(Value));
180 }
181 
182 void DebugLocDwarfExpression::emitData1(uint8_t Value) {
183  BS.EmitInt8(Value, Twine(Value));
184 }
185 
186 void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
187  assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
188  BS.EmitULEB128(Idx, Twine(Idx), ULEB128PadSize);
189 }
190 
191 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
192  unsigned MachineReg) {
193  // This information is not available while emitting .debug_loc entries.
194  return false;
195 }
196 
198  assert(getVariable() && "Invalid complex DbgVariable!");
199  return getVariable()->getType()->isBlockByrefStruct();
200 }
201 
202 const DIType *DbgVariable::getType() const {
203  DIType *Ty = getVariable()->getType();
204  // FIXME: isBlockByrefVariable should be reformulated in terms of complex
205  // addresses instead.
206  if (Ty->isBlockByrefStruct()) {
207  /* Byref variables, in Blocks, are declared by the programmer as
208  "SomeType VarName;", but the compiler creates a
209  __Block_byref_x_VarName struct, and gives the variable VarName
210  either the struct, or a pointer to the struct, as its type. This
211  is necessary for various behind-the-scenes things the compiler
212  needs to do with by-reference variables in blocks.
213 
214  However, as far as the original *programmer* is concerned, the
215  variable should still have type 'SomeType', as originally declared.
216 
217  The following function dives into the __Block_byref_x_VarName
218  struct to find the original type of the variable. This will be
219  passed back to the code generating the type for the Debug
220  Information Entry for the variable 'VarName'. 'VarName' will then
221  have the original type 'SomeType' in its debug information.
222 
223  The original type 'SomeType' will be the type of the field named
224  'VarName' inside the __Block_byref_x_VarName struct.
225 
226  NOTE: In order for this to not completely fail on the debugger
227  side, the Debug Information Entry for the variable VarName needs to
228  have a DW_AT_location that tells the debugger how to unwind through
229  the pointers and __Block_byref_x_VarName struct to find the actual
230  value of the variable. The function addBlockByrefType does this. */
231  DIType *subType = Ty;
232  uint16_t tag = Ty->getTag();
233 
234  if (tag == dwarf::DW_TAG_pointer_type)
235  subType = cast<DIDerivedType>(Ty)->getBaseType();
236 
237  auto Elements = cast<DICompositeType>(subType)->getElements();
238  for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
239  auto *DT = cast<DIDerivedType>(Elements[i]);
240  if (getName() == DT->getName())
241  return DT->getBaseType();
242  }
243  }
244  return Ty;
245 }
246 
248  if (FrameIndexExprs.size() == 1)
249  return FrameIndexExprs;
250 
251  assert(llvm::all_of(FrameIndexExprs,
252  [](const FrameIndexExpr &A) {
253  return A.Expr->isFragment();
254  }) &&
255  "multiple FI expressions without DW_OP_LLVM_fragment");
256  llvm::sort(FrameIndexExprs,
257  [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
258  return A.Expr->getFragmentInfo()->OffsetInBits <
259  B.Expr->getFragmentInfo()->OffsetInBits;
260  });
261 
262  return FrameIndexExprs;
263 }
264 
266  assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
267  assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
268  assert(V.getVariable() == getVariable() && "conflicting variable");
269  assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
270 
271  assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
272  assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
273 
274  // FIXME: This logic should not be necessary anymore, as we now have proper
275  // deduplication. However, without it, we currently run into the assertion
276  // below, which means that we are likely dealing with broken input, i.e. two
277  // non-fragment entries for the same variable at different frame indices.
278  if (FrameIndexExprs.size()) {
279  auto *Expr = FrameIndexExprs.back().Expr;
280  if (!Expr || !Expr->isFragment())
281  return;
282  }
283 
284  for (const auto &FIE : V.FrameIndexExprs)
285  // Ignore duplicate entries.
286  if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
287  return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
288  }))
289  FrameIndexExprs.push_back(FIE);
290 
291  assert((FrameIndexExprs.size() == 1 ||
292  llvm::all_of(FrameIndexExprs,
293  [](FrameIndexExpr &FIE) {
294  return FIE.Expr && FIE.Expr->isFragment();
295  })) &&
296  "conflicting locations for variable");
297 }
298 
300  bool GenerateTypeUnits,
301  DebuggerKind Tuning,
302  const Triple &TT) {
303  // Honor an explicit request.
304  if (AccelTables != AccelTableKind::Default)
305  return AccelTables;
306 
307  // Accelerator tables with type units are currently not supported.
308  if (GenerateTypeUnits)
309  return AccelTableKind::None;
310 
311  // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
312  // always implies debug_names. For lower standard versions we use apple
313  // accelerator tables on apple platforms and debug_names elsewhere.
314  if (DwarfVersion >= 5)
315  return AccelTableKind::Dwarf;
316  if (Tuning == DebuggerKind::LLDB)
319  return AccelTableKind::None;
320 }
321 
323  : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
324  InfoHolder(A, "info_string", DIEValueAllocator),
325  SkeletonHolder(A, "skel_string", DIEValueAllocator),
326  IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
327  const Triple &TT = Asm->TM.getTargetTriple();
328 
329  // Make sure we know our "debugger tuning". The target option takes
330  // precedence; fall back to triple-based defaults.
332  DebuggerTuning = Asm->TM.Options.DebuggerTuning;
333  else if (IsDarwin)
334  DebuggerTuning = DebuggerKind::LLDB;
335  else if (TT.isPS4CPU())
336  DebuggerTuning = DebuggerKind::SCE;
337  else
338  DebuggerTuning = DebuggerKind::GDB;
339 
340  if (DwarfInlinedStrings == Default)
341  UseInlineStrings = TT.isNVPTX();
342  else
343  UseInlineStrings = DwarfInlinedStrings == Enable;
344 
345  UseLocSection = !TT.isNVPTX();
346 
347  HasAppleExtensionAttributes = tuneForLLDB();
348 
349  // Handle split DWARF.
350  HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
351 
352  // SCE defaults to linkage names only for abstract subprograms.
354  UseAllLinkageNames = !tuneForSCE();
355  else
356  UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
357 
358  unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
359  unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
360  : MMI->getModule()->getDwarfVersion();
361  // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
362  DwarfVersion =
363  TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
364 
365  UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
366 
367  // Use sections as references. Force for NVPTX.
368  if (DwarfSectionsAsReferences == Default)
369  UseSectionsAsReferences = TT.isNVPTX();
370  else
371  UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
372 
373  // Don't generate type units for unsupported object file formats.
374  GenerateTypeUnits =
376 
377  TheAccelTableKind = computeAccelTableKind(
378  DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
379 
380  // Work around a GDB bug. GDB doesn't support the standard opcode;
381  // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
382  // is defined as of DWARF 3.
383  // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
384  // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
385  UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
386 
387  // GDB does not fully support the DWARF 4 representation for bitfields.
388  UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
389 
390  // The DWARF v5 string offsets table has - possibly shared - contributions
391  // from each compile and type unit each preceded by a header. The string
392  // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
393  // a monolithic string offsets table without any header.
394  UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
395 
396  Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
397 }
398 
399 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
400 DwarfDebug::~DwarfDebug() = default;
401 
402 static bool isObjCClass(StringRef Name) {
403  return Name.startswith("+") || Name.startswith("-");
404 }
405 
407  if (!isObjCClass(Name))
408  return false;
409 
410  return Name.find(") ") != StringRef::npos;
411 }
412 
414  StringRef &Category) {
415  if (!hasObjCCategory(In)) {
416  Class = In.slice(In.find('[') + 1, In.find(' '));
417  Category = "";
418  return;
419  }
420 
421  Class = In.slice(In.find('[') + 1, In.find('('));
422  Category = In.slice(In.find('[') + 1, In.find(' '));
423 }
424 
426  return In.slice(In.find(' ') + 1, In.find(']'));
427 }
428 
429 // Add the various names to the Dwarf accelerator table names.
431  const DISubprogram *SP, DIE &Die) {
434  return;
435 
436  if (!SP->isDefinition())
437  return;
438 
439  if (SP->getName() != "")
440  addAccelName(CU, SP->getName(), Die);
441 
442  // If the linkage name is different than the name, go ahead and output that as
443  // well into the name table. Only do that if we are going to actually emit
444  // that name.
445  if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
446  (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
447  addAccelName(CU, SP->getLinkageName(), Die);
448 
449  // If this is an Objective-C selector name add it to the ObjC accelerator
450  // too.
451  if (isObjCClass(SP->getName())) {
452  StringRef Class, Category;
453  getObjCClassCategory(SP->getName(), Class, Category);
454  addAccelObjC(CU, Class, Die);
455  if (Category != "")
456  addAccelObjC(CU, Category, Die);
457  // Also add the base method name to the name table.
458  addAccelName(CU, getObjCMethodName(SP->getName()), Die);
459  }
460 }
461 
462 /// Check whether we should create a DIE for the given Scope, return true
463 /// if we don't create a DIE (the corresponding DIE is null).
465  if (Scope->isAbstractScope())
466  return false;
467 
468  // We don't create a DIE if there is no Range.
469  const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
470  if (Ranges.empty())
471  return true;
472 
473  if (Ranges.size() > 1)
474  return false;
475 
476  // We don't create a DIE if we have a single Range and the end label
477  // is null.
478  return !getLabelAfterInsn(Ranges.front().second);
479 }
480 
481 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
482  F(CU);
483  if (auto *SkelCU = CU.getSkeleton())
484  if (CU.getCUNode()->getSplitDebugInlining())
485  F(*SkelCU);
486 }
487 
490 }
491 
492 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
493  LexicalScope *Scope) {
494  assert(Scope && Scope->getScopeNode());
495  assert(Scope->isAbstractScope());
496  assert(!Scope->getInlinedAt());
497 
498  auto *SP = cast<DISubprogram>(Scope->getScopeNode());
499 
500  // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
501  // was inlined from another compile unit.
502  if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
503  // Avoid building the original CU if it won't be used
505  else {
506  auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
507  if (auto *SkelCU = CU.getSkeleton()) {
508  (shareAcrossDWOCUs() ? CU : SrcCU)
509  .constructAbstractSubprogramScopeDIE(Scope);
510  if (CU.getCUNode()->getSplitDebugInlining())
511  SkelCU->constructAbstractSubprogramScopeDIE(Scope);
512  } else
513  CU.constructAbstractSubprogramScopeDIE(Scope);
514  }
515 }
516 
517 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
518  DwarfCompileUnit &CU, DIE &ScopeDIE,
519  const MachineFunction &MF) {
520  // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
521  // the subprogram is required to have one.
522  if (!SP.areAllCallsDescribed() || !SP.isDefinition())
523  return;
524 
525  // Use DW_AT_call_all_calls to express that call site entries are present
526  // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
527  // because one of its requirements is not met: call site entries for
528  // optimized-out calls are elided.
529  CU.addFlag(ScopeDIE, dwarf::DW_AT_call_all_calls);
530 
532  assert(TII && "TargetInstrInfo not found: cannot label tail calls");
533 
534  // Emit call site entries for each call or tail call in the function.
535  for (const MachineBasicBlock &MBB : MF) {
536  for (const MachineInstr &MI : MBB.instrs()) {
537  // Skip instructions which aren't calls. Both calls and tail-calling jump
538  // instructions (e.g TAILJMPd64) are classified correctly here.
539  if (!MI.isCall())
540  continue;
541 
542  // TODO: Add support for targets with delay slots (see: beginInstruction).
543  if (MI.hasDelaySlot())
544  return;
545 
546  // If this is a direct call, find the callee's subprogram.
547  const MachineOperand &CalleeOp = MI.getOperand(0);
548  if (!CalleeOp.isGlobal())
549  continue;
550  const Function *CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
551  if (!CalleeDecl || !CalleeDecl->getSubprogram())
552  continue;
553 
554  // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
555  // TODO: Add support for indirect calls.
556 
557  bool IsTail = TII->isTailCall(MI);
558 
559  // For tail calls, no return PC information is needed. For regular calls,
560  // the return PC is needed to disambiguate paths in the call graph which
561  // could lead to some target function.
562  const MCExpr *PCOffset =
563  IsTail ? nullptr : getFunctionLocalOffsetAfterInsn(&MI);
564 
565  assert((IsTail || PCOffset) && "Call without return PC information");
566  LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
567  << CalleeDecl->getName() << (IsTail ? " [tail]" : "")
568  << "\n");
569  CU.constructCallSiteEntryDIE(ScopeDIE, *CalleeDecl->getSubprogram(),
570  IsTail, PCOffset);
571  }
572  }
573 }
574 
575 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
576  if (!U.hasDwarfPubSections())
577  return;
578 
579  U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
580 }
581 
582 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
583  DwarfCompileUnit &NewCU) {
584  DIE &Die = NewCU.getUnitDie();
585  StringRef FN = DIUnit->getFilename();
586 
587  StringRef Producer = DIUnit->getProducer();
588  StringRef Flags = DIUnit->getFlags();
589  if (!Flags.empty() && !useAppleExtensionAttributes()) {
590  std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
591  NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
592  } else
593  NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
594 
595  NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
596  DIUnit->getSourceLanguage());
597  NewCU.addString(Die, dwarf::DW_AT_name, FN);
598 
599  // Add DW_str_offsets_base to the unit DIE, except for split units.
601  NewCU.addStringOffsetsStart();
602 
603  if (!useSplitDwarf()) {
604  NewCU.initStmtList();
605 
606  // If we're using split dwarf the compilation dir is going to be in the
607  // skeleton CU and so we don't need to duplicate it here.
608  if (!CompilationDir.empty())
609  NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
610 
611  addGnuPubAttributes(NewCU, Die);
612  }
613 
615  if (DIUnit->isOptimized())
616  NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
617 
618  StringRef Flags = DIUnit->getFlags();
619  if (!Flags.empty())
620  NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
621 
622  if (unsigned RVer = DIUnit->getRuntimeVersion())
623  NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
624  dwarf::DW_FORM_data1, RVer);
625  }
626 
627  if (DIUnit->getDWOId()) {
628  // This CU is either a clang module DWO or a skeleton CU.
629  NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
630  DIUnit->getDWOId());
631  if (!DIUnit->getSplitDebugFilename().empty())
632  // This is a prefabricated skeleton CU.
633  NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
634  DIUnit->getSplitDebugFilename());
635  }
636 }
637 // Create new DwarfCompileUnit for the given metadata node with tag
638 // DW_TAG_compile_unit.
640 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
641  if (auto *CU = CUMap.lookup(DIUnit))
642  return *CU;
643 
644  CompilationDir = DIUnit->getDirectory();
645 
646  auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
647  InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
648  DwarfCompileUnit &NewCU = *OwnedUnit;
649  InfoHolder.addUnit(std::move(OwnedUnit));
650 
651  for (auto *IE : DIUnit->getImportedEntities())
652  NewCU.addImportedEntity(IE);
653 
654  // LTO with assembly output shares a single line table amongst multiple CUs.
655  // To avoid the compilation directory being ambiguous, let the line table
656  // explicitly describe the directory of all files, never relying on the
657  // compilation directory.
658  if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
659  Asm->OutStreamer->emitDwarfFile0Directive(
660  CompilationDir, DIUnit->getFilename(),
661  NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(),
662  NewCU.getUniqueID());
663 
664  if (useSplitDwarf()) {
665  NewCU.setSkeleton(constructSkeletonCU(NewCU));
666  NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
667  } else {
668  finishUnitAttributes(DIUnit, NewCU);
669  NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
670  }
671 
672  CUMap.insert({DIUnit, &NewCU});
673  CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
674  return NewCU;
675 }
676 
677 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
678  const DIImportedEntity *N) {
679  if (isa<DILocalScope>(N->getScope()))
680  return;
681  if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
683 }
684 
685 /// Sort and unique GVEs by comparing their fragment offset.
688  llvm::sort(
690  // Sort order: first null exprs, then exprs without fragment
691  // info, then sort by fragment offset in bits.
692  // FIXME: Come up with a more comprehensive comparator so
693  // the sorting isn't non-deterministic, and so the following
694  // std::unique call works correctly.
695  if (!A.Expr || !B.Expr)
696  return !!B.Expr;
697  auto FragmentA = A.Expr->getFragmentInfo();
698  auto FragmentB = B.Expr->getFragmentInfo();
699  if (!FragmentA || !FragmentB)
700  return !!FragmentB;
701  return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
702  });
703  GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
706  return A.Expr == B.Expr;
707  }),
708  GVEs.end());
709  return GVEs;
710 }
711 
712 // Emit all Dwarf sections that should come prior to the content. Create
713 // global DIEs and emit initial debug info sections. This is invoked by
714 // the target AsmPrinter.
716  NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
717  DWARFGroupDescription, TimePassesIsEnabled);
720  return;
721  }
722 
723  const Module *M = MMI->getModule();
724 
725  unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
727  // Tell MMI whether we have debug info.
728  assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
729  "DebugInfoAvailabilty initialized unexpectedly");
730  SingleCU = NumDebugCUs == 1;
732  GVMap;
733  for (const GlobalVariable &Global : M->globals()) {
735  Global.getDebugInfo(GVs);
736  for (auto *GVE : GVs)
737  GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
738  }
739 
740  // Create the symbol that designates the start of the unit's contribution
741  // to the string offsets table. In a split DWARF scenario, only the skeleton
742  // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
744  (useSplitDwarf() ? SkeletonHolder : InfoHolder)
745  .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
746 
747 
748  // Create the symbols that designates the start of the DWARF v5 range list
749  // and locations list tables. They are located past the table headers.
750  if (getDwarfVersion() >= 5) {
751  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
753  Asm->createTempSymbol("rnglists_table_base"));
755  Asm->createTempSymbol("loclists_table_base"));
756 
757  if (useSplitDwarf())
758  InfoHolder.setRnglistsTableBaseSym(
759  Asm->createTempSymbol("rnglists_dwo_table_base"));
760  }
761 
762  // Create the symbol that points to the first entry following the debug
763  // address table (.debug_addr) header.
764  AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
765 
766  for (DICompileUnit *CUNode : M->debug_compile_units()) {
767  // FIXME: Move local imported entities into a list attached to the
768  // subprogram, then this search won't be needed and a
769  // getImportedEntities().empty() test should go below with the rest.
770  bool HasNonLocalImportedEntities = llvm::any_of(
771  CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
772  return !isa<DILocalScope>(IE->getScope());
773  });
774 
775  if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
776  CUNode->getRetainedTypes().empty() &&
777  CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
778  continue;
779 
780  DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
781 
782  // Global Variables.
783  for (auto *GVE : CUNode->getGlobalVariables()) {
784  // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
785  // already know about the variable and it isn't adding a constant
786  // expression.
787  auto &GVMapEntry = GVMap[GVE->getVariable()];
788  auto *Expr = GVE->getExpression();
789  if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
790  GVMapEntry.push_back({nullptr, Expr});
791  }
793  for (auto *GVE : CUNode->getGlobalVariables()) {
794  DIGlobalVariable *GV = GVE->getVariable();
795  if (Processed.insert(GV).second)
797  }
798 
799  for (auto *Ty : CUNode->getEnumTypes()) {
800  // The enum types array by design contains pointers to
801  // MDNodes rather than DIRefs. Unique them here.
802  CU.getOrCreateTypeDIE(cast<DIType>(Ty));
803  }
804  for (auto *Ty : CUNode->getRetainedTypes()) {
805  // The retained types array by design contains pointers to
806  // MDNodes rather than DIRefs. Unique them here.
807  if (DIType *RT = dyn_cast<DIType>(Ty))
808  // There is no point in force-emitting a forward declaration.
809  CU.getOrCreateTypeDIE(RT);
810  }
811  // Emit imported_modules last so that the relevant context is already
812  // available.
813  for (auto *IE : CUNode->getImportedEntities())
814  constructAndAddImportedEntityDIE(CU, IE);
815  }
816 }
817 
818 void DwarfDebug::finishEntityDefinitions() {
819  for (const auto &Entity : ConcreteEntities) {
820  DIE *Die = Entity->getDIE();
821  assert(Die);
822  // FIXME: Consider the time-space tradeoff of just storing the unit pointer
823  // in the ConcreteEntities list, rather than looking it up again here.
824  // DIE::getUnit isn't simple - it walks parent pointers, etc.
825  DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
826  assert(Unit);
827  Unit->finishEntityDefinition(Entity.get());
828  }
829 }
830 
831 void DwarfDebug::finishSubprogramDefinitions() {
832  for (const DISubprogram *SP : ProcessedSPNodes) {
833  assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
834  forBothCUs(
835  getOrCreateDwarfCompileUnit(SP->getUnit()),
836  [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
837  }
838 }
839 
840 void DwarfDebug::finalizeModuleInfo() {
842 
843  finishSubprogramDefinitions();
844 
845  finishEntityDefinitions();
846 
847  // Include the DWO file name in the hash if there's more than one CU.
848  // This handles ThinLTO's situation where imported CUs may very easily be
849  // duplicate with the same CU partially imported into another ThinLTO unit.
850  StringRef DWOName;
851  if (CUMap.size() > 1)
853 
854  // Handle anything that needs to be done on a per-unit basis after
855  // all other generation.
856  for (const auto &P : CUMap) {
857  auto &TheCU = *P.second;
858  if (TheCU.getCUNode()->isDebugDirectivesOnly())
859  continue;
860  // Emit DW_AT_containing_type attribute to connect types with their
861  // vtable holding type.
863 
864  // Add CU specific attributes if we need to add any.
865  // If we're splitting the dwarf out now that we've got the entire
866  // CU then add the dwo id to it.
867  auto *SkCU = TheCU.getSkeleton();
868  if (useSplitDwarf() && !empty(TheCU.getUnitDie().children())) {
869  finishUnitAttributes(TheCU.getCUNode(), TheCU);
870  TheCU.addString(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
872  SkCU->addString(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
874  // Emit a unique identifier for this CU.
875  uint64_t ID =
876  DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
877  if (getDwarfVersion() >= 5) {
878  TheCU.setDWOId(ID);
879  SkCU->setDWOId(ID);
880  } else {
881  TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
882  dwarf::DW_FORM_data8, ID);
883  SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
884  dwarf::DW_FORM_data8, ID);
885  }
886 
887  if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
888  const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
889  SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
890  Sym, Sym);
891  }
892  } else if (SkCU) {
893  finishUnitAttributes(SkCU->getCUNode(), *SkCU);
894  }
895 
896  // If we have code split among multiple sections or non-contiguous
897  // ranges of code then emit a DW_AT_ranges attribute on the unit that will
898  // remain in the .o file, otherwise add a DW_AT_low_pc.
899  // FIXME: We should use ranges allow reordering of code ala
900  // .subsections_via_symbols in mach-o. This would mean turning on
901  // ranges for all subprogram DIEs for mach-o.
902  DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
903 
904  if (unsigned NumRanges = TheCU.getRanges().size()) {
905  if (NumRanges > 1 && useRangesSection())
906  // A DW_AT_low_pc attribute may also be specified in combination with
907  // DW_AT_ranges to specify the default base address for use in
908  // location lists (see Section 2.6.2) and range lists (see Section
909  // 2.17.3).
910  U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
911  else
912  U.setBaseAddress(TheCU.getRanges().front().getStart());
913  U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
914  }
915 
916  // We don't keep track of which addresses are used in which CU so this
917  // is a bit pessimistic under LTO.
918  if (!AddrPool.isEmpty() &&
919  (getDwarfVersion() >= 5 ||
920  (SkCU && !empty(TheCU.getUnitDie().children()))))
921  U.addAddrTableBase();
922 
923  if (getDwarfVersion() >= 5) {
924  if (U.hasRangeLists())
925  U.addRnglistsBase();
926 
927  if (!DebugLocs.getLists().empty() && !useSplitDwarf())
928  U.addLoclistsBase();
929  }
930 
931  auto *CUNode = cast<DICompileUnit>(P.first);
932  // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
933  if (CUNode->getMacros())
934  U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
935  U.getMacroLabelBegin(),
937  }
938 
939  // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
940  for (auto *CUNode : MMI->getModule()->debug_compile_units())
941  if (CUNode->getDWOId())
942  getOrCreateDwarfCompileUnit(CUNode);
943 
944  // Compute DIE offsets and sizes.
945  InfoHolder.computeSizeAndOffsets();
946  if (useSplitDwarf())
947  SkeletonHolder.computeSizeAndOffsets();
948 }
949 
950 // Emit all Dwarf sections that should come after the content.
952  assert(CurFn == nullptr);
953  assert(CurMI == nullptr);
954 
955  for (const auto &P : CUMap) {
956  auto &CU = *P.second;
957  CU.createBaseTypeDIEs();
958  }
959 
960  // If we aren't actually generating debug info (check beginModule -
961  // conditionalized on !DisableDebugInfoPrinting and the presence of the
962  // llvm.dbg.cu metadata node)
963  if (!MMI->hasDebugInfo())
964  return;
965 
966  // Finalize the debug info for the module.
967  finalizeModuleInfo();
968 
969  emitDebugStr();
970 
971  if (useSplitDwarf())
972  emitDebugLocDWO();
973  else
974  // Emit info into a debug loc section.
975  emitDebugLoc();
976 
977  // Corresponding abbreviations into a abbrev section.
978  emitAbbreviations();
979 
980  // Emit all the DIEs into a debug info section.
981  emitDebugInfo();
982 
983  // Emit info into a debug aranges section.
985  emitDebugARanges();
986 
987  // Emit info into a debug ranges section.
988  emitDebugRanges();
989 
990  // Emit info into a debug macinfo section.
991  emitDebugMacinfo();
992 
993  if (useSplitDwarf()) {
994  emitDebugStrDWO();
995  emitDebugInfoDWO();
996  emitDebugAbbrevDWO();
997  emitDebugLineDWO();
998  emitDebugRangesDWO();
999  }
1000 
1001  emitDebugAddr();
1002 
1003  // Emit info into the dwarf accelerator table sections.
1004  switch (getAccelTableKind()) {
1005  case AccelTableKind::Apple:
1006  emitAccelNames();
1007  emitAccelObjC();
1008  emitAccelNamespaces();
1009  emitAccelTypes();
1010  break;
1011  case AccelTableKind::Dwarf:
1012  emitAccelDebugNames();
1013  break;
1014  case AccelTableKind::None:
1015  break;
1017  llvm_unreachable("Default should have already been resolved.");
1018  }
1019 
1020  // Emit the pubnames and pubtypes sections if requested.
1021  emitDebugPubSections();
1022 
1023  // clean up.
1024  // FIXME: AbstractVariables.clear();
1025 }
1026 
1027 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1028  const DINode *Node,
1029  const MDNode *ScopeNode) {
1030  if (CU.getExistingAbstractEntity(Node))
1031  return;
1032 
1034  cast<DILocalScope>(ScopeNode)));
1035 }
1036 
1037 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1038  const DINode *Node, const MDNode *ScopeNode) {
1039  if (CU.getExistingAbstractEntity(Node))
1040  return;
1041 
1042  if (LexicalScope *Scope =
1043  LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1044  CU.createAbstractEntity(Node, Scope);
1045 }
1046 
1047 // Collect variable information from side table maintained by MF.
1048 void DwarfDebug::collectVariableInfoFromMFTable(
1049  DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1051  for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1052  if (!VI.Var)
1053  continue;
1054  assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1055  "Expected inlined-at fields to agree");
1056 
1057  InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1058  Processed.insert(Var);
1059  LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1060 
1061  // If variable scope is not found then skip this variable.
1062  if (!Scope)
1063  continue;
1064 
1065  ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1066  auto RegVar = llvm::make_unique<DbgVariable>(
1067  cast<DILocalVariable>(Var.first), Var.second);
1068  RegVar->initializeMMI(VI.Expr, VI.Slot);
1069  if (DbgVariable *DbgVar = MFVars.lookup(Var))
1070  DbgVar->addMMIEntry(*RegVar);
1071  else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1072  MFVars.insert({Var, RegVar.get()});
1073  ConcreteEntities.push_back(std::move(RegVar));
1074  }
1075  }
1076 }
1077 
1078 // Get .debug_loc entry for the instruction range starting at MI.
1080  const DIExpression *Expr = MI->getDebugExpression();
1081  assert(MI->getNumOperands() == 4);
1082  if (MI->getOperand(0).isReg()) {
1083  auto RegOp = MI->getOperand(0);
1084  auto Op1 = MI->getOperand(1);
1085  // If the second operand is an immediate, this is a
1086  // register-indirect address.
1087  assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
1088  MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
1089  return DebugLocEntry::Value(Expr, MLoc);
1090  }
1091  if (MI->getOperand(0).isImm())
1092  return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
1093  if (MI->getOperand(0).isFPImm())
1094  return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
1095  if (MI->getOperand(0).isCImm())
1096  return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
1097 
1098  llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1099 }
1100 
1101 /// Build the location list for all DBG_VALUEs in the function that
1102 /// describe the same variable. The resulting DebugLocEntries will have
1103 /// strict monotonically increasing begin addresses and will never
1104 /// overlap.
1105 //
1106 // See the definition of DbgValueHistoryMap::Entry for an explanation of the
1107 // different kinds of history map entries. One thing to be aware of is that if
1108 // a debug value is ended by another entry (rather than being valid until the
1109 // end of the function), that entry's instruction may or may not be included in
1110 // the range, depending on if the entry is a clobbering entry (it has an
1111 // instruction that clobbers one or more preceding locations), or if it is an
1112 // (overlapping) debug value entry. This distinction can be seen in the example
1113 // below. The first debug value is ended by the clobbering entry 2, and the
1114 // second and third debug values are ended by the overlapping debug value entry
1115 // 4.
1116 //
1117 // Input:
1118 //
1119 // History map entries [type, end index, mi]
1120 //
1121 // 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1122 // 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1123 // 2 | | [Clobber, $reg0 = [...], -, -]
1124 // 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1125 // 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1126 //
1127 // Output [start, end) [Value...]:
1128 //
1129 // [0-1) [(reg0, fragment 0, 32)]
1130 // [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1131 // [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1132 // [4-) [(@g, fragment 0, 96)]
1133 void DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1134  const DbgValueHistoryMap::Entries &Entries) {
1135  using OpenRange =
1136  std::pair<DbgValueHistoryMap::EntryIndex, DebugLocEntry::Value>;
1137  SmallVector<OpenRange, 4> OpenRanges;
1138 
1139  for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1140  const MachineInstr *Instr = EI->getInstr();
1141 
1142  if (EI->isDbgValue()) {
1143  // Check if a variable is inaccessible in this range.
1144  // TODO: This should only truncate open ranges that are overlapping.
1145  if (Instr->getNumOperands() > 1 &&
1146  Instr->getOperand(0).isReg() && !Instr->getOperand(0).getReg()) {
1147  OpenRanges.clear();
1148  continue;
1149  }
1150  }
1151 
1152  // Remove all values that are no longer live.
1153  size_t Index = std::distance(EB, EI);
1154  auto Last =
1155  remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1156  OpenRanges.erase(Last, OpenRanges.end());
1157 
1158  // If we are dealing with a clobbering entry, this iteration will result in
1159  // a location list entry starting after the clobbering instruction.
1160  const MCSymbol *StartLabel =
1161  EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1162  assert(StartLabel &&
1163  "Forgot label before/after instruction starting a range!");
1164 
1165  const MCSymbol *EndLabel;
1166  if (std::next(EI) == Entries.end())
1167  EndLabel = Asm->getFunctionEnd();
1168  else if (std::next(EI)->isClobber())
1169  EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1170  else
1171  EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1172  assert(EndLabel && "Forgot label after instruction ending a range!");
1173 
1174  if (EI->isDbgValue())
1175  LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1176 
1177  // If this history map entry has a debug value, add that to the list of
1178  // open ranges.
1179  if (EI->isDbgValue()) {
1180  auto Value = getDebugLocValue(Instr);
1181  OpenRanges.emplace_back(EI->getEndIndex(), Value);
1182  }
1183 
1184  // Location list entries with empty location descriptions are redundant
1185  // information in DWARF, so do not emit those.
1186  if (OpenRanges.empty())
1187  continue;
1188 
1189  // Omit entries with empty ranges as they do not have any effect in DWARF.
1190  if (StartLabel == EndLabel) {
1191  LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1192  continue;
1193  }
1194 
1196  for (auto &R : OpenRanges)
1197  Values.push_back(R.second);
1198  DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1199 
1200  // Attempt to coalesce the ranges of two otherwise identical
1201  // DebugLocEntries.
1202  auto CurEntry = DebugLoc.rbegin();
1203  LLVM_DEBUG({
1204  dbgs() << CurEntry->getValues().size() << " Values:\n";
1205  for (auto &Value : CurEntry->getValues())
1206  Value.dump();
1207  dbgs() << "-----\n";
1208  });
1209 
1210  auto PrevEntry = std::next(CurEntry);
1211  if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1212  DebugLoc.pop_back();
1213  }
1214 }
1215 
1216 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1217  LexicalScope &Scope,
1218  const DINode *Node,
1219  const DILocation *Location,
1220  const MCSymbol *Sym) {
1221  ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1222  if (isa<const DILocalVariable>(Node)) {
1223  ConcreteEntities.push_back(
1224  llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1225  Location));
1226  InfoHolder.addScopeVariable(&Scope,
1227  cast<DbgVariable>(ConcreteEntities.back().get()));
1228  } else if (isa<const DILabel>(Node)) {
1229  ConcreteEntities.push_back(
1230  llvm::make_unique<DbgLabel>(cast<const DILabel>(Node),
1231  Location, Sym));
1232  InfoHolder.addScopeLabel(&Scope,
1233  cast<DbgLabel>(ConcreteEntities.back().get()));
1234  }
1235  return ConcreteEntities.back().get();
1236 }
1237 
1238 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1239 /// enclosing lexical scope. The check ensures there are no other instructions
1240 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1241 /// either open or otherwise rolls off the end of the scope.
1243  const MachineInstr *DbgValue,
1244  const MachineInstr *RangeEnd) {
1245  assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1246  auto MBB = DbgValue->getParent();
1247  auto DL = DbgValue->getDebugLoc();
1248  auto *LScope = LScopes.findLexicalScope(DL);
1249  // Scope doesn't exist; this is a dead DBG_VALUE.
1250  if (!LScope)
1251  return false;
1252  auto &LSRange = LScope->getRanges();
1253  if (LSRange.size() == 0)
1254  return false;
1255 
1256  // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1257  const MachineInstr *LScopeBegin = LSRange.front().first;
1258  // Early exit if the lexical scope begins outside of the current block.
1259  if (LScopeBegin->getParent() != MBB)
1260  return false;
1262  for (++Pred; Pred != MBB->rend(); ++Pred) {
1263  if (Pred->getFlag(MachineInstr::FrameSetup))
1264  break;
1265  auto PredDL = Pred->getDebugLoc();
1266  if (!PredDL || Pred->isMetaInstruction())
1267  continue;
1268  // Check whether the instruction preceding the DBG_VALUE is in the same
1269  // (sub)scope as the DBG_VALUE.
1270  if (DL->getScope() == PredDL->getScope())
1271  return false;
1272  auto *PredScope = LScopes.findLexicalScope(PredDL);
1273  if (!PredScope || LScope->dominates(PredScope))
1274  return false;
1275  }
1276 
1277  // If the range of the DBG_VALUE is open-ended, report success.
1278  if (!RangeEnd)
1279  return true;
1280 
1281  // Fail if there are instructions belonging to our scope in another block.
1282  const MachineInstr *LScopeEnd = LSRange.back().second;
1283  if (LScopeEnd->getParent() != MBB)
1284  return false;
1285 
1286  // Single, constant DBG_VALUEs in the prologue are promoted to be live
1287  // throughout the function. This is a hack, presumably for DWARF v2 and not
1288  // necessarily correct. It would be much better to use a dbg.declare instead
1289  // if we know the constant is live throughout the scope.
1290  if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1291  return true;
1292 
1293  return false;
1294 }
1295 
1296 // Find variables for each lexical scope.
1297 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1298  const DISubprogram *SP,
1299  DenseSet<InlinedEntity> &Processed) {
1300  // Grab the variable info that was squirreled away in the MMI side-table.
1301  collectVariableInfoFromMFTable(TheCU, Processed);
1302 
1303  for (const auto &I : DbgValues) {
1304  InlinedEntity IV = I.first;
1305  if (Processed.count(IV))
1306  continue;
1307 
1308  // Instruction ranges, specifying where IV is accessible.
1309  const auto &HistoryMapEntries = I.second;
1310  if (HistoryMapEntries.empty())
1311  continue;
1312 
1313  LexicalScope *Scope = nullptr;
1314  const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1315  if (const DILocation *IA = IV.second)
1316  Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1317  else
1318  Scope = LScopes.findLexicalScope(LocalVar->getScope());
1319  // If variable scope is not found then skip this variable.
1320  if (!Scope)
1321  continue;
1322 
1323  Processed.insert(IV);
1324  DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1325  *Scope, LocalVar, IV.second));
1326 
1327  const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1328  assert(MInsn->isDebugValue() && "History must begin with debug value");
1329 
1330  // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1331  // If the history map contains a single debug value, there may be an
1332  // additional entry which clobbers the debug value.
1333  bool SingleValueWithClobber =
1334  HistoryMapEntries.size() == 2 && HistoryMapEntries[1].isClobber();
1335  if (HistoryMapEntries.size() == 1 || SingleValueWithClobber) {
1336  const auto *End =
1337  SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1338  if (validThroughout(LScopes, MInsn, End)) {
1339  RegVar->initializeDbgValue(MInsn);
1340  continue;
1341  }
1342  }
1343 
1344  // Do not emit location lists if .debug_loc secton is disabled.
1345  if (!useLocSection())
1346  continue;
1347 
1348  // Handle multiple DBG_VALUE instructions describing one variable.
1349  DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1350 
1351  // Build the location list for this variable.
1353  buildLocationList(Entries, HistoryMapEntries);
1354 
1355  // If the variable has a DIBasicType, extract it. Basic types cannot have
1356  // unique identifiers, so don't bother resolving the type with the
1357  // identifier map.
1358  const DIBasicType *BT = dyn_cast<DIBasicType>(
1359  static_cast<const Metadata *>(LocalVar->getType()));
1360 
1361  // Finalize the entry by lowering it into a DWARF bytestream.
1362  for (auto &Entry : Entries)
1363  Entry.finalize(*Asm, List, BT, TheCU);
1364  }
1365 
1366  // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1367  // DWARF-related DbgLabel.
1368  for (const auto &I : DbgLabels) {
1369  InlinedEntity IL = I.first;
1370  const MachineInstr *MI = I.second;
1371  if (MI == nullptr)
1372  continue;
1373 
1374  LexicalScope *Scope = nullptr;
1375  const DILabel *Label = cast<DILabel>(IL.first);
1376  // Get inlined DILocation if it is inlined label.
1377  if (const DILocation *IA = IL.second)
1378  Scope = LScopes.findInlinedScope(Label->getScope(), IA);
1379  else
1380  Scope = LScopes.findLexicalScope(Label->getScope());
1381  // If label scope is not found then skip this label.
1382  if (!Scope)
1383  continue;
1384 
1385  Processed.insert(IL);
1386  /// At this point, the temporary label is created.
1387  /// Save the temporary label to DbgLabel entity to get the
1388  /// actually address when generating Dwarf DIE.
1389  MCSymbol *Sym = getLabelBeforeInsn(MI);
1390  createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1391  }
1392 
1393  // Collect info for variables/labels that were optimized out.
1394  for (const DINode *DN : SP->getRetainedNodes()) {
1395  if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1396  continue;
1397  LexicalScope *Scope = nullptr;
1398  if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1399  Scope = LScopes.findLexicalScope(DV->getScope());
1400  } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1401  Scope = LScopes.findLexicalScope(DL->getScope());
1402  }
1403 
1404  if (Scope)
1405  createConcreteEntity(TheCU, *Scope, DN, nullptr);
1406  }
1407 }
1408 
1409 // Process beginning of an instruction.
1412  assert(CurMI);
1413 
1414  const auto *SP = MI->getMF()->getFunction().getSubprogram();
1415  if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1416  return;
1417 
1418  // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1419  // If the instruction is part of the function frame setup code, do not emit
1420  // any line record, as there is no correspondence with any user code.
1422  return;
1423  const DebugLoc &DL = MI->getDebugLoc();
1424  // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1425  // the last line number actually emitted, to see if it was line 0.
1426  unsigned LastAsmLine =
1427  Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1428 
1429  // Request a label after the call in order to emit AT_return_pc information
1430  // in call site entries. TODO: Add support for targets with delay slots.
1431  if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot())
1433 
1434  if (DL == PrevInstLoc) {
1435  // If we have an ongoing unspecified location, nothing to do here.
1436  if (!DL)
1437  return;
1438  // We have an explicit location, same as the previous location.
1439  // But we might be coming back to it after a line 0 record.
1440  if (LastAsmLine == 0 && DL.getLine() != 0) {
1441  // Reinstate the source location but not marked as a statement.
1442  const MDNode *Scope = DL.getScope();
1443  recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1444  }
1445  return;
1446  }
1447 
1448  if (!DL) {
1449  // We have an unspecified location, which might want to be line 0.
1450  // If we have already emitted a line-0 record, don't repeat it.
1451  if (LastAsmLine == 0)
1452  return;
1453  // If user said Don't Do That, don't do that.
1454  if (UnknownLocations == Disable)
1455  return;
1456  // See if we have a reason to emit a line-0 record now.
1457  // Reasons to emit a line-0 record include:
1458  // - User asked for it (UnknownLocations).
1459  // - Instruction has a label, so it's referenced from somewhere else,
1460  // possibly debug information; we want it to have a source location.
1461  // - Instruction is at the top of a block; we don't want to inherit the
1462  // location from the physically previous (maybe unrelated) block.
1463  if (UnknownLocations == Enable || PrevLabel ||
1464  (PrevInstBB && PrevInstBB != MI->getParent())) {
1465  // Preserve the file and column numbers, if we can, to save space in
1466  // the encoded line table.
1467  // Do not update PrevInstLoc, it remembers the last non-0 line.
1468  const MDNode *Scope = nullptr;
1469  unsigned Column = 0;
1470  if (PrevInstLoc) {
1471  Scope = PrevInstLoc.getScope();
1472  Column = PrevInstLoc.getCol();
1473  }
1474  recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1475  }
1476  return;
1477  }
1478 
1479  // We have an explicit location, different from the previous location.
1480  // Don't repeat a line-0 record, but otherwise emit the new location.
1481  // (The new location might be an explicit line 0, which we do emit.)
1482  if (DL.getLine() == 0 && LastAsmLine == 0)
1483  return;
1484  unsigned Flags = 0;
1485  if (DL == PrologEndLoc) {
1487  PrologEndLoc = DebugLoc();
1488  }
1489  // If the line changed, we call that a new statement; unless we went to
1490  // line 0 and came back, in which case it is not a new statement.
1491  unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1492  if (DL.getLine() && DL.getLine() != OldLine)
1493  Flags |= DWARF2_FLAG_IS_STMT;
1494 
1495  const MDNode *Scope = DL.getScope();
1496  recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1497 
1498  // If we're not at line 0, remember this location.
1499  if (DL.getLine())
1500  PrevInstLoc = DL;
1501 }
1502 
1503 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1504  // First known non-DBG_VALUE and non-frame setup location marks
1505  // the beginning of the function body.
1506  for (const auto &MBB : *MF)
1507  for (const auto &MI : MBB)
1508  if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1509  MI.getDebugLoc())
1510  return MI.getDebugLoc();
1511  return DebugLoc();
1512 }
1513 
1514 /// Register a source line with debug info. Returns the unique label that was
1515 /// emitted and which provides correspondence to the source line list.
1516 static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
1517  const MDNode *S, unsigned Flags, unsigned CUID,
1518  uint16_t DwarfVersion,
1519  ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
1520  StringRef Fn;
1521  unsigned FileNo = 1;
1522  unsigned Discriminator = 0;
1523  if (auto *Scope = cast_or_null<DIScope>(S)) {
1524  Fn = Scope->getFilename();
1525  if (Line != 0 && DwarfVersion >= 4)
1526  if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1527  Discriminator = LBF->getDiscriminator();
1528 
1529  FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
1530  .getOrCreateSourceID(Scope->getFile());
1531  }
1532  Asm.OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
1533  Discriminator, Fn);
1534 }
1535 
1537  unsigned CUID) {
1538  // Get beginning of function.
1539  if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
1540  // Ensure the compile unit is created if the function is called before
1541  // beginFunction().
1542  (void)getOrCreateDwarfCompileUnit(
1543  MF.getFunction().getSubprogram()->getUnit());
1544  // We'd like to list the prologue as "not statements" but GDB behaves
1545  // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1546  const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1547  ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
1548  CUID, getDwarfVersion(), getUnits());
1549  return PrologEndLoc;
1550  }
1551  return DebugLoc();
1552 }
1553 
1554 // Gather pre-function debug information. Assumes being called immediately
1555 // after the function entry point has been emitted.
1557  CurFn = MF;
1558 
1559  auto *SP = MF->getFunction().getSubprogram();
1561  if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1562  return;
1563 
1564  DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1565 
1566  // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1567  // belongs to so that we add to the correct per-cu line table in the
1568  // non-asm case.
1569  if (Asm->OutStreamer->hasRawTextSupport())
1570  // Use a single line table if we are generating assembly.
1571  Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1572  else
1573  Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1574 
1575  // Record beginning of function.
1577  *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
1578 }
1579 
1581  // If we don't have a subprogram for this function then there will be a hole
1582  // in the range information. Keep note of this by setting the previously used
1583  // section to nullptr.
1584  PrevCU = nullptr;
1585  CurFn = nullptr;
1586 }
1587 
1588 // Gather and emit post-function debug information.
1590  const DISubprogram *SP = MF->getFunction().getSubprogram();
1591 
1592  assert(CurFn == MF &&
1593  "endFunction should be called with the same function as beginFunction");
1594 
1595  // Set DwarfDwarfCompileUnitID in MCContext to default value.
1596  Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1597 
1599  assert(!FnScope || SP == FnScope->getScopeNode());
1600  DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1601  if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1602  PrevLabel = nullptr;
1603  CurFn = nullptr;
1604  return;
1605  }
1606 
1607  DenseSet<InlinedEntity> Processed;
1608  collectEntityInfo(TheCU, SP, Processed);
1609 
1610  // Add the range of this function to the list of ranges for the CU.
1611  TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1612 
1613  // Under -gmlt, skip building the subprogram if there are no inlined
1614  // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1615  // is still needed as we need its source location.
1616  if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1617  TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1618  LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1619  assert(InfoHolder.getScopeVariables().empty());
1620  PrevLabel = nullptr;
1621  CurFn = nullptr;
1622  return;
1623  }
1624 
1625 #ifndef NDEBUG
1626  size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1627 #endif
1628  // Construct abstract scopes.
1629  for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1630  auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1631  for (const DINode *DN : SP->getRetainedNodes()) {
1632  if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1633  continue;
1634 
1635  const MDNode *Scope = nullptr;
1636  if (auto *DV = dyn_cast<DILocalVariable>(DN))
1637  Scope = DV->getScope();
1638  else if (auto *DL = dyn_cast<DILabel>(DN))
1639  Scope = DL->getScope();
1640  else
1641  llvm_unreachable("Unexpected DI type!");
1642 
1643  // Collect info for variables/labels that were optimized out.
1644  ensureAbstractEntityIsCreated(TheCU, DN, Scope);
1645  assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1646  && "ensureAbstractEntityIsCreated inserted abstract scopes");
1647  }
1648  constructAbstractSubprogramScopeDIE(TheCU, AScope);
1649  }
1650 
1651  ProcessedSPNodes.insert(SP);
1652  DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
1653  if (auto *SkelCU = TheCU.getSkeleton())
1654  if (!LScopes.getAbstractScopesList().empty() &&
1655  TheCU.getCUNode()->getSplitDebugInlining())
1656  SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1657 
1658  // Construct call site entries.
1659  constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
1660 
1661  // Clear debug info
1662  // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1663  // DbgVariables except those that are also in AbstractVariables (since they
1664  // can be used cross-function)
1665  InfoHolder.getScopeVariables().clear();
1666  InfoHolder.getScopeLabels().clear();
1667  PrevLabel = nullptr;
1668  CurFn = nullptr;
1669 }
1670 
1671 // Register a source line with debug info. Returns the unique label that was
1672 // emitted and which provides correspondence to the source line list.
1673 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1674  unsigned Flags) {
1675  ::recordSourceLine(*Asm, Line, Col, S, Flags,
1676  Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
1677  getDwarfVersion(), getUnits());
1678 }
1679 
1680 //===----------------------------------------------------------------------===//
1681 // Emit Methods
1682 //===----------------------------------------------------------------------===//
1683 
1684 // Emit the debug info section.
1685 void DwarfDebug::emitDebugInfo() {
1686  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1687  Holder.emitUnits(/* UseOffsets */ false);
1688 }
1689 
1690 // Emit the abbreviation section.
1691 void DwarfDebug::emitAbbreviations() {
1692  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1693 
1695 }
1696 
1697 void DwarfDebug::emitStringOffsetsTableHeader() {
1698  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1701  Holder.getStringOffsetsStartSym());
1702 }
1703 
1704 template <typename AccelTableT>
1705 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
1706  StringRef TableName) {
1707  Asm->OutStreamer->SwitchSection(Section);
1708 
1709  // Emit the full data.
1710  emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1711 }
1712 
1713 void DwarfDebug::emitAccelDebugNames() {
1714  // Don't emit anything if we have no compilation units to index.
1715  if (getUnits().empty())
1716  return;
1717 
1718  emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
1719 }
1720 
1721 // Emit visible names into a hashed accelerator table section.
1722 void DwarfDebug::emitAccelNames() {
1723  emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1724  "Names");
1725 }
1726 
1727 // Emit objective C classes and categories into a hashed accelerator table
1728 // section.
1729 void DwarfDebug::emitAccelObjC() {
1730  emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1731  "ObjC");
1732 }
1733 
1734 // Emit namespace dies into a hashed accelerator table.
1735 void DwarfDebug::emitAccelNamespaces() {
1736  emitAccel(AccelNamespace,
1738  "namespac");
1739 }
1740 
1741 // Emit type dies into a hashed accelerator table.
1742 void DwarfDebug::emitAccelTypes() {
1743  emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1744  "types");
1745 }
1746 
1747 // Public name handling.
1748 // The format for the various pubnames:
1749 //
1750 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1751 // for the DIE that is named.
1752 //
1753 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1754 // into the CU and the index value is computed according to the type of value
1755 // for the DIE that is named.
1756 //
1757 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1758 // it's the offset within the debug_info/debug_types dwo section, however, the
1759 // reference in the pubname header doesn't change.
1760 
1761 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1763  const DIE *Die) {
1764  // Entities that ended up only in a Type Unit reference the CU instead (since
1765  // the pub entry has offsets within the CU there's no real offset that can be
1766  // provided anyway). As it happens all such entities (namespaces and types,
1767  // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
1768  // not to be true it would be necessary to persist this information from the
1769  // point at which the entry is added to the index data structure - since by
1770  // the time the index is built from that, the original type/namespace DIE in a
1771  // type unit has already been destroyed so it can't be queried for properties
1772  // like tag, etc.
1773  if (Die->getTag() == dwarf::DW_TAG_compile_unit)
1777 
1778  // We could have a specification DIE that has our most of our knowledge,
1779  // look for that now.
1780  if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1781  DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1782  if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1783  Linkage = dwarf::GIEL_EXTERNAL;
1784  } else if (Die->findAttribute(dwarf::DW_AT_external))
1785  Linkage = dwarf::GIEL_EXTERNAL;
1786 
1787  switch (Die->getTag()) {
1788  case dwarf::DW_TAG_class_type:
1789  case dwarf::DW_TAG_structure_type:
1790  case dwarf::DW_TAG_union_type:
1791  case dwarf::DW_TAG_enumeration_type:
1793  dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1796  case dwarf::DW_TAG_typedef:
1797  case dwarf::DW_TAG_base_type:
1798  case dwarf::DW_TAG_subrange_type:
1800  case dwarf::DW_TAG_namespace:
1801  return dwarf::GIEK_TYPE;
1802  case dwarf::DW_TAG_subprogram:
1804  case dwarf::DW_TAG_variable:
1806  case dwarf::DW_TAG_enumerator:
1809  default:
1810  return dwarf::GIEK_NONE;
1811  }
1812 }
1813 
1814 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
1815 /// pubtypes sections.
1816 void DwarfDebug::emitDebugPubSections() {
1817  for (const auto &NU : CUMap) {
1818  DwarfCompileUnit *TheU = NU.second;
1819  if (!TheU->hasDwarfPubSections())
1820  continue;
1821 
1822  bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
1824 
1825  Asm->OutStreamer->SwitchSection(
1828  emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
1829 
1830  Asm->OutStreamer->SwitchSection(
1833  emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
1834  }
1835 }
1836 
1837 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
1840  CU.getDebugSectionOffset());
1841  else
1843 }
1844 
1845 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
1846  DwarfCompileUnit *TheU,
1847  const StringMap<const DIE *> &Globals) {
1848  if (auto *Skeleton = TheU->getSkeleton())
1849  TheU = Skeleton;
1850 
1851  // Emit the header.
1852  Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1853  MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1854  MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1855  Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1856 
1857  Asm->OutStreamer->EmitLabel(BeginLabel);
1858 
1859  Asm->OutStreamer->AddComment("DWARF Version");
1861 
1862  Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1863  emitSectionReference(*TheU);
1864 
1865  Asm->OutStreamer->AddComment("Compilation Unit Length");
1866  Asm->emitInt32(TheU->getLength());
1867 
1868  // Emit the pubnames for this compilation unit.
1869  for (const auto &GI : Globals) {
1870  const char *Name = GI.getKeyData();
1871  const DIE *Entity = GI.second;
1872 
1873  Asm->OutStreamer->AddComment("DIE offset");
1874  Asm->emitInt32(Entity->getOffset());
1875 
1876  if (GnuStyle) {
1878  Asm->OutStreamer->AddComment(
1879  Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
1881  Asm->emitInt8(Desc.toBits());
1882  }
1883 
1884  Asm->OutStreamer->AddComment("External Name");
1885  Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1886  }
1887 
1888  Asm->OutStreamer->AddComment("End Mark");
1889  Asm->emitInt32(0);
1890  Asm->OutStreamer->EmitLabel(EndLabel);
1891 }
1892 
1893 /// Emit null-terminated strings into a debug str section.
1894 void DwarfDebug::emitDebugStr() {
1895  MCSection *StringOffsetsSection = nullptr;
1897  emitStringOffsetsTableHeader();
1898  StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
1899  }
1900  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1902  StringOffsetsSection, /* UseRelativeOffsets = */ true);
1903 }
1904 
1907  const DwarfCompileUnit *CU) {
1908  auto &&Comments = DebugLocs.getComments(Entry);
1909  auto Comment = Comments.begin();
1910  auto End = Comments.end();
1911 
1912  // The expressions are inserted into a byte stream rather early (see
1913  // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
1914  // need to reference a base_type DIE the offset of that DIE is not yet known.
1915  // To deal with this we instead insert a placeholder early and then extract
1916  // it here and replace it with the real reference.
1917  unsigned PtrSize = Asm->MAI->getCodePointerSize();
1918  DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
1919  DebugLocs.getBytes(Entry).size()),
1920  Asm->getDataLayout().isLittleEndian(), PtrSize);
1921  DWARFExpression Expr(Data, getDwarfVersion(), PtrSize);
1922 
1923  using Encoding = DWARFExpression::Operation::Encoding;
1924  uint32_t Offset = 0;
1925  for (auto &Op : Expr) {
1926  assert(Op.getCode() != dwarf::DW_OP_const_type &&
1927  "3 operand ops not yet supported");
1928  Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
1929  Offset++;
1930  for (unsigned I = 0; I < 2; ++I) {
1931  if (Op.getDescription().Op[I] == Encoding::SizeNA)
1932  continue;
1933  if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
1934  if (CU) {
1935  uint64_t Offset = CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset();
1936  assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit");
1937  Asm->EmitULEB128(Offset, nullptr, ULEB128PadSize);
1938  } else {
1939  // Emit a reference to the 'generic type'.
1940  Asm->EmitULEB128(0, nullptr, ULEB128PadSize);
1941  }
1942  // Make sure comments stay aligned.
1943  for (unsigned J = 0; J < ULEB128PadSize; ++J)
1944  if (Comment != End)
1945  Comment++;
1946  } else {
1947  for (uint32_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
1948  Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
1949  }
1950  Offset = Op.getOperandEndOffset(I);
1951  }
1952  assert(Offset == Op.getEndOffset());
1953  }
1954 }
1955 
1956 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1957  const DebugLocEntry::Value &Value,
1958  DwarfExpression &DwarfExpr) {
1959  auto *DIExpr = Value.getExpression();
1960  DIExpressionCursor ExprCursor(DIExpr);
1961  DwarfExpr.addFragmentOffset(DIExpr);
1962  // Regular entry.
1963  if (Value.isInt()) {
1964  if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1965  BT->getEncoding() == dwarf::DW_ATE_signed_char))
1966  DwarfExpr.addSignedConstant(Value.getInt());
1967  else
1968  DwarfExpr.addUnsignedConstant(Value.getInt());
1969  } else if (Value.isLocation()) {
1970  MachineLocation Location = Value.getLoc();
1971  if (Location.isIndirect())
1972  DwarfExpr.setMemoryLocationKind();
1973  DIExpressionCursor Cursor(DIExpr);
1974  const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
1975  if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1976  return;
1977  return DwarfExpr.addExpression(std::move(Cursor));
1978  } else if (Value.isConstantFP()) {
1979  APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
1980  DwarfExpr.addUnsignedConstant(RawBytes);
1981  }
1982  DwarfExpr.addExpression(std::move(ExprCursor));
1983 }
1984 
1987  const DIBasicType *BT,
1988  DwarfCompileUnit &TheCU) {
1989  assert(!Values.empty() &&
1990  "location list entries without values are redundant");
1991  assert(Begin != End && "unexpected location list entry with empty range");
1992  DebugLocStream::EntryBuilder Entry(List, Begin, End);
1993  BufferByteStreamer Streamer = Entry.getStreamer();
1994  DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
1995  const DebugLocEntry::Value &Value = Values[0];
1996  if (Value.isFragment()) {
1997  // Emit all fragments that belong to the same variable and range.
1999  return P.isFragment();
2000  }) && "all values are expected to be fragments");
2001  assert(std::is_sorted(Values.begin(), Values.end()) &&
2002  "fragments are expected to be sorted");
2003 
2004  for (auto Fragment : Values)
2005  emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2006 
2007  } else {
2008  assert(Values.size() == 1 && "only fragments may have >1 value");
2009  emitDebugLocValue(AP, BT, Value, DwarfExpr);
2010  }
2011  DwarfExpr.finalize();
2012 }
2013 
2015  const DwarfCompileUnit *CU) {
2016  // Emit the size.
2017  Asm->OutStreamer->AddComment("Loc expr size");
2018  if (getDwarfVersion() >= 5)
2019  Asm->EmitULEB128(DebugLocs.getBytes(Entry).size());
2020  else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2021  Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2022  else {
2023  // The entry is too big to fit into 16 bit, drop it as there is nothing we
2024  // can do.
2025  Asm->emitInt16(0);
2026  return;
2027  }
2028  // Emit the entry.
2029  APByteStreamer Streamer(*Asm);
2030  emitDebugLocEntry(Streamer, Entry, CU);
2031 }
2032 
2033 // Emit the common part of the DWARF 5 range/locations list tables header.
2035  MCSymbol *TableStart,
2036  MCSymbol *TableEnd) {
2037  // Build the table header, which starts with the length field.
2038  Asm->OutStreamer->AddComment("Length");
2039  Asm->EmitLabelDifference(TableEnd, TableStart, 4);
2040  Asm->OutStreamer->EmitLabel(TableStart);
2041  // Version number (DWARF v5 and later).
2042  Asm->OutStreamer->AddComment("Version");
2043  Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
2044  // Address size.
2045  Asm->OutStreamer->AddComment("Address size");
2046  Asm->emitInt8(Asm->MAI->getCodePointerSize());
2047  // Segment selector size.
2048  Asm->OutStreamer->AddComment("Segment selector size");
2049  Asm->emitInt8(0);
2050 }
2051 
2052 // Emit the header of a DWARF 5 range list table list table. Returns the symbol
2053 // that designates the end of the table for the caller to emit when the table is
2054 // complete.
2056  const DwarfFile &Holder) {
2057  MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
2058  MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
2059  emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd);
2060 
2061  Asm->OutStreamer->AddComment("Offset entry count");
2062  Asm->emitInt32(Holder.getRangeLists().size());
2063  Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym());
2064 
2065  for (const RangeSpanList &List : Holder.getRangeLists())
2066  Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(),
2067  4);
2068 
2069  return TableEnd;
2070 }
2071 
2072 // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2073 // designates the end of the table for the caller to emit when the table is
2074 // complete.
2076  const DwarfFile &Holder) {
2077  MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start");
2078  MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end");
2079  emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd);
2080 
2081  // FIXME: Generate the offsets table and use DW_FORM_loclistx with the
2082  // DW_AT_loclists_base attribute. Until then set the number of offsets to 0.
2083  Asm->OutStreamer->AddComment("Offset entry count");
2084  Asm->emitInt32(0);
2085  Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym());
2086 
2087  return TableEnd;
2088 }
2089 
2090 // Emit locations into the .debug_loc/.debug_rnglists section.
2091 void DwarfDebug::emitDebugLoc() {
2092  if (DebugLocs.getLists().empty())
2093  return;
2094 
2095  bool IsLocLists = getDwarfVersion() >= 5;
2096  MCSymbol *TableEnd = nullptr;
2097  if (IsLocLists) {
2098  Asm->OutStreamer->SwitchSection(
2100  TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder
2101  : InfoHolder);
2102  } else {
2103  Asm->OutStreamer->SwitchSection(
2105  }
2106 
2107  unsigned char Size = Asm->MAI->getCodePointerSize();
2108  for (const auto &List : DebugLocs.getLists()) {
2109  Asm->OutStreamer->EmitLabel(List.Label);
2110 
2111  const DwarfCompileUnit *CU = List.CU;
2112  const MCSymbol *Base = CU->getBaseAddress();
2113  for (const auto &Entry : DebugLocs.getEntries(List)) {
2114  if (Base) {
2115  // Set up the range. This range is relative to the entry point of the
2116  // compile unit. This is a hard coded 0 for low_pc when we're emitting
2117  // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2118  if (IsLocLists) {
2119  Asm->OutStreamer->AddComment("DW_LLE_offset_pair");
2120  Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1);
2121  Asm->OutStreamer->AddComment(" starting offset");
2122  Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base);
2123  Asm->OutStreamer->AddComment(" ending offset");
2124  Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base);
2125  } else {
2126  Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
2127  Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
2128  }
2129 
2131  continue;
2132  }
2133 
2134  // We have no base address.
2135  if (IsLocLists) {
2136  // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or
2137  // DW_LLE_startx_length in case if there is only a single range.
2138  // That should reduce the size of the debug data emited.
2139  // For now just use the DW_LLE_startx_length for all cases.
2140  Asm->OutStreamer->AddComment("DW_LLE_startx_length");
2142  Asm->OutStreamer->AddComment(" start idx");
2143  Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym));
2144  Asm->OutStreamer->AddComment(" length");
2145  Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym);
2146  } else {
2147  Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
2148  Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
2149  }
2150 
2152  }
2153 
2154  if (IsLocLists) {
2155  // .debug_loclists section ends with DW_LLE_end_of_list.
2156  Asm->OutStreamer->AddComment("DW_LLE_end_of_list");
2157  Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1);
2158  } else {
2159  // Terminate the .debug_loc list with two 0 values.
2160  Asm->OutStreamer->EmitIntValue(0, Size);
2161  Asm->OutStreamer->EmitIntValue(0, Size);
2162  }
2163  }
2164 
2165  if (TableEnd)
2166  Asm->OutStreamer->EmitLabel(TableEnd);
2167 }
2168 
2169 void DwarfDebug::emitDebugLocDWO() {
2170  for (const auto &List : DebugLocs.getLists()) {
2171  Asm->OutStreamer->SwitchSection(
2173  Asm->OutStreamer->EmitLabel(List.Label);
2174  for (const auto &Entry : DebugLocs.getEntries(List)) {
2175  // GDB only supports startx_length in pre-standard split-DWARF.
2176  // (in v5 standard loclists, it currently* /only/ supports base_address +
2177  // offset_pair, so the implementations can't really share much since they
2178  // need to use different representations)
2179  // * as of October 2018, at least
2180  // Ideally/in v5, this could use SectionLabels to reuse existing addresses
2181  // in the address pool to minimize object size/relocations.
2183  unsigned idx = AddrPool.getIndex(Entry.BeginSym);
2184  Asm->EmitULEB128(idx);
2185  Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
2186 
2188  }
2190  }
2191 }
2192 
2193 struct ArangeSpan {
2194  const MCSymbol *Start, *End;
2195 };
2196 
2197 // Emit a debug aranges section, containing a CU lookup for any
2198 // address we can tie back to a CU.
2199 void DwarfDebug::emitDebugARanges() {
2200  // Provides a unique id per text section.
2202 
2203  // Filter labels by section.
2204  for (const SymbolCU &SCU : ArangeLabels) {
2205  if (SCU.Sym->isInSection()) {
2206  // Make a note of this symbol and it's section.
2207  MCSection *Section = &SCU.Sym->getSection();
2208  if (!Section->getKind().isMetadata())
2209  SectionMap[Section].push_back(SCU);
2210  } else {
2211  // Some symbols (e.g. common/bss on mach-o) can have no section but still
2212  // appear in the output. This sucks as we rely on sections to build
2213  // arange spans. We can do it without, but it's icky.
2214  SectionMap[nullptr].push_back(SCU);
2215  }
2216  }
2217 
2219 
2220  for (auto &I : SectionMap) {
2221  MCSection *Section = I.first;
2222  SmallVector<SymbolCU, 8> &List = I.second;
2223  if (List.size() < 1)
2224  continue;
2225 
2226  // If we have no section (e.g. common), just write out
2227  // individual spans for each symbol.
2228  if (!Section) {
2229  for (const SymbolCU &Cur : List) {
2230  ArangeSpan Span;
2231  Span.Start = Cur.Sym;
2232  Span.End = nullptr;
2233  assert(Cur.CU);
2234  Spans[Cur.CU].push_back(Span);
2235  }
2236  continue;
2237  }
2238 
2239  // Sort the symbols by offset within the section.
2240  llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
2241  unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2242  unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
2243 
2244  // Symbols with no order assigned should be placed at the end.
2245  // (e.g. section end labels)
2246  if (IA == 0)
2247  return false;
2248  if (IB == 0)
2249  return true;
2250  return IA < IB;
2251  });
2252 
2253  // Insert a final terminator.
2254  List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2255 
2256  // Build spans between each label.
2257  const MCSymbol *StartSym = List[0].Sym;
2258  for (size_t n = 1, e = List.size(); n < e; n++) {
2259  const SymbolCU &Prev = List[n - 1];
2260  const SymbolCU &Cur = List[n];
2261 
2262  // Try and build the longest span we can within the same CU.
2263  if (Cur.CU != Prev.CU) {
2264  ArangeSpan Span;
2265  Span.Start = StartSym;
2266  Span.End = Cur.Sym;
2267  assert(Prev.CU);
2268  Spans[Prev.CU].push_back(Span);
2269  StartSym = Cur.Sym;
2270  }
2271  }
2272  }
2273 
2274  // Start the dwarf aranges section.
2275  Asm->OutStreamer->SwitchSection(
2277 
2278  unsigned PtrSize = Asm->MAI->getCodePointerSize();
2279 
2280  // Build a list of CUs used.
2281  std::vector<DwarfCompileUnit *> CUs;
2282  for (const auto &it : Spans) {
2283  DwarfCompileUnit *CU = it.first;
2284  CUs.push_back(CU);
2285  }
2286 
2287  // Sort the CU list (again, to ensure consistent output order).
2288  llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2289  return A->getUniqueID() < B->getUniqueID();
2290  });
2291 
2292  // Emit an arange table for each CU we used.
2293  for (DwarfCompileUnit *CU : CUs) {
2294  std::vector<ArangeSpan> &List = Spans[CU];
2295 
2296  // Describe the skeleton CU's offset and length, not the dwo file's.
2297  if (auto *Skel = CU->getSkeleton())
2298  CU = Skel;
2299 
2300  // Emit size of content not including length itself.
2301  unsigned ContentSize =
2302  sizeof(int16_t) + // DWARF ARange version number
2303  sizeof(int32_t) + // Offset of CU in the .debug_info section
2304  sizeof(int8_t) + // Pointer Size (in bytes)
2305  sizeof(int8_t); // Segment Size (in bytes)
2306 
2307  unsigned TupleSize = PtrSize * 2;
2308 
2309  // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2310  unsigned Padding =
2311  OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2312 
2313  ContentSize += Padding;
2314  ContentSize += (List.size() + 1) * TupleSize;
2315 
2316  // For each compile unit, write the list of spans it covers.
2317  Asm->OutStreamer->AddComment("Length of ARange Set");
2318  Asm->emitInt32(ContentSize);
2319  Asm->OutStreamer->AddComment("DWARF Arange version number");
2321  Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2322  emitSectionReference(*CU);
2323  Asm->OutStreamer->AddComment("Address Size (in bytes)");
2324  Asm->emitInt8(PtrSize);
2325  Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2326  Asm->emitInt8(0);
2327 
2328  Asm->OutStreamer->emitFill(Padding, 0xff);
2329 
2330  for (const ArangeSpan &Span : List) {
2331  Asm->EmitLabelReference(Span.Start, PtrSize);
2332 
2333  // Calculate the size as being from the span start to it's end.
2334  if (Span.End) {
2335  Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2336  } else {
2337  // For symbols without an end marker (e.g. common), we
2338  // write a single arange entry containing just that one symbol.
2339  uint64_t Size = SymSize[Span.Start];
2340  if (Size == 0)
2341  Size = 1;
2342 
2343  Asm->OutStreamer->EmitIntValue(Size, PtrSize);
2344  }
2345  }
2346 
2347  Asm->OutStreamer->AddComment("ARange terminator");
2348  Asm->OutStreamer->EmitIntValue(0, PtrSize);
2349  Asm->OutStreamer->EmitIntValue(0, PtrSize);
2350  }
2351 }
2352 
2353 /// Emit a single range list. We handle both DWARF v5 and earlier.
2355  const RangeSpanList &List) {
2356 
2357  auto DwarfVersion = DD.getDwarfVersion();
2358  // Emit our symbol so we can find the beginning of the range.
2359  Asm->OutStreamer->EmitLabel(List.getSym());
2360  // Gather all the ranges that apply to the same section so they can share
2361  // a base address entry.
2363  // Size for our labels.
2364  auto Size = Asm->MAI->getCodePointerSize();
2365 
2366  for (const RangeSpan &Range : List.getRanges())
2367  SectionRanges[&Range.getStart()->getSection()].push_back(&Range);
2368 
2369  const DwarfCompileUnit &CU = List.getCU();
2370  const MCSymbol *CUBase = CU.getBaseAddress();
2371  bool BaseIsSet = false;
2372  for (const auto &P : SectionRanges) {
2373  // Don't bother with a base address entry if there's only one range in
2374  // this section in this range list - for example ranges for a CU will
2375  // usually consist of single regions from each of many sections
2376  // (-ffunction-sections, or just C++ inline functions) except under LTO
2377  // or optnone where there may be holes in a single CU's section
2378  // contributions.
2379  auto *Base = CUBase;
2380  if (!Base && (P.second.size() > 1 || DwarfVersion < 5) &&
2381  (CU.getCUNode()->getRangesBaseAddress() || DwarfVersion >= 5)) {
2382  BaseIsSet = true;
2383  // FIXME/use care: This may not be a useful base address if it's not
2384  // the lowest address/range in this object.
2385  Base = P.second.front()->getStart();
2386  if (DwarfVersion >= 5) {
2387  Base = DD.getSectionLabel(&Base->getSection());
2388  Asm->OutStreamer->AddComment("DW_RLE_base_addressx");
2389  Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1);
2390  Asm->OutStreamer->AddComment(" base address index");
2392  } else {
2393  Asm->OutStreamer->EmitIntValue(-1, Size);
2394  Asm->OutStreamer->AddComment(" base address");
2395  Asm->OutStreamer->EmitSymbolValue(Base, Size);
2396  }
2397  } else if (BaseIsSet && DwarfVersion < 5) {
2398  BaseIsSet = false;
2399  assert(!Base);
2400  Asm->OutStreamer->EmitIntValue(-1, Size);
2401  Asm->OutStreamer->EmitIntValue(0, Size);
2402  }
2403 
2404  for (const auto *RS : P.second) {
2405  const MCSymbol *Begin = RS->getStart();
2406  const MCSymbol *End = RS->getEnd();
2407  assert(Begin && "Range without a begin symbol?");
2408  assert(End && "Range without an end symbol?");
2409  if (Base) {
2410  if (DwarfVersion >= 5) {
2411  // Emit DW_RLE_offset_pair when we have a base.
2412  Asm->OutStreamer->AddComment("DW_RLE_offset_pair");
2413  Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1);
2414  Asm->OutStreamer->AddComment(" starting offset");
2415  Asm->EmitLabelDifferenceAsULEB128(Begin, Base);
2416  Asm->OutStreamer->AddComment(" ending offset");
2418  } else {
2419  Asm->EmitLabelDifference(Begin, Base, Size);
2420  Asm->EmitLabelDifference(End, Base, Size);
2421  }
2422  } else if (DwarfVersion >= 5) {
2423  Asm->OutStreamer->AddComment("DW_RLE_startx_length");
2424  Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1);
2425  Asm->OutStreamer->AddComment(" start index");
2426  Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin));
2427  Asm->OutStreamer->AddComment(" length");
2428  Asm->EmitLabelDifferenceAsULEB128(End, Begin);
2429  } else {
2430  Asm->OutStreamer->EmitSymbolValue(Begin, Size);
2431  Asm->OutStreamer->EmitSymbolValue(End, Size);
2432  }
2433  }
2434  }
2435  if (DwarfVersion >= 5) {
2436  Asm->OutStreamer->AddComment("DW_RLE_end_of_list");
2437  Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1);
2438  } else {
2439  // Terminate the list with two 0 values.
2440  Asm->OutStreamer->EmitIntValue(0, Size);
2441  Asm->OutStreamer->EmitIntValue(0, Size);
2442  }
2443 }
2444 
2446  const DwarfFile &Holder, MCSymbol *TableEnd) {
2447  for (const RangeSpanList &List : Holder.getRangeLists())
2448  emitRangeList(DD, Asm, List);
2449 
2450  if (TableEnd)
2451  Asm->OutStreamer->EmitLabel(TableEnd);
2452 }
2453 
2454 /// Emit address ranges into the .debug_ranges section or into the DWARF v5
2455 /// .debug_rnglists section.
2456 void DwarfDebug::emitDebugRanges() {
2457  if (CUMap.empty())
2458  return;
2459 
2460  const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2461 
2462  if (Holder.getRangeLists().empty())
2463  return;
2464 
2466  assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2467  return Pair.second->getCUNode()->isDebugDirectivesOnly();
2468  }));
2469 
2470  // Start the dwarf ranges section.
2471  MCSymbol *TableEnd = nullptr;
2472  if (getDwarfVersion() >= 5) {
2473  Asm->OutStreamer->SwitchSection(
2475  TableEnd = emitRnglistsTableHeader(Asm, Holder);
2476  } else
2477  Asm->OutStreamer->SwitchSection(
2479 
2480  emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
2481 }
2482 
2483 void DwarfDebug::emitDebugRangesDWO() {
2484  assert(useSplitDwarf());
2485 
2486  if (CUMap.empty())
2487  return;
2488 
2489  const auto &Holder = InfoHolder;
2490 
2491  if (Holder.getRangeLists().empty())
2492  return;
2493 
2494  assert(getDwarfVersion() >= 5);
2496  assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2497  return Pair.second->getCUNode()->isDebugDirectivesOnly();
2498  }));
2499 
2500  // Start the dwarf ranges section.
2501  Asm->OutStreamer->SwitchSection(
2503  MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder);
2504 
2505  emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
2506 }
2507 
2508 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
2509  for (auto *MN : Nodes) {
2510  if (auto *M = dyn_cast<DIMacro>(MN))
2511  emitMacro(*M);
2512  else if (auto *F = dyn_cast<DIMacroFile>(MN))
2513  emitMacroFile(*F, U);
2514  else
2515  llvm_unreachable("Unexpected DI type!");
2516  }
2517 }
2518 
2519 void DwarfDebug::emitMacro(DIMacro &M) {
2521  Asm->EmitULEB128(M.getLine());
2522  StringRef Name = M.getName();
2523  StringRef Value = M.getValue();
2524  Asm->OutStreamer->EmitBytes(Name);
2525  if (!Value.empty()) {
2526  // There should be one space between macro name and macro value.
2527  Asm->emitInt8(' ');
2528  Asm->OutStreamer->EmitBytes(Value);
2529  }
2530  Asm->emitInt8('\0');
2531 }
2532 
2533 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
2536  Asm->EmitULEB128(F.getLine());
2538  handleMacroNodes(F.getElements(), U);
2540 }
2541 
2542 /// Emit macros into a debug macinfo section.
2543 void DwarfDebug::emitDebugMacinfo() {
2544  if (CUMap.empty())
2545  return;
2546 
2547  if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2548  return Pair.second->getCUNode()->isDebugDirectivesOnly();
2549  }))
2550  return;
2551 
2552  // Start the dwarf macinfo section.
2553  Asm->OutStreamer->SwitchSection(
2555 
2556  for (const auto &P : CUMap) {
2557  auto &TheCU = *P.second;
2558  if (TheCU.getCUNode()->isDebugDirectivesOnly())
2559  continue;
2560  auto *SkCU = TheCU.getSkeleton();
2561  DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2562  auto *CUNode = cast<DICompileUnit>(P.first);
2563  DIMacroNodeArray Macros = CUNode->getMacros();
2564  if (!Macros.empty()) {
2565  Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2566  handleMacroNodes(Macros, U);
2567  }
2568  }
2569  Asm->OutStreamer->AddComment("End Of Macro List Mark");
2570  Asm->emitInt8(0);
2571 }
2572 
2573 // DWARF5 Experimental Separate Dwarf emitters.
2574 
2575 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2576  std::unique_ptr<DwarfCompileUnit> NewU) {
2577 
2578  if (!CompilationDir.empty())
2579  NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2580 
2581  addGnuPubAttributes(*NewU, Die);
2582 
2583  SkeletonHolder.addUnit(std::move(NewU));
2584 }
2585 
2586 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2587 
2588  auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
2589  CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2590  DwarfCompileUnit &NewCU = *OwnedUnit;
2592 
2593  NewCU.initStmtList();
2594 
2596  NewCU.addStringOffsetsStart();
2597 
2598  initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2599 
2600  return NewCU;
2601 }
2602 
2603 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2604 // compile units that would normally be in debug_info.
2605 void DwarfDebug::emitDebugInfoDWO() {
2606  assert(useSplitDwarf() && "No split dwarf debug info?");
2607  // Don't emit relocations into the dwo file.
2608  InfoHolder.emitUnits(/* UseOffsets */ true);
2609 }
2610 
2611 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2612 // abbreviations for the .debug_info.dwo section.
2613 void DwarfDebug::emitDebugAbbrevDWO() {
2614  assert(useSplitDwarf() && "No split dwarf?");
2615  InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2616 }
2617 
2618 void DwarfDebug::emitDebugLineDWO() {
2619  assert(useSplitDwarf() && "No split dwarf?");
2620  SplitTypeUnitFileTable.Emit(
2623 }
2624 
2625 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2626  assert(useSplitDwarf() && "No split dwarf?");
2627  InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2629  InfoHolder.getStringOffsetsStartSym());
2630 }
2631 
2632 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2633 // string section and is identical in format to traditional .debug_str
2634 // sections.
2635 void DwarfDebug::emitDebugStrDWO() {
2637  emitStringOffsetsTableHeaderDWO();
2638  assert(useSplitDwarf() && "No split dwarf?");
2640  InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2641  OffSec, /* UseRelativeOffsets = */ false);
2642 }
2643 
2644 // Emit address pool.
2645 void DwarfDebug::emitDebugAddr() {
2646  AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2647 }
2648 
2649 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2650  if (!useSplitDwarf())
2651  return nullptr;
2652  const DICompileUnit *DIUnit = CU.getCUNode();
2653  SplitTypeUnitFileTable.maybeSetRootFile(
2654  DIUnit->getDirectory(), DIUnit->getFilename(),
2655  CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
2656  return &SplitTypeUnitFileTable;
2657 }
2658 
2660  MD5 Hash;
2661  Hash.update(Identifier);
2662  // ... take the least significant 8 bytes and return those. Our MD5
2663  // implementation always returns its results in little endian, so we actually
2664  // need the "high" word.
2665  MD5::MD5Result Result;
2666  Hash.final(Result);
2667  return Result.high();
2668 }
2669 
2671  StringRef Identifier, DIE &RefDie,
2672  const DICompositeType *CTy) {
2673  // Fast path if we're building some type units and one has already used the
2674  // address pool we know we're going to throw away all this work anyway, so
2675  // don't bother building dependent types.
2676  if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2677  return;
2678 
2679  auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2680  if (!Ins.second) {
2681  CU.addDIETypeSignature(RefDie, Ins.first->second);
2682  return;
2683  }
2684 
2685  bool TopLevelType = TypeUnitsUnderConstruction.empty();
2686  AddrPool.resetUsedFlag();
2687 
2688  auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2689  getDwoLineTable(CU));
2690  DwarfTypeUnit &NewTU = *OwnedUnit;
2691  DIE &UnitDie = NewTU.getUnitDie();
2692  TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2693 
2694  NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2695  CU.getLanguage());
2696 
2697  uint64_t Signature = makeTypeSignature(Identifier);
2698  NewTU.setTypeSignature(Signature);
2699  Ins.first->second = Signature;
2700 
2701  if (useSplitDwarf()) {
2702  MCSection *Section =
2703  getDwarfVersion() <= 4
2704  ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
2705  : Asm->getObjFileLowering().getDwarfInfoDWOSection();
2706  NewTU.setSection(Section);
2707  } else {
2708  MCSection *Section =
2709  getDwarfVersion() <= 4
2710  ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
2711  : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
2712  NewTU.setSection(Section);
2713  // Non-split type units reuse the compile unit's line table.
2714  CU.applyStmtList(UnitDie);
2715  }
2716 
2717  // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2718  // units.
2720  NewTU.addStringOffsetsStart();
2721 
2722  NewTU.setType(NewTU.createTypeDIE(CTy));
2723 
2724  if (TopLevelType) {
2725  auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2726  TypeUnitsUnderConstruction.clear();
2727 
2728  // Types referencing entries in the address table cannot be placed in type
2729  // units.
2730  if (AddrPool.hasBeenUsed()) {
2731 
2732  // Remove all the types built while building this type.
2733  // This is pessimistic as some of these types might not be dependent on
2734  // the type that used an address.
2735  for (const auto &TU : TypeUnitsToAdd)
2736  TypeSignatures.erase(TU.second);
2737 
2738  // Construct this type in the CU directly.
2739  // This is inefficient because all the dependent types will be rebuilt
2740  // from scratch, including building them in type units, discovering that
2741  // they depend on addresses, throwing them out and rebuilding them.
2742  CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2743  return;
2744  }
2745 
2746  // If the type wasn't dependent on fission addresses, finish adding the type
2747  // and all its dependent types.
2748  for (auto &TU : TypeUnitsToAdd) {
2749  InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2750  InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2751  }
2752  }
2753  CU.addDIETypeSignature(RefDie, Signature);
2754 }
2755 
2756 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD)
2757  : DD(DD),
2758  TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) {
2759  DD->TypeUnitsUnderConstruction.clear();
2760  assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed());
2761 }
2762 
2764  DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction);
2765  DD->AddrPool.resetUsedFlag();
2766 }
2767 
2769  return NonTypeUnitContext(this);
2770 }
2771 
2772 // Add the Name along with its companion DIE to the appropriate accelerator
2773 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
2774 // AccelTableKind::Apple, we use the table we got as an argument). If
2775 // accelerator tables are disabled, this function does nothing.
2776 template <typename DataT>
2777 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
2778  AccelTable<DataT> &AppleAccel, StringRef Name,
2779  const DIE &Die) {
2781  return;
2782 
2785  return;
2786 
2787  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2789 
2790  switch (getAccelTableKind()) {
2791  case AccelTableKind::Apple:
2792  AppleAccel.addName(Ref, Die);
2793  break;
2794  case AccelTableKind::Dwarf:
2795  AccelDebugNames.addName(Ref, Die);
2796  break;
2798  llvm_unreachable("Default should have already been resolved.");
2799  case AccelTableKind::None:
2800  llvm_unreachable("None handled above");
2801  }
2802 }
2803 
2805  const DIE &Die) {
2806  addAccelNameImpl(CU, AccelNames, Name, Die);
2807 }
2808 
2810  const DIE &Die) {
2811  // ObjC names go only into the Apple accelerator tables.
2813  addAccelNameImpl(CU, AccelObjC, Name, Die);
2814 }
2815 
2817  const DIE &Die) {
2818  addAccelNameImpl(CU, AccelNamespace, Name, Die);
2819 }
2820 
2822  const DIE &Die, char Flags) {
2823  addAccelNameImpl(CU, AccelTypes, Name, Die);
2824 }
2825 
2827  return Asm->OutStreamer->getContext().getDwarfVersion();
2828 }
2829 
2831  SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym));
2832 }
2833 
2835  return SectionLabels.find(S)->second;
2836 }
const StringMap< const DIE * > & getGlobalTypes() const
const DICompileUnit * getCUNode() const
Definition: DwarfUnit.h:89
debug_compile_units_iterator debug_compile_units_end() const
Definition: Module.h:773
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
Definition: AsmPrinter.cpp:212
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:38
An object containing the capability of hashing and adding hash attributes onto a DIE.
Definition: DIEHash.h:27
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:645
const DILocalScope * getScopeNode() const
Definition: LexicalScopes.h:63
std::vector< BaseTypeRef > ExprRefedBaseTypes
Builder for DebugLocStream lists.
MCSection * getDwarfStrOffSection() const
void addFlag(DIE &Die, dwarf::Attribute Attribute)
Add a flag that is true to the DIE.
Definition: DwarfUnit.cpp:208
SectionKind getKind() const
Definition: MCSection.h:105
void setLabel(MCSymbol *Sym)
Definition: AddressPool.h:54
static cl::opt< bool > SplitDwarfCrossCuReferences("split-dwarf-cross-cu-references", cl::Hidden, cl::desc("Enable cross-cu references in DWO files"), cl::init(false))
void addUnit(std::unique_ptr< DwarfCompileUnit > U)
Add a unit to the list of CUs.
Definition: DwarfFile.cpp:26
static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU, const DIE *Die)
computeIndexValue - Compute the gdb index value for the DIE and CU.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:218
void emitAppleAccelTable(AsmPrinter *Asm, AccelTable< DataT > &Contents, StringRef Prefix, const MCSymbol *SecBegin)
Emit an Apple Accelerator Table consisting of entries in the specified AccelTable.
Definition: AccelTable.h:304
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:632
void addMMIEntry(const DbgVariable &V)
Definition: DwarfDebug.cpp:265
static cl::opt< bool > DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, cl::desc("Disable debug info printing"))
MCSection * getDwarfAccelObjCSection() const
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:84
MCSection * getDwarfStrSection() const
MCTargetOptions MCOptions
Machine level options.
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
static SmallVectorImpl< DwarfCompileUnit::GlobalExpr > & sortGlobalExprs(SmallVectorImpl< DwarfCompileUnit::GlobalExpr > &GVEs)
Sort and unique GVEs by comparing their fragment offset.
Definition: DwarfDebug.cpp:687
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool isAbstractScope() const
Definition: LexicalScopes.h:64
void addUnsignedConstant(uint64_t Value)
Emit an unsigned constant.
void setRnglistsTableBaseSym(MCSymbol *Sym)
Definition: DwarfFile.h:168
unsigned getRuntimeVersion() const
MCSection * getDwarfLocSection() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
NonTypeUnitContext enterNonTypeUnitContext()
void setMemoryLocationKind()
Lock this down to become a memory location description.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:615
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
const SmallVectorImpl< RangeSpanList > & getRangeLists() const
getRangeLists - Get the vector of range lists.
Definition: DwarfFile.h:127
DWARF v5 .debug_names.
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:256
Implements a dense probed hash-table based set.
Definition: DenseSet.h:249
const DIType * getType() const
Definition: DwarfDebug.cpp:202
AccelTableKind getAccelTableKind() const
Returns what kind (if any) of accelerator tables to emit.
Definition: DwarfDebug.h:653
DIFile * getFile() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:382
std::string SplitDwarfFile
uint16_t getDwarfVersion() const
unsigned getReg() const
unsigned getReg() const
getReg - Returns the register number.
child_range children()
Definition: DIE.h:748
Collects and handles dwarf debug information.
Definition: DwarfDebug.h:270
MCSection * getDwarfAccelNamesSection() const
This class holds an abstract representation of an Accelerator Table, consisting of a sequence of buck...
Definition: AccelTable.h:198
bool hasDelaySlot(QueryType Type=AnyInBundle) const
Returns true if the specified instruction has a delay slot which must be filled by the code generator...
Definition: MachineInstr.h:740
static cl::opt< AccelTableKind > AccelTables("accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."), cl::values(clEnumValN(AccelTableKind::Default, "Default", "Default for platform"), clEnumValN(AccelTableKind::None, "Disable", "Disabled."), clEnumValN(AccelTableKind::Apple, "Apple", "Apple"), clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")), cl::init(AccelTableKind::Default))
Base class containing the logic for constructing DWARF expressions independently of whether they are ...
SmallVectorImpl< InsnRange > & getRanges()
Definition: LexicalScopes.h:66
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.
unsigned getDebugSectionOffset() const
Definition: DIE.h:874
static cl::opt< bool > NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden, cl::desc("Disable emission .debug_ranges section."), cl::init(false))
This class is defined as the common parent of DbgVariable and DbgLabel such that it could levarage po...
Definition: DwarfDebug.h:67
void emitDwarfSymbolReference(const MCSymbol *Label, bool ForceOffset=false) const
Emit a reference to a symbol for use in dwarf.
This class implements a map that also provides access to all stored values in a deterministic order...
Definition: MapVector.h:37
unsigned getLine() const
Definition: DebugLoc.cpp:25
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:1185
void addName(DwarfStringPoolEntryRef Name, Types &&... Args)
Definition: AccelTable.h:208
static const char *const DbgTimerName
Definition: DwarfDebug.cpp:164
DebugLoc emitInitialLocDirective(const MachineFunction &MF, unsigned CUID)
Emits inital debug location directive.
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:33
Metadata node.
Definition: Metadata.h:863
F(f)
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:96
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...
LexicalScope - This class is used to track scope information.
Definition: LexicalScopes.h:44
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
const MachineInstr * CurMI
If nonnull, stores the current machine instruction we&#39;re processing.
MCSection * getDwarfRnglistsDWOSection() const
VariableDbgInfoMapTy & getVariableDbgInfo()
static void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder, MCSymbol *TableStart, MCSymbol *TableEnd)
Tagged DWARF-like metadata node.
DebuggerKind
Identify a debugger for "tuning" the debug info.
Definition: TargetOptions.h:91
bool useSplitDwarf() const
Returns whether or not to change the current debug info for the split dwarf proposal support...
Definition: DwarfDebug.h:661
void initializeDbgValue(const MachineInstr *DbgValue)
Initialize from a DBG_VALUE instruction.
Definition: DwarfDebug.h:147
static const char *const DbgTimerDescription
Definition: DwarfDebug.cpp:165
static cl::opt< bool > GenerateARangeSection("generate-arange-section", cl::Hidden, cl::desc("Generate dwarf aranges"), cl::init(false))
DbgEntity * getExistingAbstractEntity(const DINode *Node)
MCSection * getDwarfRnglistsSection() const
MCSection * getDwarfPubNamesSection() const
DIScope * getScope() const
MCSymbol * getRnglistsTableBaseSym() const
Definition: DwarfFile.h:167
DebugLoc PrevInstLoc
Previous instruction&#39;s location information.
DbgLabelInstrMap DbgLabels
Mapping of inlined labels and DBG_LABEL machine instruction.
StringRef getSplitDebugFilename() const
#define DWARF2_FLAG_IS_STMT
Definition: MCDwarf.h:82
static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, const DebugLocEntry::Value &Value, DwarfExpression &DwarfExpr)
StringRef getFlags() const
MCSection * getDwarfMacinfoSection() const
MCSymbol * getLoclistsTableBaseSym() const
Definition: DwarfFile.h:170
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:80
bool isDebugDirectivesOnly() const
const HexagonInstrInfo * TII
const MCExpr * getFunctionLocalOffsetAfterInsn(const MachineInstr *MI)
Return the function-local offset of an instruction.
DbgValueHistoryMap DbgValues
History of DBG_VALUE and clobber instructions for each user variable.
unsigned getTag() const
const ConstantFP * getFPImm() const
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:411
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
static void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm, const DwarfFile &Holder, MCSymbol *TableEnd)
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:203
MachineBasicBlock iterator that automatically skips over MIs that are inside bundles (i...
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
void addSubprogramNames(const DICompileUnit &CU, const DISubprogram *SP, DIE &Die)
Definition: DwarfDebug.cpp:430
The access may reference the value stored in memory.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1199
static StringRef getName(Value *V)
bool getRangesBaseAddress() const
LLVM_NODISCARD StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition: StringRef.h:679
bool isLexicalScopeDIENull(LexicalScope *Scope)
A helper function to check whether the DIE for a given Scope is going to be null. ...
Definition: DwarfDebug.cpp:464
void constructContainingTypeDIEs()
Construct DIEs for types that contain vtables.
Definition: DwarfUnit.cpp:1407
void setDWOId(uint64_t DwoId)
virtual void EmitInt8(uint8_t Byte, const Twine &Comment="")=0
void addAccelName(const DICompileUnit &CU, StringRef Name, const DIE &Die)
DenseMap< LexicalScope *, ScopeVars > & getScopeVariables()
Definition: DwarfFile.h:178
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
AccelTableKind
The kind of accelerator tables we should emit.
Definition: DwarfDebug.h:262
#define clEnumVal(ENUMVAL, DESC)
Definition: CommandLine.h:625
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
StringRef getFilename() const
DwarfExpression implementation for .debug_loc entries.
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:851
This file implements a class to represent arbitrary precision integral constant values and operations...
DIE * getOrCreateTypeDIE(const MDNode *TyNode)
Find existing DIE or create new DIE for the given type.
Definition: DwarfUnit.cpp:661
void createAbstractEntity(const DINode *Node, LexicalScope *Scope)
static Optional< DebugNameTableKind > getNameTableKind(StringRef Str)
void addString(DIE &Die, dwarf::Attribute Attribute, StringRef Str)
Add a string attribute data and value.
Definition: DwarfUnit.cpp:243
const SmallVectorImpl< RangeSpan > & getRanges() const
Definition: DwarfFile.h:60
AddressPool & getAddressPool()
Definition: DwarfDebug.h:698
Subprogram description.
Describes an entry of the various gnu_pub* debug sections.
Definition: Dwarf.h:561
unsigned getUniqueID() const
~DwarfDebug() override
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:208
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...
DenseMap< const MDNode *, DIE * > & getAbstractSPDies()
Definition: DwarfFile.h:186
This class is used to track local variable information.
Definition: DwarfDebug.h:116
static MCSymbol * emitRnglistsTableHeader(AsmPrinter *Asm, const DwarfFile &Holder)
#define T
const DILocalVariable * getVariable() const
Definition: DwarfDebug.h:162
static AccelTableKind computeAccelTableKind(unsigned DwarfVersion, bool GenerateTypeUnits, DebuggerKind Tuning, const Triple &TT)
Definition: DwarfDebug.cpp:299
DIMacroNodeArray getElements() const
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
bool isLittleEndian() const
Layout endianness...
Definition: DataLayout.h:232
.apple_names, .apple_namespaces, .apple_types, .apple_objc.
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:768
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:119
virtual const TargetInstrInfo * getInstrInfo() const
static cl::opt< DefaultOnOff > DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden, cl::desc("Use inlined strings rather than string section."), cl::values(clEnumVal(Default, "Default for platform"), clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), cl::init(Default))
MCSection * getDwarfAccelTypesSection() const
Debug location.
DIE & addChild(DIE *Child)
Add a child to the DIE.
Definition: DIE.h:807
static cl::opt< bool > GenerateDwarfTypeUnits("generate-type-units", cl::Hidden, cl::desc("Generate DWARF4 type units."), cl::init(false))
void EmitLabelDifferenceAsULEB128(const MCSymbol *Hi, const MCSymbol *Lo) const
Emit something like ".uleb128 Hi-Lo".
static cl::opt< bool > UseDwarfRangesBaseAddressSpecifier("use-dwarf-ranges-base-address-specifier", cl::Hidden, cl::desc("Use base address specifiers in debug_ranges"), cl::init(false))
MCSection * getDwarfAbbrevSection() const
MCSection * getDwarfAbbrevDWOSection() const
TargetInstrInfo - Interface to description of machine instruction set.
LexicalScope * findAbstractScope(const DILocalScope *N)
findAbstractScope - Find an abstract scope or return null.
static void forBothCUs(DwarfCompileUnit &CU, Func F)
Definition: DwarfDebug.cpp:481
MCSymbol * getStringOffsetsStartSym() const
Definition: DwarfFile.h:164
MCSection * getDwarfGnuPubTypesSection() const
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:40
#define P(N)
DwarfStringPool & getStringPool()
Returns the string pool.
Definition: DwarfFile.h:162
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
StringRef GDBIndexEntryKindString(GDBIndexEntryKind Kind)
Definition: Dwarf.cpp:542
void endModule() override
Emit all Dwarf sections that should come after the content.
Definition: DwarfDebug.cpp:951
DwarfCompileUnit * CU
Definition: DwarfDebug.h:258
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
MCSymbol * getSym() const
Definition: DwarfFile.h:58
bool tuneForLLDB() const
Definition: DwarfDebug.h:727
const MachineBasicBlock * PrevInstBB
LinkageNameOption
Definition: DwarfDebug.cpp:146
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:84
static void getObjCClassCategory(StringRef In, StringRef &Class, StringRef &Category)
Definition: DwarfDebug.cpp:413
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:1504
void EmitULEB128(uint64_t Value, const char *Desc=nullptr, unsigned PadTo=0) const
Emit the specified unsigned leb128 value.
const DILocation * getInlinedAt() const
Definition: LexicalScopes.h:62
static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:652
const DIExpression * getExpression() const
Definition: DebugLocEntry.h:76
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const GlobalValue * getGlobal() const
A structured debug information entry.
Definition: DIE.h:700
AsmPrinter * Asm
Target of debug info emission.
DIE & getUnitDie()
Definition: DIE.h:879
ArrayRef< char > getBytes(const Entry &E) const
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:81
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:78
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:285
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.
unsigned getOrCreateSourceID(const DIFile *File) override
Look up the source ID for the given file.
virtual void EmitULEB128(uint64_t DWord, const Twine &Comment="", unsigned PadTo=0)=0
void finishEntityDefinition(const DbgEntity *Entity)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1192
DIImportedEntityArray getImportedEntities() const
Encoding
Size and signedness of expression operations&#39; operands.
MCSection * getDwarfLineDWOSection() const
bool isPS4CPU() const
Tests whether the target is the PS4 CPU.
Definition: Triple.h:640
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:322
void addAccelType(const DICompileUnit &CU, StringRef Name, const DIE &Die, char Flags)
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:499
const Triple & getTargetTriple() const
void computeSizeAndOffsets()
Compute the size and offset of all the DIEs.
Definition: DwarfFile.cpp:60
bool useSegmentedStringOffsetsTable() const
Returns whether to generate a string offsets table with (possibly shared) contributions from each CU ...
Definition: DwarfDebug.h:669
ArrayRef< Entry > getEntries(const List &L) const
StringRef GDBIndexEntryLinkageString(GDBIndexEntryLinkage Linkage)
Definition: Dwarf.cpp:565
bool addScopeVariable(LexicalScope *LS, DbgVariable *Var)
Definition: DwarfFile.cpp:104
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1225
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:625
GDBIndexEntryLinkage Linkage
Definition: Dwarf.h:563
MDNode * getScope() const
Definition: DebugLoc.cpp:35
A pair of GlobalVariable and DIExpression.
void emitDWARF5AccelTable(AsmPrinter *Asm, AccelTable< DWARF5AccelTableData > &Contents, const DwarfDebug &DD, ArrayRef< std::unique_ptr< DwarfCompileUnit >> CUs)
Definition: AccelTable.cpp:551
Helper used to pair up a symbol and its DWARF compile unit.
Definition: DwarfDebug.h:254
void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry, const DwarfCompileUnit *CU)
Emit the location for a debug loc entry, including the size header.
StringRef getDirectory() const
iterator erase(const_iterator CI)
Definition: SmallVector.h:438
bool useAllLinkageNames() const
Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
Definition: DwarfDebug.h:623
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...
size_t size() const
Definition: SmallVector.h:52
const DwarfCompileUnit & getCU() const
Definition: DwarfFile.h:59
unsigned getDwarfVersion() const
Returns the Dwarf Version by checking module flags.
Definition: Module.cpp:461
const DILocation * getInlinedAt() const
Definition: DwarfDebug.h:86
#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:163
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
ArrayRef< FrameIndexExpr > getFrameIndexExprs() const
Get the FI entries, sorted by fragment offset.
Definition: DwarfDebug.cpp:247
An imported module (C++ using directive or similar).
bool useLocSection() const
Returns whether .debug_loc section should be emitted.
Definition: DwarfDebug.h:645
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1115
DIE * constructImportedEntityDIE(const DIImportedEntity *Module)
Construct import_module DIE.
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:209
const APFloat & getValueAPF() const
Definition: Constants.h:302
void addSectionLabel(const MCSymbol *Sym)
A DataExtractor (typically for an in-memory copy of an object-file section) plus a relocation map for...
void addExpression(DIExpressionCursor &&Expr, unsigned FragmentOffsetInBits=0)
Emit all remaining operations in the DIExpressionCursor.
uint16_t getLanguage() const
Definition: DwarfUnit.h:88
bool tuneForGDB() const
Definition: DwarfDebug.h:726
SmallVector< RangeSpan, 2 > takeRanges()
void constructAbstractSubprogramScopeDIE(LexicalScope *Scope)
void addScopeLabel(LexicalScope *LS, DbgLabel *Label)
Definition: DwarfFile.cpp:121
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.
bool useSectionsAsReferences() const
Returns whether to use sections as labels rather than temp symbols.
Definition: DwarfDebug.h:640
DenseMap< LexicalScope *, LabelList > & getScopeLabels()
Definition: DwarfFile.h:182
MCSymbol * getMacroLabelBegin() const
static bool hasObjCCategory(StringRef Name)
Definition: DwarfDebug.cpp:406
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
const StringMap< const DIE * > & getGlobalNames() const
Base class for types.
void addAccelNamespace(const DICompileUnit &CU, StringRef Name, const DIE &Die)
void setDebugInfoAvailability(bool avail)
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
StringRef getName() const
unsigned getLine() const
MCSection * getSection() const
Return the section that this DIEUnit will be emitted into.
Definition: DIE.h:872
DIFile * getFile() const
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
virtual void EmitSLEB128(uint64_t DWord, const Twine &Comment="")=0
Module.h This file contains the declarations for the Module class.
void beginModule()
Emit all Dwarf sections that should come prior to the content.
Definition: DwarfDebug.cpp:715
Optional< MD5::MD5Result > getMD5AsBytes(const DIFile *File) const
If the File has an MD5 checksum, return it as an MD5Result allocated in the MCContext.
Definition: DwarfUnit.cpp:296
MCSymbol * getBeginSymbol()
Definition: MCSection.h:109
bool isMetadata() const
Definition: SectionKind.h:116
void finishSubprogramDefinition(const DISubprogram *SP)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
void emitDebugLocEntry(ByteStreamer &Streamer, const DebugLocStream::Entry &Entry, const DwarfCompileUnit *CU)
Emit an entry for the debug loc section.
MCSection * getDwarfInfoSection() const
bool useAppleExtensionAttributes() const
Definition: DwarfDebug.h:655
void emitInt32(int Value) const
Emit a long directive and value.
MCSection * getDwarfStrOffDWOSection() const
virtual bool isTailCall(const MachineInstr &Inst) const
Determines whether Inst is a tail call instruction.
MCSymbol * getFunctionEnd() const
Definition: AsmPrinter.h:209
int64_t getImm() const
void finalize(const AsmPrinter &AP, DebugLocStream::ListBuilder &List, const DIBasicType *BT, DwarfCompileUnit &TheCU)
Lower this entry into a DWARF expression.
DWARF expression.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
unsigned getSourceLanguage() const
DIType * getType() const
static cl::opt< DefaultOnOff > DwarfSectionsAsReferences("dwarf-sections-as-references", cl::Hidden, cl::desc("Use sections+offset as references rather than labels."), cl::values(clEnumVal(Default, "Default for platform"), clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")), cl::init(Default))
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:219
This file contains constants used for implementing Dwarf debug support.
Class for arbitrary precision integers.
Definition: APInt.h:69
static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm, const RangeSpanList &List)
Emit a single range list. We handle both DWARF v5 and earlier.
ArrayRef< std::string > getComments(const Entry &E) const
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:266
MCSection * getDwarfPubTypesSection() const
bool isBlockByrefStruct() const
DebugLoc PrologEndLoc
This location indicates end of function prologue and beginning of function body.
void setLoclistsTableBaseSym(MCSymbol *Sym)
Definition: DwarfFile.h:171
const SmallVectorImpl< RangeSpan > & getRanges() const
getRanges - Get the list of ranges for this unit.
dwarf::Tag getTag() const
Definition: DIE.h:736
String pool entry reference.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:627
A single location or constant.
Definition: DebugLocEntry.h:32
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:253
void emitStringOffsetsTableHeader(AsmPrinter &Asm, MCSection *OffsetSection, MCSymbol *StartSym)
static constexpr unsigned ULEB128PadSize
Definition: DwarfDebug.cpp:166
DIE * getOrCreateContextDIE(const DIScope *Context)
Get context owner&#39;s DIE.
Definition: DwarfUnit.cpp:600
void requestLabelAfterInsn(const MachineInstr *MI)
Ensure that a label will be emitted after MI.
MCSection * getDwarfStrDWOSection() const
Representation of each machine instruction.
Definition: MachineInstr.h:63
static StringRef getObjCMethodName(StringRef In)
Definition: DwarfDebug.cpp:425
bool getSplitDebugInlining() const
void setSection(MCSection *Section)
Set the section that this DIEUnit will be emitted into.
Definition: DIE.h:860
unsigned getEncoding() const
EntryRef getEntry(AsmPrinter &Asm, StringRef Str)
Get a reference to an entry in the string pool.
void EmitDwarfOffset(const MCSymbol *Label, uint64_t Offset) const
Emit something like ".long Label + Offset".
static const size_t npos
Definition: StringRef.h:50
DIE * getOrCreateGlobalVariableDIE(const DIGlobalVariable *GV, ArrayRef< GlobalExpr > GlobalExprs)
Get or create global variable DIE.
void addAccelObjC(const DICompileUnit &CU, StringRef Name, const DIE &Die)
LexicalScopes - This class provides interface to collect and use lexical scoping information from mac...
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
bool useRangesSection() const
Returns whether ranges section should be emitted.
Definition: DwarfDebug.h:637
bool isBlockByrefVariable() const
Definition: DwarfDebug.cpp:197
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
TargetOptions Options
void endFunctionImpl(const MachineFunction *MF) override
Gather and emit post-function debug information.
const NodeList & List
Definition: RDFGraph.cpp:201
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
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:781
bool shareAcrossDWOCUs() const
Definition: DwarfDebug.cpp:488
MCSection * getDwarfGnuPubNamesSection() const
Definition: MD5.h:41
Optional< StringRef > getSource() const
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:332
Base class for debug information backends.
uint32_t Size
Definition: Profile.cpp:46
static uint64_t makeTypeSignature(StringRef Identifier)
Perform an MD5 checksum of Identifier and return the lower 64 bits.
DIE & constructCallSiteEntryDIE(DIE &ScopeDIE, const DISubprogram &CalleeSP, bool IsTail, const MCExpr *PCOffset)
Construct a call site entry DIE describing a call within Scope to a callee described by CalleeSP...
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
const Module * getModule() const
void emitStrings(MCSection *StrSection, MCSection *OffsetSection=nullptr, bool UseRelativeOffsets=false)
Emit all of the strings to the section given.
Definition: DwarfFile.cpp:99
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:211
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:355
DIEValue findAttribute(dwarf::Attribute Attribute) const
Find a value in the DIE with the attribute given.
Definition: DIE.cpp:221
ArrayRef< LexicalScope * > getAbstractScopesList() const
getAbstractScopesList - Return a reference to list of abstract scopes.
unsigned getCol() const
Definition: DebugLoc.cpp:30
const MCSymbol * End
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
Definition: MCAsmInfo.h:395
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...
DILocalScope * getScope() const
Get the local scope for this label.
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:162
void stable_sort(R &&Range)
Definition: STLExtras.h:1309
const MCSymbol * getSectionLabel(const MCSection *S)
void emitInt8(int Value) const
Emit a byte directive and value.
LLVM Value Representation.
Definition: Value.h:72
void addStringOffsetsStart()
Add the DW_AT_str_offsets_base attribute to the unit DIE.
Definition: DwarfUnit.cpp:1674
friend class NonTypeUnitContext
Definition: DwarfDebug.h:599
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:726
uint16_t getDwarfVersion() const
Returns the Dwarf Version.
void emitAbbrevs(MCSection *)
Emit a set of abbreviations to the specific section.
Definition: DwarfFile.cpp:96
GDBIndexEntryLinkage
Definition: Dwarf.h:407
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:217
const DataLayout & getDataLayout() const
Return information about data layout.
Definition: AsmPrinter.cpp:216
MachineModuleInfo * MMI
Collected machine module information.
void resetUsedFlag()
Definition: AddressPool.h:51
unsigned getOffset() const
Get the compile/type unit relative offset of this DIE.
Definition: DIE.h:738
void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition: MD5.cpp:234
DefaultOnOff
Definition: DwarfDebug.cpp:108
bool isNVPTX() const
Tests whether the target is NVPTX (32- or 64-bit).
Definition: Triple.h:681
iterator_range< global_iterator > globals()
Definition: Module.h:587
IRTranslator LLVM IR MI
MachineLocation getLoc() const
Definition: DebugLocEntry.h:74
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
APInt bitcastToAPInt() const
Definition: APFloat.h:1093
void emitUnits(bool UseOffsets)
Emit all of the units to the section listed with the given abbreviation section.
Definition: DwarfFile.cpp:32
MCSection * getDwarfRangesSection() const
bool tuneForSCE() const
Definition: DwarfDebug.h:728
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: Pass.h:356
uint64_t high() const
Definition: MD5.h:72
static bool isObjCClass(StringRef Name)
Definition: DwarfDebug.cpp:402
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
DILocalScope * getScope() const
Get the local scope for this variable.
Builder for DebugLocStream entries.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
const ConstantInt * getCImm() const
MCSymbol * getLabelBegin() const
Root of the metadata hierarchy.
Definition: Metadata.h:57
MCSymbol * createTempSymbol(const Twine &Name) const
bool addMachineRegExpression(const TargetRegisterInfo &TRI, DIExpressionCursor &Expr, unsigned MachineReg, unsigned FragmentOffsetInBits=0)
Emit a machine register location.
bool getFlag(MIFlag Flag) const
Return whether an MI flag is set.
Definition: MachineInstr.h:294
const ConstantFP * getConstantFP() const
Definition: DebugLocEntry.h:72
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.
void emitInt16(int Value) const
Emit a short directive and value.
StringRef getName() const
MCSection * getDwarfLoclistsSection() const
bool hasBeenUsed() const
Definition: AddressPool.h:49
Basic type, like &#39;int&#39; or &#39;float&#39;.
const MCSymbol * Sym
Definition: DwarfDebug.h:257
static MCSymbol * emitLoclistsTableHeader(AsmPrinter *Asm, const DwarfFile &Holder)
unsigned getIndex(const MCSymbol *Sym, bool TLS=false)
Returns the index into the address pool with the given label/symbol.
Definition: AddressPool.cpp:19