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