1 //===-- llvm/DebugProgramInstruction.h - Stream of debug info ---*- 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 // Data structures for storing variable assignment information in LLVM. In the
10 // dbg.value design, a dbg.value intrinsic specifies the position in a block
11 // a source variable take on an LLVM Value:
12 //
13 //    %foo = add i32 1, %0
14 //    dbg.value(metadata i32 %foo, ...)
15 //    %bar = void call @ext(%foo);
16 //
17 // and all information is stored in the Value / Metadata hierachy defined
18 // elsewhere in LLVM. In the "DbgRecord" design, each instruction /may/ have a
19 // connection with a DPMarker, which identifies a position immediately before
20 // the instruction, and each DPMarker /may/ then have connections to DbgRecords
21 // which record the variable assignment information. To illustrate:
22 //
23 //    %foo = add i32 1, %0
24 //       ; foo->DbgMarker == nullptr
25 //       ;; There are no variable assignments / debug records "in front" of
26 //       ;; the instruction for %foo, therefore it has no DbgMarker.
27 //    %bar = void call @ext(%foo)
28 //       ; bar->DbgMarker = {
29 //       ;   StoredDbgRecords = {
30 //       ;     DPValue(metadata i32 %foo, ...)
31 //       ;   }
32 //       ; }
33 //       ;; There is a debug-info record in front of the %bar instruction,
34 //       ;; thus it points at a DPMarker object. That DPMarker contains a
35 //       ;; DPValue in it's ilist, storing the equivalent information to the
36 //       ;; dbg.value above: the Value, DILocalVariable, etc.
37 //
38 // This structure separates the two concerns of the position of the debug-info
39 // in the function, and the Value that it refers to. It also creates a new
40 // "place" in-between the Value / Metadata hierachy where we can customise
41 // storage and allocation techniques to better suite debug-info workloads.
42 // NB: as of the initial prototype, none of that has actually been attempted
43 // yet.
44 //
45 //===----------------------------------------------------------------------===//
46 
47 #ifndef LLVM_IR_DEBUGPROGRAMINSTRUCTION_H
48 #define LLVM_IR_DEBUGPROGRAMINSTRUCTION_H
49 
50 #include "llvm/ADT/ilist.h"
51 #include "llvm/ADT/ilist_node.h"
52 #include "llvm/ADT/iterator.h"
53 #include "llvm/IR/DebugLoc.h"
54 #include "llvm/IR/Instruction.h"
55 #include "llvm/IR/SymbolTableListTraits.h"
56 #include "llvm/Support/Casting.h"
57 
58 namespace llvm {
59 
60 class Instruction;
61 class BasicBlock;
62 class MDNode;
63 class Module;
64 class DbgVariableIntrinsic;
65 class DbgInfoIntrinsic;
66 class DbgLabelInst;
67 class DIAssignID;
68 class DPMarker;
69 class DPValue;
70 class raw_ostream;
71 
72 /// A typed tracking MDNode reference that does not require a definition for its
73 /// parameter type. Necessary to avoid including DebugInfoMetadata.h, which has
74 /// a significant impact on compile times if included in this file.
75 template <typename T> class DbgRecordParamRef {
76   TrackingMDNodeRef Ref;
77 
78 public:
79 public:
80   DbgRecordParamRef() = default;
81 
82   /// Construct from the templated type.
83   DbgRecordParamRef(const T *Param);
84 
85   /// Construct from an \a MDNode.
86   ///
87   /// Note: if \c Param does not have the template type, a verifier check will
88   /// fail, and accessors will crash.  However, construction from other nodes
89   /// is supported in order to handle forward references when reading textual
90   /// IR.
91   explicit DbgRecordParamRef(const MDNode *Param);
92 
93   /// Get the underlying type.
94   ///
95   /// \pre !*this or \c isa<T>(getAsMDNode()).
96   /// @{
97   T *get() const;
98   operator T *() const { return get(); }
99   T *operator->() const { return get(); }
100   T &operator*() const { return *get(); }
101   /// @}
102 
103   /// Check for null.
104   ///
105   /// Check for null in a way that is safe with broken debug info.
106   explicit operator bool() const { return Ref; }
107 
108   /// Return \c this as a \a MDNode.
getAsMDNode()109   MDNode *getAsMDNode() const { return Ref; }
110 
111   bool operator==(const DbgRecordParamRef &Other) const {
112     return Ref == Other.Ref;
113   }
114   bool operator!=(const DbgRecordParamRef &Other) const {
115     return Ref != Other.Ref;
116   }
117 };
118 
119 /// Base class for non-instruction debug metadata records that have positions
120 /// within IR. Features various methods copied across from the Instruction
121 /// class to aid ease-of-use. DbgRecords should always be linked into a
122 /// DPMarker's StoredDbgRecords list. The marker connects a DbgRecord back to
123 /// it's position in the BasicBlock.
124 ///
125 /// We need a discriminator for dyn/isa casts. In order to avoid paying for a
126 /// vtable for "virtual" functions too, subclasses must add a new discriminator
127 /// value (RecordKind) and cases to a few functions in the base class:
128 ///   deleteRecord
129 ///   clone
130 ///   isIdenticalToWhenDefined
131 ///   both print methods
132 ///   createDebugIntrinsic
133 class DbgRecord : public ilist_node<DbgRecord> {
134 public:
135   /// Marker that this DbgRecord is linked into.
136   DPMarker *Marker = nullptr;
137   /// Subclass discriminator.
138   enum Kind : uint8_t { ValueKind, LabelKind };
139 
140 protected:
141   DebugLoc DbgLoc;
142   Kind RecordKind; ///< Subclass discriminator.
143 
144 public:
DbgRecord(Kind RecordKind,DebugLoc DL)145   DbgRecord(Kind RecordKind, DebugLoc DL)
146       : DbgLoc(DL), RecordKind(RecordKind) {}
147 
148   /// Methods that dispatch to subclass implementations. These need to be
149   /// manually updated when a new subclass is added.
150   ///@{
151   void deleteRecord();
152   DbgRecord *clone() const;
153   void print(raw_ostream &O, bool IsForDebug = false) const;
154   void print(raw_ostream &O, ModuleSlotTracker &MST, bool IsForDebug) const;
155   bool isIdenticalToWhenDefined(const DbgRecord &R) const;
156   /// Convert this DbgRecord back into an appropriate llvm.dbg.* intrinsic.
157   /// \p InsertBefore Optional position to insert this intrinsic.
158   /// \returns A new llvm.dbg.* intrinsic representiung this DbgRecord.
159   DbgInfoIntrinsic *createDebugIntrinsic(Module *M,
160                                          Instruction *InsertBefore) const;
161   ///@}
162 
163   /// Same as isIdenticalToWhenDefined but checks DebugLoc too.
164   bool isEquivalentTo(const DbgRecord &R) const;
165 
getRecordKind()166   Kind getRecordKind() const { return RecordKind; }
167 
setMarker(DPMarker * M)168   void setMarker(DPMarker *M) { Marker = M; }
169 
getMarker()170   DPMarker *getMarker() { return Marker; }
getMarker()171   const DPMarker *getMarker() const { return Marker; }
172 
173   BasicBlock *getBlock();
174   const BasicBlock *getBlock() const;
175 
176   Function *getFunction();
177   const Function *getFunction() const;
178 
179   Module *getModule();
180   const Module *getModule() const;
181 
182   LLVMContext &getContext();
183   const LLVMContext &getContext() const;
184 
185   const Instruction *getInstruction() const;
186   const BasicBlock *getParent() const;
187   BasicBlock *getParent();
188 
189   void removeFromParent();
190   void eraseFromParent();
191 
getNextNode()192   DbgRecord *getNextNode() { return &*std::next(getIterator()); }
getPrevNode()193   DbgRecord *getPrevNode() { return &*std::prev(getIterator()); }
194   void insertBefore(DbgRecord *InsertBefore);
195   void insertAfter(DbgRecord *InsertAfter);
196   void moveBefore(DbgRecord *MoveBefore);
197   void moveAfter(DbgRecord *MoveAfter);
198 
getDebugLoc()199   DebugLoc getDebugLoc() const { return DbgLoc; }
setDebugLoc(DebugLoc Loc)200   void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
201 
202   void dump() const;
203 
204   using self_iterator = simple_ilist<DbgRecord>::iterator;
205   using const_self_iterator = simple_ilist<DbgRecord>::const_iterator;
206 
207 protected:
208   /// Similarly to Value, we avoid paying the cost of a vtable
209   /// by protecting the dtor and having deleteRecord dispatch
210   /// cleanup.
211   /// Use deleteRecord to delete a generic record.
212   ~DbgRecord() = default;
213 };
214 
215 inline raw_ostream &operator<<(raw_ostream &OS, const DbgRecord &R) {
216   R.print(OS);
217   return OS;
218 }
219 
220 /// Records a position in IR for a source label (DILabel). Corresponds to the
221 /// llvm.dbg.label intrinsic.
222 /// FIXME: Rename DbgLabelRecord when DPValue is renamed to DbgVariableRecord.
223 class DPLabel : public DbgRecord {
224   DbgRecordParamRef<DILabel> Label;
225 
226   /// This constructor intentionally left private, so that it is only called via
227   /// "createUnresolvedDPLabel", which clearly expresses that it is for parsing
228   /// only.
229   DPLabel(MDNode *Label, MDNode *DL);
230 
231 public:
232   DPLabel(DILabel *Label, DebugLoc DL);
233 
234   /// For use during parsing; creates a DPLabel from as-of-yet unresolved
235   /// MDNodes. Trying to access the resulting DPLabel's fields before they are
236   /// resolved, or if they resolve to the wrong type, will result in a crash.
237   static DPLabel *createUnresolvedDPLabel(MDNode *Label, MDNode *DL);
238 
239   DPLabel *clone() const;
240   void print(raw_ostream &O, bool IsForDebug = false) const;
241   void print(raw_ostream &ROS, ModuleSlotTracker &MST, bool IsForDebug) const;
242   DbgLabelInst *createDebugIntrinsic(Module *M,
243                                      Instruction *InsertBefore) const;
244 
setLabel(DILabel * NewLabel)245   void setLabel(DILabel *NewLabel) { Label = NewLabel; }
getLabel()246   DILabel *getLabel() const { return Label.get(); }
getRawLabel()247   MDNode *getRawLabel() const { return Label.getAsMDNode(); };
248 
249   /// Support type inquiry through isa, cast, and dyn_cast.
classof(const DbgRecord * E)250   static bool classof(const DbgRecord *E) {
251     return E->getRecordKind() == LabelKind;
252   }
253 };
254 
255 /// Record of a variable value-assignment, aka a non instruction representation
256 /// of the dbg.value intrinsic.
257 ///
258 /// This class inherits from DebugValueUser to allow LLVM's metadata facilities
259 /// to update our references to metadata beneath our feet.
260 class DPValue : public DbgRecord, protected DebugValueUser {
261   friend class DebugValueUser;
262 
263 public:
264   enum class LocationType : uint8_t {
265     Declare,
266     Value,
267     Assign,
268 
269     End, ///< Marks the end of the concrete types.
270     Any, ///< To indicate all LocationTypes in searches.
271   };
272   /// Classification of the debug-info record that this DPValue represents.
273   /// Essentially, "is this a dbg.value or dbg.declare?". dbg.declares are not
274   /// currently supported, but it would be trivial to do so.
275   /// FIXME: We could use spare padding bits from DbgRecord for this.
276   LocationType Type;
277 
278   // NB: there is no explicit "Value" field in this class, it's effectively the
279   // DebugValueUser superclass instead. The referred to Value can either be a
280   // ValueAsMetadata or a DIArgList.
281 
282   DbgRecordParamRef<DILocalVariable> Variable;
283   DbgRecordParamRef<DIExpression> Expression;
284   DbgRecordParamRef<DIExpression> AddressExpression;
285 
286 public:
287   /// Create a new DPValue representing the intrinsic \p DVI, for example the
288   /// assignment represented by a dbg.value.
289   DPValue(const DbgVariableIntrinsic *DVI);
290   DPValue(const DPValue &DPV);
291   /// Directly construct a new DPValue representing a dbg.value intrinsic
292   /// assigning \p Location to the DV / Expr / DI variable.
293   DPValue(Metadata *Location, DILocalVariable *DV, DIExpression *Expr,
294           const DILocation *DI, LocationType Type = LocationType::Value);
295   DPValue(Metadata *Value, DILocalVariable *Variable, DIExpression *Expression,
296           DIAssignID *AssignID, Metadata *Address,
297           DIExpression *AddressExpression, const DILocation *DI);
298 
299 private:
300   /// Private constructor for creating new instances during parsing only. Only
301   /// called through `createUnresolvedDPValue` below, which makes clear that
302   /// this is used for parsing only, and will later return a subclass depending
303   /// on which Type is passed.
304   DPValue(LocationType Type, Metadata *Val, MDNode *Variable,
305           MDNode *Expression, MDNode *AssignID, Metadata *Address,
306           MDNode *AddressExpression, MDNode *DI);
307 
308 public:
309   /// Used to create DPValues during parsing, where some metadata references may
310   /// still be unresolved. Although for some fields a generic `Metadata*`
311   /// argument is accepted for forward type-references, the verifier and
312   /// accessors will reject incorrect types later on. The function is used for
313   /// all types of DPValues for simplicity while parsing, but asserts if any
314   /// necessary fields are empty or unused fields are not empty, i.e. if the
315   /// #dbg_assign fields are used for a non-dbg-assign type.
316   static DPValue *createUnresolvedDPValue(LocationType Type, Metadata *Val,
317                                           MDNode *Variable, MDNode *Expression,
318                                           MDNode *AssignID, Metadata *Address,
319                                           MDNode *AddressExpression,
320                                           MDNode *DI);
321 
322   static DPValue *createDPVAssign(Value *Val, DILocalVariable *Variable,
323                                   DIExpression *Expression,
324                                   DIAssignID *AssignID, Value *Address,
325                                   DIExpression *AddressExpression,
326                                   const DILocation *DI);
327   static DPValue *createLinkedDPVAssign(Instruction *LinkedInstr, Value *Val,
328                                         DILocalVariable *Variable,
329                                         DIExpression *Expression,
330                                         Value *Address,
331                                         DIExpression *AddressExpression,
332                                         const DILocation *DI);
333 
334   static DPValue *createDPValue(Value *Location, DILocalVariable *DV,
335                                 DIExpression *Expr, const DILocation *DI);
336   static DPValue *createDPValue(Value *Location, DILocalVariable *DV,
337                                 DIExpression *Expr, const DILocation *DI,
338                                 DPValue &InsertBefore);
339   static DPValue *createDPVDeclare(Value *Address, DILocalVariable *DV,
340                                    DIExpression *Expr, const DILocation *DI);
341   static DPValue *createDPVDeclare(Value *Address, DILocalVariable *DV,
342                                    DIExpression *Expr, const DILocation *DI,
343                                    DPValue &InsertBefore);
344 
345   /// Iterator for ValueAsMetadata that internally uses direct pointer iteration
346   /// over either a ValueAsMetadata* or a ValueAsMetadata**, dereferencing to the
347   /// ValueAsMetadata .
348   class location_op_iterator
349       : public iterator_facade_base<location_op_iterator,
350                                     std::bidirectional_iterator_tag, Value *> {
351     PointerUnion<ValueAsMetadata *, ValueAsMetadata **> I;
352 
353   public:
location_op_iterator(ValueAsMetadata * SingleIter)354     location_op_iterator(ValueAsMetadata *SingleIter) : I(SingleIter) {}
location_op_iterator(ValueAsMetadata ** MultiIter)355     location_op_iterator(ValueAsMetadata **MultiIter) : I(MultiIter) {}
356 
location_op_iterator(const location_op_iterator & R)357     location_op_iterator(const location_op_iterator &R) : I(R.I) {}
358     location_op_iterator &operator=(const location_op_iterator &R) {
359       I = R.I;
360       return *this;
361     }
362     bool operator==(const location_op_iterator &RHS) const {
363       return I == RHS.I;
364     }
365     const Value *operator*() const {
366       ValueAsMetadata *VAM = I.is<ValueAsMetadata *>()
367                                  ? I.get<ValueAsMetadata *>()
368                                  : *I.get<ValueAsMetadata **>();
369       return VAM->getValue();
370     };
371     Value *operator*() {
372       ValueAsMetadata *VAM = I.is<ValueAsMetadata *>()
373                                  ? I.get<ValueAsMetadata *>()
374                                  : *I.get<ValueAsMetadata **>();
375       return VAM->getValue();
376     }
377     location_op_iterator &operator++() {
378       if (I.is<ValueAsMetadata *>())
379         I = I.get<ValueAsMetadata *>() + 1;
380       else
381         I = I.get<ValueAsMetadata **>() + 1;
382       return *this;
383     }
384     location_op_iterator &operator--() {
385       if (I.is<ValueAsMetadata *>())
386         I = I.get<ValueAsMetadata *>() - 1;
387       else
388         I = I.get<ValueAsMetadata **>() - 1;
389       return *this;
390     }
391   };
392 
isDbgDeclare()393   bool isDbgDeclare() { return Type == LocationType::Declare; }
isDbgValue()394   bool isDbgValue() { return Type == LocationType::Value; }
395 
396   /// Get the locations corresponding to the variable referenced by the debug
397   /// info intrinsic.  Depending on the intrinsic, this could be the
398   /// variable's value or its address.
399   iterator_range<location_op_iterator> location_ops() const;
400 
401   Value *getVariableLocationOp(unsigned OpIdx) const;
402 
403   void replaceVariableLocationOp(Value *OldValue, Value *NewValue,
404                                  bool AllowEmpty = false);
405   void replaceVariableLocationOp(unsigned OpIdx, Value *NewValue);
406   /// Adding a new location operand will always result in this intrinsic using
407   /// an ArgList, and must always be accompanied by a new expression that uses
408   /// the new operand.
409   void addVariableLocationOps(ArrayRef<Value *> NewValues,
410                               DIExpression *NewExpr);
411 
412   unsigned getNumVariableLocationOps() const;
413 
hasArgList()414   bool hasArgList() const { return isa<DIArgList>(getRawLocation()); }
415   /// Returns true if this DPValue has no empty MDNodes in its location list.
hasValidLocation()416   bool hasValidLocation() const { return getVariableLocationOp(0) != nullptr; }
417 
418   /// Does this describe the address of a local variable. True for dbg.addr
419   /// and dbg.declare, but not dbg.value, which describes its value.
isAddressOfVariable()420   bool isAddressOfVariable() const { return Type == LocationType::Declare; }
getType()421   LocationType getType() const { return Type; }
422 
423   void setKillLocation();
424   bool isKillLocation() const;
425 
setVariable(DILocalVariable * NewVar)426   void setVariable(DILocalVariable *NewVar) { Variable = NewVar; }
getVariable()427   DILocalVariable *getVariable() const { return Variable.get(); };
getRawVariable()428   MDNode *getRawVariable() const { return Variable.getAsMDNode(); }
429 
setExpression(DIExpression * NewExpr)430   void setExpression(DIExpression *NewExpr) { Expression = NewExpr; }
getExpression()431   DIExpression *getExpression() const { return Expression.get(); }
getRawExpression()432   MDNode *getRawExpression() const { return Expression.getAsMDNode(); }
433 
434   /// Returns the metadata operand for the first location description. i.e.,
435   /// dbg intrinsic dbg.value,declare operand and dbg.assign 1st location
436   /// operand (the "value componenet"). Note the operand (singular) may be
437   /// a DIArgList which is a list of values.
getRawLocation()438   Metadata *getRawLocation() const { return DebugValues[0]; }
439 
440   Value *getValue(unsigned OpIdx = 0) const {
441     return getVariableLocationOp(OpIdx);
442   }
443 
444   /// Use of this should generally be avoided; instead,
445   /// replaceVariableLocationOp and addVariableLocationOps should be used where
446   /// possible to avoid creating invalid state.
setRawLocation(Metadata * NewLocation)447   void setRawLocation(Metadata *NewLocation) {
448     assert(
449         (isa<ValueAsMetadata>(NewLocation) || isa<DIArgList>(NewLocation) ||
450          isa<MDNode>(NewLocation)) &&
451         "Location for a DPValue must be either ValueAsMetadata or DIArgList");
452     resetDebugValue(0, NewLocation);
453   }
454 
455   /// Get the size (in bits) of the variable, or fragment of the variable that
456   /// is described.
457   std::optional<uint64_t> getFragmentSizeInBits() const;
458 
isEquivalentTo(const DPValue & Other)459   bool isEquivalentTo(const DPValue &Other) const {
460     return DbgLoc == Other.DbgLoc && isIdenticalToWhenDefined(Other);
461   }
462   // Matches the definition of the Instruction version, equivalent to above but
463   // without checking DbgLoc.
isIdenticalToWhenDefined(const DPValue & Other)464   bool isIdenticalToWhenDefined(const DPValue &Other) const {
465     return std::tie(Type, DebugValues, Variable, Expression,
466                     AddressExpression) ==
467            std::tie(Other.Type, Other.DebugValues, Other.Variable,
468                     Other.Expression, Other.AddressExpression);
469   }
470 
471   /// @name DbgAssign Methods
472   /// @{
isDbgAssign()473   bool isDbgAssign() const { return getType() == LocationType::Assign; }
474 
475   Value *getAddress() const;
getRawAddress()476   Metadata *getRawAddress() const {
477     return isDbgAssign() ? DebugValues[1] : DebugValues[0];
478   }
getRawAssignID()479   Metadata *getRawAssignID() const { return DebugValues[2]; }
480   DIAssignID *getAssignID() const;
getAddressExpression()481   DIExpression *getAddressExpression() const { return AddressExpression.get(); }
getRawAddressExpression()482   MDNode *getRawAddressExpression() const {
483     return AddressExpression.getAsMDNode();
484   }
setAddressExpression(DIExpression * NewExpr)485   void setAddressExpression(DIExpression *NewExpr) {
486     AddressExpression = NewExpr;
487   }
488   void setAssignId(DIAssignID *New);
setAddress(Value * V)489   void setAddress(Value *V) { resetDebugValue(1, ValueAsMetadata::get(V)); }
490   /// Kill the address component.
491   void setKillAddress();
492   /// Check whether this kills the address component. This doesn't take into
493   /// account the position of the intrinsic, therefore a returned value of false
494   /// does not guarentee the address is a valid location for the variable at the
495   /// intrinsic's position in IR.
496   bool isKillAddress() const;
497 
498   /// @}
499 
500   DPValue *clone() const;
501   /// Convert this DPValue back into a dbg.value intrinsic.
502   /// \p InsertBefore Optional position to insert this intrinsic.
503   /// \returns A new dbg.value intrinsic representiung this DPValue.
504   DbgVariableIntrinsic *createDebugIntrinsic(Module *M,
505                                              Instruction *InsertBefore) const;
506 
507   /// Handle changes to the location of the Value(s) that we refer to happening
508   /// "under our feet".
509   void handleChangedLocation(Metadata *NewLocation);
510 
511   void print(raw_ostream &O, bool IsForDebug = false) const;
512   void print(raw_ostream &ROS, ModuleSlotTracker &MST, bool IsForDebug) const;
513 
514   /// Filter the DbgRecord range to DPValue types only and downcast.
515   static inline auto
filter(iterator_range<simple_ilist<DbgRecord>::iterator> R)516   filter(iterator_range<simple_ilist<DbgRecord>::iterator> R) {
517     return map_range(
518         make_filter_range(R, [](DbgRecord &E) { return isa<DPValue>(E); }),
519         [](DbgRecord &E) { return std::ref(cast<DPValue>(E)); });
520   }
521 
522   /// Support type inquiry through isa, cast, and dyn_cast.
classof(const DbgRecord * E)523   static bool classof(const DbgRecord *E) {
524     return E->getRecordKind() == ValueKind;
525   }
526 };
527 
528 /// Per-instruction record of debug-info. If an Instruction is the position of
529 /// some debugging information, it points at a DPMarker storing that info. Each
530 /// marker points back at the instruction that owns it. Various utilities are
531 /// provided for manipulating the DbgRecords contained within this marker.
532 ///
533 /// This class has a rough surface area, because it's needed to preserve the
534 /// one arefact that we can't yet eliminate from the intrinsic / dbg.value
535 /// debug-info design: the order of records is significant, and duplicates can
536 /// exist. Thus, if one has a run of debug-info records such as:
537 ///    dbg.value(...
538 ///    %foo = barinst
539 ///    dbg.value(...
540 /// and remove barinst, then the dbg.values must be preserved in the correct
541 /// order. Hence, the use of iterators to select positions to insert things
542 /// into, or the occasional InsertAtHead parameter indicating that new records
543 /// should go at the start of the list.
544 ///
545 /// There are only five or six places in LLVM that truly rely on this ordering,
546 /// which we can improve in the future. Additionally, many improvements in the
547 /// way that debug-info is stored can be achieved in this class, at a future
548 /// date.
549 class DPMarker {
550 public:
DPMarker()551   DPMarker() {}
552   /// Link back to the Instruction that owns this marker. Can be null during
553   /// operations that move a marker from one instruction to another.
554   Instruction *MarkedInstr = nullptr;
555 
556   /// List of DbgRecords, the non-instruction equivalent of llvm.dbg.*
557   /// intrinsics. There is a one-to-one relationship between each debug
558   /// intrinsic in a block and each DbgRecord once the representation has been
559   /// converted, and the ordering is meaningful in the same way.
560   simple_ilist<DbgRecord> StoredDbgRecords;
empty()561   bool empty() const { return StoredDbgRecords.empty(); }
562 
563   const BasicBlock *getParent() const;
564   BasicBlock *getParent();
565 
566   /// Handle the removal of a marker: the position of debug-info has gone away,
567   /// but the stored debug records should not. Drop them onto the next
568   /// instruction, or otherwise work out what to do with them.
569   void removeMarker();
570   void dump() const;
571 
572   void removeFromParent();
573   void eraseFromParent();
574 
575   /// Implement operator<< on DPMarker.
576   void print(raw_ostream &O, bool IsForDebug = false) const;
577   void print(raw_ostream &ROS, ModuleSlotTracker &MST, bool IsForDebug) const;
578 
579   /// Produce a range over all the DbgRecords in this Marker.
580   iterator_range<simple_ilist<DbgRecord>::iterator> getDbgRecordRange();
581   iterator_range<simple_ilist<DbgRecord>::const_iterator>
582   getDbgRecordRange() const;
583   /// Transfer any DbgRecords from \p Src into this DPMarker. If \p InsertAtHead
584   /// is true, place them before existing DbgRecords, otherwise afterwards.
585   void absorbDebugValues(DPMarker &Src, bool InsertAtHead);
586   /// Transfer the DbgRecords in \p Range from \p Src into this DPMarker. If
587   /// \p InsertAtHead is true, place them before existing DbgRecords, otherwise
588   // afterwards.
589   void absorbDebugValues(iterator_range<DbgRecord::self_iterator> Range,
590                          DPMarker &Src, bool InsertAtHead);
591   /// Insert a DbgRecord into this DPMarker, at the end of the list. If
592   /// \p InsertAtHead is true, at the start.
593   void insertDbgRecord(DbgRecord *New, bool InsertAtHead);
594   /// Insert a DbgRecord prior to a DbgRecord contained within this marker.
595   void insertDbgRecord(DbgRecord *New, DbgRecord *InsertBefore);
596   /// Insert a DbgRecord after a DbgRecord contained within this marker.
597   void insertDbgRecordAfter(DbgRecord *New, DbgRecord *InsertAfter);
598   /// Clone all DPMarkers from \p From into this marker. There are numerous
599   /// options to customise the source/destination, due to gnarliness, see class
600   /// comment.
601   /// \p FromHere If non-null, copy from FromHere to the end of From's
602   /// DbgRecords
603   /// \p InsertAtHead Place the cloned DbgRecords at the start of
604   /// StoredDbgRecords
605   /// \returns Range over all the newly cloned DbgRecords
606   iterator_range<simple_ilist<DbgRecord>::iterator>
607   cloneDebugInfoFrom(DPMarker *From,
608                      std::optional<simple_ilist<DbgRecord>::iterator> FromHere,
609                      bool InsertAtHead = false);
610   /// Erase all DbgRecords in this DPMarker.
611   void dropDbgRecords();
612   /// Erase a single DbgRecord from this marker. In an ideal future, we would
613   /// never erase an assignment in this way, but it's the equivalent to
614   /// erasing a debug intrinsic from a block.
615   void dropOneDbgRecord(DbgRecord *DR);
616 
617   /// We generally act like all llvm Instructions have a range of DbgRecords
618   /// attached to them, but in reality sometimes we don't allocate the DPMarker
619   /// to save time and memory, but still have to return ranges of DbgRecords.
620   /// When we need to describe such an unallocated DbgRecord range, use this
621   /// static markers range instead. This will bite us if someone tries to insert
622   /// a DbgRecord in that range, but they should be using the Official (TM) API
623   /// for that.
624   static DPMarker EmptyDPMarker;
625   static iterator_range<simple_ilist<DbgRecord>::iterator>
getEmptyDbgRecordRange()626   getEmptyDbgRecordRange() {
627     return make_range(EmptyDPMarker.StoredDbgRecords.end(),
628                       EmptyDPMarker.StoredDbgRecords.end());
629   }
630 };
631 
632 inline raw_ostream &operator<<(raw_ostream &OS, const DPMarker &Marker) {
633   Marker.print(OS);
634   return OS;
635 }
636 
637 /// Inline helper to return a range of DbgRecords attached to a marker. It needs
638 /// to be inlined as it's frequently called, but also come after the declaration
639 /// of DPMarker. Thus: it's pre-declared by users like Instruction, then an
640 /// inlineable body defined here.
641 inline iterator_range<simple_ilist<DbgRecord>::iterator>
getDbgRecordRange(DPMarker * DbgMarker)642 getDbgRecordRange(DPMarker *DbgMarker) {
643   if (!DbgMarker)
644     return DPMarker::getEmptyDbgRecordRange();
645   return DbgMarker->getDbgRecordRange();
646 }
647 
648 } // namespace llvm
649 
650 #endif // LLVM_IR_DEBUGPROGRAMINSTRUCTION_H
651