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