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