LLVM  9.0.0svn
DebugHandlerBase.cpp
Go to the documentation of this file.
1 //===-- llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp -------*- C++ -*--===//
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 // Common functionality for different debug information format backends.
10 // LLVM currently supports DWARF and CodeView.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "dwarfdebug"
28 
31  const MachineInstr &Instruction) {
32  DbgVariableLocation Location;
33  if (!Instruction.isDebugValue())
34  return None;
35  if (!Instruction.getOperand(0).isReg())
36  return None;
37  Location.Register = Instruction.getOperand(0).getReg();
38  Location.FragmentInfo.reset();
39  // We only handle expressions generated by DIExpression::appendOffset,
40  // which doesn't require a full stack machine.
41  int64_t Offset = 0;
42  const DIExpression *DIExpr = Instruction.getDebugExpression();
43  auto Op = DIExpr->expr_op_begin();
44  while (Op != DIExpr->expr_op_end()) {
45  switch (Op->getOp()) {
46  case dwarf::DW_OP_constu: {
47  int Value = Op->getArg(0);
48  ++Op;
49  if (Op != DIExpr->expr_op_end()) {
50  switch (Op->getOp()) {
51  case dwarf::DW_OP_minus:
52  Offset -= Value;
53  break;
54  case dwarf::DW_OP_plus:
55  Offset += Value;
56  break;
57  default:
58  continue;
59  }
60  }
61  } break;
62  case dwarf::DW_OP_plus_uconst:
63  Offset += Op->getArg(0);
64  break;
66  Location.FragmentInfo = {Op->getArg(1), Op->getArg(0)};
67  break;
68  case dwarf::DW_OP_deref:
69  Location.LoadChain.push_back(Offset);
70  Offset = 0;
71  break;
72  default:
73  return None;
74  }
75  ++Op;
76  }
77 
78  // Do one final implicit DW_OP_deref if this was an indirect DBG_VALUE
79  // instruction.
80  // FIXME: Replace these with DIExpression.
81  if (Instruction.isIndirectDebugValue())
82  Location.LoadChain.push_back(Offset);
83 
84  return Location;
85 }
86 
88 
89 // Each LexicalScope has first instruction and last instruction to mark
90 // beginning and end of a scope respectively. Create an inverse map that list
91 // scopes starts (and ends) with an instruction. One instruction may start (or
92 // end) multiple scopes. Ignore scopes that are not reachable.
96  while (!WorkList.empty()) {
97  LexicalScope *S = WorkList.pop_back_val();
98 
99  const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
100  if (!Children.empty())
101  WorkList.append(Children.begin(), Children.end());
102 
103  if (S->isAbstractScope())
104  continue;
105 
106  for (const InsnRange &R : S->getRanges()) {
107  assert(R.first && "InsnRange does not have first instruction!");
108  assert(R.second && "InsnRange does not have second instruction!");
109  requestLabelBeforeInsn(R.first);
110  requestLabelAfterInsn(R.second);
111  }
112  }
113 }
114 
115 // Return Label preceding the instruction.
117  MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
118  assert(Label && "Didn't insert label before instruction");
119  return Label;
120 }
121 
122 // Return Label immediately following the instruction.
124  return LabelsAfterInsn.lookup(MI);
125 }
126 
127 // Return the function-local offset of an instruction.
128 const MCExpr *
130  MCContext &MC = Asm->OutContext;
131 
132  MCSymbol *Start = Asm->getFunctionBegin();
133  const auto *StartRef = MCSymbolRefExpr::create(Start, MC);
134 
135  MCSymbol *AfterInsn = getLabelAfterInsn(MI);
136  assert(AfterInsn && "Expected label after instruction");
137  const auto *AfterRef = MCSymbolRefExpr::create(AfterInsn, MC);
138 
139  return MCBinaryExpr::createSub(AfterRef, StartRef, MC);
140 }
141 
142 /// If this type is derived from a base type then return base type size.
144  DIType *Ty = TyRef.resolve();
145  assert(Ty);
146  DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty);
147  if (!DDTy)
148  return Ty->getSizeInBits();
149 
150  unsigned Tag = DDTy->getTag();
151 
152  if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
153  Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
154  Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type)
155  return DDTy->getSizeInBits();
156 
157  DIType *BaseType = DDTy->getBaseType().resolve();
158 
159  if (!BaseType)
160  return 0;
161 
162  // If this is a derived type, go ahead and get the base type, unless it's a
163  // reference then it's just the size of the field. Pointer types have no need
164  // of this since they're a different type of qualification on the type.
165  if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
166  BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
167  return Ty->getSizeInBits();
168 
169  return getBaseTypeSize(BaseType);
170 }
171 
172 static bool hasDebugInfo(const MachineModuleInfo *MMI,
173  const MachineFunction *MF) {
174  if (!MMI->hasDebugInfo())
175  return false;
176  auto *SP = MF->getFunction().getSubprogram();
177  if (!SP)
178  return false;
179  assert(SP->getUnit());
180  auto EK = SP->getUnit()->getEmissionKind();
181  if (EK == DICompileUnit::NoDebug)
182  return false;
183  return true;
184 }
185 
187  PrevInstBB = nullptr;
188 
189  if (!Asm || !hasDebugInfo(MMI, MF)) {
191  return;
192  }
193 
194  // Grab the lexical scopes for the function, if we don't have any of those
195  // then we're not going to be able to do anything.
196  LScopes.initialize(*MF);
197  if (LScopes.empty()) {
198  beginFunctionImpl(MF);
199  return;
200  }
201 
202  // Make sure that each lexical scope will have a begin/end label.
204 
205  // Calculate history for local variables.
206  assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
207  assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!");
211 
212  // Request labels for the full history.
213  for (const auto &I : DbgValues) {
214  const auto &Ranges = I.second;
215  if (Ranges.empty())
216  continue;
217 
218  auto IsDescribedByReg = [](const MachineInstr *MI) {
219  return MI->getOperand(0).isReg() && MI->getOperand(0).getReg();
220  };
221 
222  // The first mention of a function argument gets the CurrentFnBegin label,
223  // so arguments are visible when breaking at function entry.
224  //
225  // We do not change the label for values that are described by registers,
226  // as that could place them above their defining instructions. We should
227  // ideally not change the labels for constant debug values either, since
228  // doing that violates the ranges that are calculated in the history map.
229  // However, we currently do not emit debug values for constant arguments
230  // directly at the start of the function, so this code is still useful.
231  const DILocalVariable *DIVar = Ranges.front().first->getDebugVariable();
232  if (DIVar->isParameter() &&
233  getDISubprogram(DIVar->getScope())->describes(&MF->getFunction())) {
234  if (!IsDescribedByReg(Ranges.front().first))
235  LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
236  if (Ranges.front().first->getDebugExpression()->isFragment()) {
237  // Mark all non-overlapping initial fragments.
238  for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
239  const DIExpression *Fragment = I->first->getDebugExpression();
240  if (std::any_of(Ranges.begin(), I,
242  return Fragment->fragmentsOverlap(
243  Pred.first->getDebugExpression());
244  }))
245  break;
246  if (!IsDescribedByReg(I->first))
247  LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
248  }
249  }
250  }
251 
252  for (const auto &Range : Ranges) {
253  requestLabelBeforeInsn(Range.first);
254  if (Range.second)
255  requestLabelAfterInsn(Range.second);
256  }
257  }
258 
259  // Ensure there is a symbol before DBG_LABEL.
260  for (const auto &I : DbgLabels) {
261  const MachineInstr *MI = I.second;
263  }
264 
265  PrevInstLoc = DebugLoc();
267  beginFunctionImpl(MF);
268 }
269 
271  if (!MMI->hasDebugInfo())
272  return;
273 
274  assert(CurMI == nullptr);
275  CurMI = MI;
276 
277  // Insert labels where requested.
279  LabelsBeforeInsn.find(MI);
280 
281  // No label needed.
282  if (I == LabelsBeforeInsn.end())
283  return;
284 
285  // Label already assigned.
286  if (I->second)
287  return;
288 
289  if (!PrevLabel) {
291  Asm->OutStreamer->EmitLabel(PrevLabel);
292  }
293  I->second = PrevLabel;
294 }
295 
297  if (!MMI->hasDebugInfo())
298  return;
299 
300  assert(CurMI != nullptr);
301  // Don't create a new label after DBG_VALUE and other instructions that don't
302  // generate code.
303  if (!CurMI->isMetaInstruction()) {
304  PrevLabel = nullptr;
306  }
307 
309  LabelsAfterInsn.find(CurMI);
310  CurMI = nullptr;
311 
312  // No label needed.
313  if (I == LabelsAfterInsn.end())
314  return;
315 
316  // Label already assigned.
317  if (I->second)
318  return;
319 
320  // We need a label after this instruction.
321  if (!PrevLabel) {
323  Asm->OutStreamer->EmitLabel(PrevLabel);
324  }
325  I->second = PrevLabel;
326 }
327 
329  if (hasDebugInfo(MMI, MF))
330  endFunctionImpl(MF);
331  DbgValues.clear();
332  DbgLabels.clear();
333  LabelsBeforeInsn.clear();
334  LabelsAfterInsn.clear();
335 }
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:93
bool hasDebugInfo() const
Returns true if valid debug info is present.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:319
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool isAbstractScope() const
Definition: LexicalScopes.h:64
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:88
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
void push_back(const T &Elt)
Definition: SmallVector.h:211
unsigned getReg() const
getReg - Returns the register number.
SmallVectorImpl< InsnRange > & getRanges()
Definition: LexicalScopes.h:66
A debug info location.
Definition: DebugLoc.h:33
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:96
bool isMetaInstruction() const
Return true if this instruction doesn&#39;t produce any output in the form of executable instructions...
LexicalScope - This class is used to track scope information.
Definition: LexicalScopes.h:44
const MachineInstr * CurMI
If nonnull, stores the current machine instruction we&#39;re processing.
void calculateDbgEntityHistory(const MachineFunction *MF, const TargetRegisterInfo *TRI, DbgValueHistoryMap &DbgValues, DbgLabelInstrMap &DbgLabels)
DebugLoc PrevInstLoc
Previous instruction&#39;s location information.
DbgLabelInstrMap DbgLabels
Mapping of inlined labels and DBG_LABEL machine instruction.
const MCExpr * getFunctionLocalOffsetAfterInsn(const MachineInstr *MI)
Return the function-local offset of an instruction.
SmallVectorImpl< LexicalScope * > & getChildren()
Definition: LexicalScopes.h:65
DbgValueHistoryMap DbgValues
History of DBG_VALUE and clobber instructions for each user variable.
unsigned getTag() const
expr_op_iterator expr_op_begin() const
Visit the elements via ExprOperand wrappers.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
void beginFunction(const MachineFunction *MF) override
Gather pre-function debug information.
Only used in LLVM metadata.
Definition: Dwarf.h:132
uint64_t getSizeInBits() const
Holds a subclass of DINode.
DISubprogram * getDISubprogram(const MDNode *Scope)
Find subprogram that is enclosing this scope.
Definition: DebugInfo.cpp:43
Context object for machine code objects.
Definition: MCContext.h:62
DebugHandlerBase(AsmPrinter *A)
expr_op_iterator expr_op_end() const
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:542
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:208
void identifyScopeMarkers()
Indentify instructions that are marking the beginning of or ending of a scope.
void initialize(const MachineFunction &)
initialize - Scan machine function and constuct lexical scope nest, resets the instance if necessary...
const MCContext & getContext() const
virtual void endFunctionImpl(const MachineFunction *MF)=0
DenseMap< const MachineInstr *, MCSymbol * > LabelsAfterInsn
Maps instruction with label emitted after instruction.
void requestLabelBeforeInsn(const MachineInstr *MI)
Ensure that a label will be emitted before MI.
void resolve()
Resolve a unique, unresolved node.
Definition: Metadata.cpp:575
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:220
const MachineBasicBlock * PrevInstBB
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1507
AsmPrinter * Asm
Target of debug info emission.
llvm::Optional< llvm::DIExpression::FragmentInfo > FragmentInfo
Present if the location is part of a larger variable.
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:78
DenseMap< const MachineInstr *, MCSymbol * > LabelsBeforeInsn
Maps instruction with label emitted before instruction.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1192
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
void endFunction(const MachineFunction *MF) override
Gather post-function debug information.
MCSymbol * getLabelAfterInsn(const MachineInstr *MI)
Return Label immediately following the instruction.
const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
virtual void skippedNonDebugFunction()
Represents the location at which a variable is stored.
virtual void beginFunctionImpl(const MachineFunction *MF)=0
static Optional< DbgVariableLocation > extractFromMachineInstruction(const MachineInstr &Instruction)
Extract a VariableLocation from a MachineInstr.
Base class for types.
static bool hasDebugInfo(const MachineModuleInfo *MMI, const MachineFunction *MF)
bool isDebugValue() const
Definition: MachineInstr.h:996
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
DWARF expression.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
bool fragmentsOverlap(const DIExpression *Other) const
Check if fragments overlap between this DIExpression and Other.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:387
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:253
void requestLabelAfterInsn(const MachineInstr *MI)
Ensure that a label will be emitted after MI.
Representation of each machine instruction.
Definition: MachineInstr.h:63
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
#define I(x, y, z)
Definition: MD5.cpp:58
std::pair< const MachineInstr *, const MachineInstr * > InstrRange
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:322
void endInstruction() override
Process end of an instruction.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void reset()
Definition: Optional.h:251
MCSymbol * getLabelBeforeInsn(const MachineInstr *MI)
Return Label preceding the instruction.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SmallVector< int64_t, 1 > LoadChain
Chain of offsetted loads necessary to load the value if it lives in memory.
LLVM Value Representation.
Definition: Value.h:72
MachineModuleInfo * MMI
Collected machine module information.
static uint64_t getBaseTypeSize(const DITypeRef TyRef)
If this type is derived from a base type then return base type size.
IRTranslator LLVM IR MI
unsigned Register
Base register.
DILocalScope * getScope() const
Get the local scope for this variable.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
LLVM_DUMP_METHOD void dump() const
bool isIndirectDebugValue() const
A DBG_VALUE is indirect iff the first operand is a register and the second operand is an immediate...
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
InsnRange - This is used to track range of instructions with identical lexical scope.
Definition: LexicalScopes.h:39
bool empty()
empty - Return true if there is any lexical scope information available.
LexicalScope * getCurrentFunctionScope() const
getCurrentFunctionScope - Return lexical scope for the current function.
This class contains meta information specific to a module.