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