Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:59

0001 //===-- llvm/DebugProgramInstruction.h - Stream of debug info ---*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // Data structures for storing variable assignment information in LLVM. In the
0010 // dbg.value design, a dbg.value intrinsic specifies the position in a block
0011 // a source variable take on an LLVM Value:
0012 //
0013 //    %foo = add i32 1, %0
0014 //    dbg.value(metadata i32 %foo, ...)
0015 //    %bar = void call @ext(%foo);
0016 //
0017 // and all information is stored in the Value / Metadata hierachy defined
0018 // elsewhere in LLVM. In the "DbgRecord" design, each instruction /may/ have a
0019 // connection with a DbgMarker, which identifies a position immediately before
0020 // the instruction, and each DbgMarker /may/ then have connections to DbgRecords
0021 // which record the variable assignment information. To illustrate:
0022 //
0023 //    %foo = add i32 1, %0
0024 //       ; foo->DebugMarker == nullptr
0025 //       ;; There are no variable assignments / debug records "in front" of
0026 //       ;; the instruction for %foo, therefore it has no DebugMarker.
0027 //    %bar = void call @ext(%foo)
0028 //       ; bar->DebugMarker = {
0029 //       ;   StoredDbgRecords = {
0030 //       ;     DbgVariableRecord(metadata i32 %foo, ...)
0031 //       ;   }
0032 //       ; }
0033 //       ;; There is a debug-info record in front of the %bar instruction,
0034 //       ;; thus it points at a DbgMarker object. That DbgMarker contains a
0035 //       ;; DbgVariableRecord in its ilist, storing the equivalent information
0036 //       ;; to the dbg.value above: the Value, DILocalVariable, etc.
0037 //
0038 // This structure separates the two concerns of the position of the debug-info
0039 // in the function, and the Value that it refers to. It also creates a new
0040 // "place" in-between the Value / Metadata hierachy where we can customise
0041 // storage and allocation techniques to better suite debug-info workloads.
0042 // NB: as of the initial prototype, none of that has actually been attempted
0043 // yet.
0044 //
0045 //===----------------------------------------------------------------------===//
0046 
0047 #ifndef LLVM_IR_DEBUGPROGRAMINSTRUCTION_H
0048 #define LLVM_IR_DEBUGPROGRAMINSTRUCTION_H
0049 
0050 #include "llvm/ADT/ilist.h"
0051 #include "llvm/ADT/ilist_node.h"
0052 #include "llvm/ADT/iterator.h"
0053 #include "llvm/IR/DbgVariableFragmentInfo.h"
0054 #include "llvm/IR/DebugLoc.h"
0055 #include "llvm/IR/Instruction.h"
0056 #include "llvm/IR/SymbolTableListTraits.h"
0057 #include "llvm/Support/Casting.h"
0058 
0059 namespace llvm {
0060 
0061 class Instruction;
0062 class BasicBlock;
0063 class MDNode;
0064 class Module;
0065 class DbgVariableIntrinsic;
0066 class DbgInfoIntrinsic;
0067 class DbgLabelInst;
0068 class DIAssignID;
0069 class DbgMarker;
0070 class DbgVariableRecord;
0071 class raw_ostream;
0072 
0073 /// A typed tracking MDNode reference that does not require a definition for its
0074 /// parameter type. Necessary to avoid including DebugInfoMetadata.h, which has
0075 /// a significant impact on compile times if included in this file.
0076 template <typename T> class DbgRecordParamRef {
0077   TrackingMDNodeRef Ref;
0078 
0079 public:
0080 public:
0081   DbgRecordParamRef() = default;
0082 
0083   /// Construct from the templated type.
0084   DbgRecordParamRef(const T *Param);
0085 
0086   /// Construct from an \a MDNode.
0087   ///
0088   /// Note: if \c Param does not have the template type, a verifier check will
0089   /// fail, and accessors will crash.  However, construction from other nodes
0090   /// is supported in order to handle forward references when reading textual
0091   /// IR.
0092   explicit DbgRecordParamRef(const MDNode *Param);
0093 
0094   /// Get the underlying type.
0095   ///
0096   /// \pre !*this or \c isa<T>(getAsMDNode()).
0097   /// @{
0098   T *get() const;
0099   operator T *() const { return get(); }
0100   T *operator->() const { return get(); }
0101   T &operator*() const { return *get(); }
0102   /// @}
0103 
0104   /// Check for null.
0105   ///
0106   /// Check for null in a way that is safe with broken debug info.
0107   explicit operator bool() const { return Ref; }
0108 
0109   /// Return \c this as a \a MDNode.
0110   MDNode *getAsMDNode() const { return Ref; }
0111 
0112   bool operator==(const DbgRecordParamRef &Other) const {
0113     return Ref == Other.Ref;
0114   }
0115   bool operator!=(const DbgRecordParamRef &Other) const {
0116     return Ref != Other.Ref;
0117   }
0118 };
0119 
0120 /// Base class for non-instruction debug metadata records that have positions
0121 /// within IR. Features various methods copied across from the Instruction
0122 /// class to aid ease-of-use. DbgRecords should always be linked into a
0123 /// DbgMarker's StoredDbgRecords list. The marker connects a DbgRecord back to
0124 /// its position in the BasicBlock.
0125 ///
0126 /// We need a discriminator for dyn/isa casts. In order to avoid paying for a
0127 /// vtable for "virtual" functions too, subclasses must add a new discriminator
0128 /// value (RecordKind) and cases to a few functions in the base class:
0129 ///   deleteRecord
0130 ///   clone
0131 ///   isIdenticalToWhenDefined
0132 ///   both print methods
0133 ///   createDebugIntrinsic
0134 class DbgRecord : public ilist_node<DbgRecord> {
0135 public:
0136   /// Marker that this DbgRecord is linked into.
0137   DbgMarker *Marker = nullptr;
0138   /// Subclass discriminator.
0139   enum Kind : uint8_t { ValueKind, LabelKind };
0140 
0141 protected:
0142   DebugLoc DbgLoc;
0143   Kind RecordKind; ///< Subclass discriminator.
0144 
0145 public:
0146   DbgRecord(Kind RecordKind, DebugLoc DL)
0147       : DbgLoc(DL), RecordKind(RecordKind) {}
0148 
0149   /// Methods that dispatch to subclass implementations. These need to be
0150   /// manually updated when a new subclass is added.
0151   ///@{
0152   void deleteRecord();
0153   DbgRecord *clone() const;
0154   void print(raw_ostream &O, bool IsForDebug = false) const;
0155   void print(raw_ostream &O, ModuleSlotTracker &MST, bool IsForDebug) const;
0156   bool isIdenticalToWhenDefined(const DbgRecord &R) const;
0157   /// Convert this DbgRecord back into an appropriate llvm.dbg.* intrinsic.
0158   /// \p InsertBefore Optional position to insert this intrinsic.
0159   /// \returns A new llvm.dbg.* intrinsic representiung this DbgRecord.
0160   DbgInfoIntrinsic *createDebugIntrinsic(Module *M,
0161                                          Instruction *InsertBefore) const;
0162   ///@}
0163 
0164   /// Same as isIdenticalToWhenDefined but checks DebugLoc too.
0165   bool isEquivalentTo(const DbgRecord &R) const;
0166 
0167   Kind getRecordKind() const { return RecordKind; }
0168 
0169   void setMarker(DbgMarker *M) { Marker = M; }
0170 
0171   DbgMarker *getMarker() { return Marker; }
0172   const DbgMarker *getMarker() const { return Marker; }
0173 
0174   BasicBlock *getBlock();
0175   const BasicBlock *getBlock() const;
0176 
0177   Function *getFunction();
0178   const Function *getFunction() const;
0179 
0180   Module *getModule();
0181   const Module *getModule() const;
0182 
0183   LLVMContext &getContext();
0184   const LLVMContext &getContext() const;
0185 
0186   const Instruction *getInstruction() const;
0187   const BasicBlock *getParent() const;
0188   BasicBlock *getParent();
0189 
0190   void removeFromParent();
0191   void eraseFromParent();
0192 
0193   DbgRecord *getNextNode() { return &*std::next(getIterator()); }
0194   DbgRecord *getPrevNode() { return &*std::prev(getIterator()); }
0195 
0196   // Some generic lambdas supporting intrinsic-based debug-info mean we need
0197   // to support both iterator and instruction position based insertion.
0198   void insertBefore(DbgRecord *InsertBefore);
0199   void insertAfter(DbgRecord *InsertAfter);
0200   void moveBefore(DbgRecord *MoveBefore);
0201   void moveAfter(DbgRecord *MoveAfter);
0202 
0203   void insertBefore(self_iterator InsertBefore);
0204   void insertAfter(self_iterator InsertAfter);
0205   void moveBefore(self_iterator MoveBefore);
0206   void moveAfter(self_iterator MoveAfter);
0207 
0208   DebugLoc getDebugLoc() const { return DbgLoc; }
0209   void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
0210 
0211   void dump() const;
0212 
0213   using self_iterator = simple_ilist<DbgRecord>::iterator;
0214   using const_self_iterator = simple_ilist<DbgRecord>::const_iterator;
0215 
0216 protected:
0217   /// Similarly to Value, we avoid paying the cost of a vtable
0218   /// by protecting the dtor and having deleteRecord dispatch
0219   /// cleanup.
0220   /// Use deleteRecord to delete a generic record.
0221   ~DbgRecord() = default;
0222 };
0223 
0224 inline raw_ostream &operator<<(raw_ostream &OS, const DbgRecord &R) {
0225   R.print(OS);
0226   return OS;
0227 }
0228 
0229 /// Records a position in IR for a source label (DILabel). Corresponds to the
0230 /// llvm.dbg.label intrinsic.
0231 class DbgLabelRecord : public DbgRecord {
0232   DbgRecordParamRef<DILabel> Label;
0233 
0234   /// This constructor intentionally left private, so that it is only called via
0235   /// "createUnresolvedDbgLabelRecord", which clearly expresses that it is for
0236   /// parsing only.
0237   DbgLabelRecord(MDNode *Label, MDNode *DL);
0238 
0239 public:
0240   DbgLabelRecord(DILabel *Label, DebugLoc DL);
0241 
0242   /// For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved
0243   /// MDNodes. Trying to access the resulting DbgLabelRecord's fields before
0244   /// they are resolved, or if they resolve to the wrong type, will result in a
0245   /// crash.
0246   static DbgLabelRecord *createUnresolvedDbgLabelRecord(MDNode *Label,
0247                                                         MDNode *DL);
0248 
0249   DbgLabelRecord *clone() const;
0250   void print(raw_ostream &O, bool IsForDebug = false) const;
0251   void print(raw_ostream &ROS, ModuleSlotTracker &MST, bool IsForDebug) const;
0252   DbgLabelInst *createDebugIntrinsic(Module *M,
0253                                      Instruction *InsertBefore) const;
0254 
0255   void setLabel(DILabel *NewLabel) { Label = NewLabel; }
0256   DILabel *getLabel() const { return Label.get(); }
0257   MDNode *getRawLabel() const { return Label.getAsMDNode(); };
0258 
0259   /// Support type inquiry through isa, cast, and dyn_cast.
0260   static bool classof(const DbgRecord *E) {
0261     return E->getRecordKind() == LabelKind;
0262   }
0263 };
0264 
0265 /// Record of a variable value-assignment, aka a non instruction representation
0266 /// of the dbg.value intrinsic.
0267 ///
0268 /// This class inherits from DebugValueUser to allow LLVM's metadata facilities
0269 /// to update our references to metadata beneath our feet.
0270 class DbgVariableRecord : public DbgRecord, protected DebugValueUser {
0271   friend class DebugValueUser;
0272 
0273 public:
0274   enum class LocationType : uint8_t {
0275     Declare,
0276     Value,
0277     Assign,
0278 
0279     End, ///< Marks the end of the concrete types.
0280     Any, ///< To indicate all LocationTypes in searches.
0281   };
0282   /// Classification of the debug-info record that this DbgVariableRecord
0283   /// represents. Essentially, "does this correspond to a dbg.value,
0284   /// dbg.declare, or dbg.assign?".
0285   /// FIXME: We could use spare padding bits from DbgRecord for this.
0286   LocationType Type;
0287 
0288   // NB: there is no explicit "Value" field in this class, it's effectively the
0289   // DebugValueUser superclass instead. The referred to Value can either be a
0290   // ValueAsMetadata or a DIArgList.
0291 
0292   DbgRecordParamRef<DILocalVariable> Variable;
0293   DbgRecordParamRef<DIExpression> Expression;
0294   DbgRecordParamRef<DIExpression> AddressExpression;
0295 
0296 public:
0297   /// Create a new DbgVariableRecord representing the intrinsic \p DVI, for
0298   /// example the assignment represented by a dbg.value.
0299   DbgVariableRecord(const DbgVariableIntrinsic *DVI);
0300   DbgVariableRecord(const DbgVariableRecord &DVR);
0301   /// Directly construct a new DbgVariableRecord representing a dbg.value
0302   /// intrinsic assigning \p Location to the DV / Expr / DI variable.
0303   DbgVariableRecord(Metadata *Location, DILocalVariable *DV, DIExpression *Expr,
0304                     const DILocation *DI,
0305                     LocationType Type = LocationType::Value);
0306   DbgVariableRecord(Metadata *Value, DILocalVariable *Variable,
0307                     DIExpression *Expression, DIAssignID *AssignID,
0308                     Metadata *Address, DIExpression *AddressExpression,
0309                     const DILocation *DI);
0310 
0311 private:
0312   /// Private constructor for creating new instances during parsing only. Only
0313   /// called through `createUnresolvedDbgVariableRecord` below, which makes
0314   /// clear that this is used for parsing only, and will later return a subclass
0315   /// depending on which Type is passed.
0316   DbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable,
0317                     MDNode *Expression, MDNode *AssignID, Metadata *Address,
0318                     MDNode *AddressExpression, MDNode *DI);
0319 
0320 public:
0321   /// Used to create DbgVariableRecords during parsing, where some metadata
0322   /// references may still be unresolved. Although for some fields a generic
0323   /// `Metadata*` argument is accepted for forward type-references, the verifier
0324   /// and accessors will reject incorrect types later on. The function is used
0325   /// for all types of DbgVariableRecords for simplicity while parsing, but
0326   /// asserts if any necessary fields are empty or unused fields are not empty,
0327   /// i.e. if the #dbg_assign fields are used for a non-dbg-assign type.
0328   static DbgVariableRecord *
0329   createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val,
0330                                     MDNode *Variable, MDNode *Expression,
0331                                     MDNode *AssignID, Metadata *Address,
0332                                     MDNode *AddressExpression, MDNode *DI);
0333 
0334   static DbgVariableRecord *
0335   createDVRAssign(Value *Val, DILocalVariable *Variable,
0336                   DIExpression *Expression, DIAssignID *AssignID,
0337                   Value *Address, DIExpression *AddressExpression,
0338                   const DILocation *DI);
0339   static DbgVariableRecord *
0340   createLinkedDVRAssign(Instruction *LinkedInstr, Value *Val,
0341                         DILocalVariable *Variable, DIExpression *Expression,
0342                         Value *Address, DIExpression *AddressExpression,
0343                         const DILocation *DI);
0344 
0345   static DbgVariableRecord *createDbgVariableRecord(Value *Location,
0346                                                     DILocalVariable *DV,
0347                                                     DIExpression *Expr,
0348                                                     const DILocation *DI);
0349   static DbgVariableRecord *
0350   createDbgVariableRecord(Value *Location, DILocalVariable *DV,
0351                           DIExpression *Expr, const DILocation *DI,
0352                           DbgVariableRecord &InsertBefore);
0353   static DbgVariableRecord *createDVRDeclare(Value *Address,
0354                                              DILocalVariable *DV,
0355                                              DIExpression *Expr,
0356                                              const DILocation *DI);
0357   static DbgVariableRecord *
0358   createDVRDeclare(Value *Address, DILocalVariable *DV, DIExpression *Expr,
0359                    const DILocation *DI, DbgVariableRecord &InsertBefore);
0360 
0361   /// Iterator for ValueAsMetadata that internally uses direct pointer iteration
0362   /// over either a ValueAsMetadata* or a ValueAsMetadata**, dereferencing to the
0363   /// ValueAsMetadata .
0364   class location_op_iterator
0365       : public iterator_facade_base<location_op_iterator,
0366                                     std::bidirectional_iterator_tag, Value *> {
0367     PointerUnion<ValueAsMetadata *, ValueAsMetadata **> I;
0368 
0369   public:
0370     location_op_iterator(ValueAsMetadata *SingleIter) : I(SingleIter) {}
0371     location_op_iterator(ValueAsMetadata **MultiIter) : I(MultiIter) {}
0372 
0373     location_op_iterator(const location_op_iterator &R) : I(R.I) {}
0374     location_op_iterator &operator=(const location_op_iterator &R) {
0375       I = R.I;
0376       return *this;
0377     }
0378     bool operator==(const location_op_iterator &RHS) const {
0379       return I == RHS.I;
0380     }
0381     const Value *operator*() const {
0382       ValueAsMetadata *VAM = isa<ValueAsMetadata *>(I)
0383                                  ? cast<ValueAsMetadata *>(I)
0384                                  : *cast<ValueAsMetadata **>(I);
0385       return VAM->getValue();
0386     };
0387     Value *operator*() {
0388       ValueAsMetadata *VAM = isa<ValueAsMetadata *>(I)
0389                                  ? cast<ValueAsMetadata *>(I)
0390                                  : *cast<ValueAsMetadata **>(I);
0391       return VAM->getValue();
0392     }
0393     location_op_iterator &operator++() {
0394       if (auto *VAM = dyn_cast<ValueAsMetadata *>(I))
0395         I = VAM + 1;
0396       else
0397         I = cast<ValueAsMetadata **>(I) + 1;
0398       return *this;
0399     }
0400     location_op_iterator &operator--() {
0401       if (auto *VAM = dyn_cast<ValueAsMetadata *>(I))
0402         I = VAM - 1;
0403       else
0404         I = cast<ValueAsMetadata **>(I) - 1;
0405       return *this;
0406     }
0407   };
0408 
0409   bool isDbgDeclare() const { return Type == LocationType::Declare; }
0410   bool isDbgValue() const { return Type == LocationType::Value; }
0411 
0412   /// Get the locations corresponding to the variable referenced by the debug
0413   /// info intrinsic.  Depending on the intrinsic, this could be the
0414   /// variable's value or its address.
0415   iterator_range<location_op_iterator> location_ops() const;
0416 
0417   Value *getVariableLocationOp(unsigned OpIdx) const;
0418 
0419   void replaceVariableLocationOp(Value *OldValue, Value *NewValue,
0420                                  bool AllowEmpty = false);
0421   void replaceVariableLocationOp(unsigned OpIdx, Value *NewValue);
0422   /// Adding a new location operand will always result in this intrinsic using
0423   /// an ArgList, and must always be accompanied by a new expression that uses
0424   /// the new operand.
0425   void addVariableLocationOps(ArrayRef<Value *> NewValues,
0426                               DIExpression *NewExpr);
0427 
0428   unsigned getNumVariableLocationOps() const;
0429 
0430   bool hasArgList() const { return isa<DIArgList>(getRawLocation()); }
0431   /// Returns true if this DbgVariableRecord has no empty MDNodes in its
0432   /// location list.
0433   bool hasValidLocation() const { return getVariableLocationOp(0) != nullptr; }
0434 
0435   /// Does this describe the address of a local variable. True for dbg.addr
0436   /// and dbg.declare, but not dbg.value, which describes its value.
0437   bool isAddressOfVariable() const { return Type == LocationType::Declare; }
0438 
0439   /// Determine if this describes the value of a local variable. It is false for
0440   /// dbg.declare, but true for dbg.value, which describes its value.
0441   bool isValueOfVariable() const { return Type == LocationType::Value; }
0442 
0443   LocationType getType() const { return Type; }
0444 
0445   void setKillLocation();
0446   bool isKillLocation() const;
0447 
0448   void setVariable(DILocalVariable *NewVar) { Variable = NewVar; }
0449   DILocalVariable *getVariable() const { return Variable.get(); };
0450   MDNode *getRawVariable() const { return Variable.getAsMDNode(); }
0451 
0452   void setExpression(DIExpression *NewExpr) { Expression = NewExpr; }
0453   DIExpression *getExpression() const { return Expression.get(); }
0454   MDNode *getRawExpression() const { return Expression.getAsMDNode(); }
0455 
0456   /// Returns the metadata operand for the first location description. i.e.,
0457   /// dbg intrinsic dbg.value,declare operand and dbg.assign 1st location
0458   /// operand (the "value componenet"). Note the operand (singular) may be
0459   /// a DIArgList which is a list of values.
0460   Metadata *getRawLocation() const { return DebugValues[0]; }
0461 
0462   Value *getValue(unsigned OpIdx = 0) const {
0463     return getVariableLocationOp(OpIdx);
0464   }
0465 
0466   /// Use of this should generally be avoided; instead,
0467   /// replaceVariableLocationOp and addVariableLocationOps should be used where
0468   /// possible to avoid creating invalid state.
0469   void setRawLocation(Metadata *NewLocation) {
0470     assert((isa<ValueAsMetadata>(NewLocation) || isa<DIArgList>(NewLocation) ||
0471             isa<MDNode>(NewLocation)) &&
0472            "Location for a DbgVariableRecord must be either ValueAsMetadata or "
0473            "DIArgList");
0474     resetDebugValue(0, NewLocation);
0475   }
0476 
0477   std::optional<DbgVariableFragmentInfo> getFragment() const;
0478   /// Get the FragmentInfo for the variable if it exists, otherwise return a
0479   /// FragmentInfo that covers the entire variable if the variable size is
0480   /// known, otherwise return a zero-sized fragment.
0481   DbgVariableFragmentInfo getFragmentOrEntireVariable() const {
0482     if (auto Frag = getFragment())
0483       return *Frag;
0484     if (auto Sz = getFragmentSizeInBits())
0485       return {*Sz, 0};
0486     return {0, 0};
0487   }
0488   /// Get the size (in bits) of the variable, or fragment of the variable that
0489   /// is described.
0490   std::optional<uint64_t> getFragmentSizeInBits() const;
0491 
0492   bool isEquivalentTo(const DbgVariableRecord &Other) const {
0493     return DbgLoc == Other.DbgLoc && isIdenticalToWhenDefined(Other);
0494   }
0495   // Matches the definition of the Instruction version, equivalent to above but
0496   // without checking DbgLoc.
0497   bool isIdenticalToWhenDefined(const DbgVariableRecord &Other) const {
0498     return std::tie(Type, DebugValues, Variable, Expression,
0499                     AddressExpression) ==
0500            std::tie(Other.Type, Other.DebugValues, Other.Variable,
0501                     Other.Expression, Other.AddressExpression);
0502   }
0503 
0504   /// @name DbgAssign Methods
0505   /// @{
0506   bool isDbgAssign() const { return getType() == LocationType::Assign; }
0507 
0508   Value *getAddress() const;
0509   Metadata *getRawAddress() const {
0510     return isDbgAssign() ? DebugValues[1] : DebugValues[0];
0511   }
0512   Metadata *getRawAssignID() const { return DebugValues[2]; }
0513   DIAssignID *getAssignID() const;
0514   DIExpression *getAddressExpression() const { return AddressExpression.get(); }
0515   MDNode *getRawAddressExpression() const {
0516     return AddressExpression.getAsMDNode();
0517   }
0518   void setAddressExpression(DIExpression *NewExpr) {
0519     AddressExpression = NewExpr;
0520   }
0521   void setAssignId(DIAssignID *New);
0522   void setAddress(Value *V) { resetDebugValue(1, ValueAsMetadata::get(V)); }
0523   /// Kill the address component.
0524   void setKillAddress();
0525   /// Check whether this kills the address component. This doesn't take into
0526   /// account the position of the intrinsic, therefore a returned value of false
0527   /// does not guarentee the address is a valid location for the variable at the
0528   /// intrinsic's position in IR.
0529   bool isKillAddress() const;
0530 
0531   /// @}
0532 
0533   DbgVariableRecord *clone() const;
0534   /// Convert this DbgVariableRecord back into a dbg.value intrinsic.
0535   /// \p InsertBefore Optional position to insert this intrinsic.
0536   /// \returns A new dbg.value intrinsic representiung this DbgVariableRecord.
0537   DbgVariableIntrinsic *createDebugIntrinsic(Module *M,
0538                                              Instruction *InsertBefore) const;
0539 
0540   /// Handle changes to the location of the Value(s) that we refer to happening
0541   /// "under our feet".
0542   void handleChangedLocation(Metadata *NewLocation);
0543 
0544   void print(raw_ostream &O, bool IsForDebug = false) const;
0545   void print(raw_ostream &ROS, ModuleSlotTracker &MST, bool IsForDebug) const;
0546 
0547   /// Support type inquiry through isa, cast, and dyn_cast.
0548   static bool classof(const DbgRecord *E) {
0549     return E->getRecordKind() == ValueKind;
0550   }
0551 };
0552 
0553 /// Filter the DbgRecord range to DbgVariableRecord types only and downcast.
0554 static inline auto
0555 filterDbgVars(iterator_range<simple_ilist<DbgRecord>::iterator> R) {
0556   return map_range(
0557       make_filter_range(R,
0558                         [](DbgRecord &E) { return isa<DbgVariableRecord>(E); }),
0559       [](DbgRecord &E) { return std::ref(cast<DbgVariableRecord>(E)); });
0560 }
0561 
0562 /// Per-instruction record of debug-info. If an Instruction is the position of
0563 /// some debugging information, it points at a DbgMarker storing that info. Each
0564 /// marker points back at the instruction that owns it. Various utilities are
0565 /// provided for manipulating the DbgRecords contained within this marker.
0566 ///
0567 /// This class has a rough surface area, because it's needed to preserve the
0568 /// one arefact that we can't yet eliminate from the intrinsic / dbg.value
0569 /// debug-info design: the order of records is significant, and duplicates can
0570 /// exist. Thus, if one has a run of debug-info records such as:
0571 ///    dbg.value(...
0572 ///    %foo = barinst
0573 ///    dbg.value(...
0574 /// and remove barinst, then the dbg.values must be preserved in the correct
0575 /// order. Hence, the use of iterators to select positions to insert things
0576 /// into, or the occasional InsertAtHead parameter indicating that new records
0577 /// should go at the start of the list.
0578 ///
0579 /// There are only five or six places in LLVM that truly rely on this ordering,
0580 /// which we can improve in the future. Additionally, many improvements in the
0581 /// way that debug-info is stored can be achieved in this class, at a future
0582 /// date.
0583 class DbgMarker {
0584 public:
0585   DbgMarker() {}
0586   /// Link back to the Instruction that owns this marker. Can be null during
0587   /// operations that move a marker from one instruction to another.
0588   Instruction *MarkedInstr = nullptr;
0589 
0590   /// List of DbgRecords, the non-instruction equivalent of llvm.dbg.*
0591   /// intrinsics. There is a one-to-one relationship between each debug
0592   /// intrinsic in a block and each DbgRecord once the representation has been
0593   /// converted, and the ordering is meaningful in the same way.
0594   simple_ilist<DbgRecord> StoredDbgRecords;
0595   bool empty() const { return StoredDbgRecords.empty(); }
0596 
0597   const BasicBlock *getParent() const;
0598   BasicBlock *getParent();
0599 
0600   /// Handle the removal of a marker: the position of debug-info has gone away,
0601   /// but the stored debug records should not. Drop them onto the next
0602   /// instruction, or otherwise work out what to do with them.
0603   void removeMarker();
0604   void dump() const;
0605 
0606   void removeFromParent();
0607   void eraseFromParent();
0608 
0609   /// Implement operator<< on DbgMarker.
0610   void print(raw_ostream &O, bool IsForDebug = false) const;
0611   void print(raw_ostream &ROS, ModuleSlotTracker &MST, bool IsForDebug) const;
0612 
0613   /// Produce a range over all the DbgRecords in this Marker.
0614   iterator_range<simple_ilist<DbgRecord>::iterator> getDbgRecordRange();
0615   iterator_range<simple_ilist<DbgRecord>::const_iterator>
0616   getDbgRecordRange() const;
0617   /// Transfer any DbgRecords from \p Src into this DbgMarker. If \p
0618   /// InsertAtHead is true, place them before existing DbgRecords, otherwise
0619   /// afterwards.
0620   void absorbDebugValues(DbgMarker &Src, bool InsertAtHead);
0621   /// Transfer the DbgRecords in \p Range from \p Src into this DbgMarker. If
0622   /// \p InsertAtHead is true, place them before existing DbgRecords, otherwise
0623   // afterwards.
0624   void absorbDebugValues(iterator_range<DbgRecord::self_iterator> Range,
0625                          DbgMarker &Src, bool InsertAtHead);
0626   /// Insert a DbgRecord into this DbgMarker, at the end of the list. If
0627   /// \p InsertAtHead is true, at the start.
0628   void insertDbgRecord(DbgRecord *New, bool InsertAtHead);
0629   /// Insert a DbgRecord prior to a DbgRecord contained within this marker.
0630   void insertDbgRecord(DbgRecord *New, DbgRecord *InsertBefore);
0631   /// Insert a DbgRecord after a DbgRecord contained within this marker.
0632   void insertDbgRecordAfter(DbgRecord *New, DbgRecord *InsertAfter);
0633   /// Clone all DbgMarkers from \p From into this marker. There are numerous
0634   /// options to customise the source/destination, due to gnarliness, see class
0635   /// comment.
0636   /// \p FromHere If non-null, copy from FromHere to the end of From's
0637   /// DbgRecords
0638   /// \p InsertAtHead Place the cloned DbgRecords at the start of
0639   /// StoredDbgRecords
0640   /// \returns Range over all the newly cloned DbgRecords
0641   iterator_range<simple_ilist<DbgRecord>::iterator>
0642   cloneDebugInfoFrom(DbgMarker *From,
0643                      std::optional<simple_ilist<DbgRecord>::iterator> FromHere,
0644                      bool InsertAtHead = false);
0645   /// Erase all DbgRecords in this DbgMarker.
0646   void dropDbgRecords();
0647   /// Erase a single DbgRecord from this marker. In an ideal future, we would
0648   /// never erase an assignment in this way, but it's the equivalent to
0649   /// erasing a debug intrinsic from a block.
0650   void dropOneDbgRecord(DbgRecord *DR);
0651 
0652   /// We generally act like all llvm Instructions have a range of DbgRecords
0653   /// attached to them, but in reality sometimes we don't allocate the DbgMarker
0654   /// to save time and memory, but still have to return ranges of DbgRecords.
0655   /// When we need to describe such an unallocated DbgRecord range, use this
0656   /// static markers range instead. This will bite us if someone tries to insert
0657   /// a DbgRecord in that range, but they should be using the Official (TM) API
0658   /// for that.
0659   static DbgMarker EmptyDbgMarker;
0660   static iterator_range<simple_ilist<DbgRecord>::iterator>
0661   getEmptyDbgRecordRange() {
0662     return make_range(EmptyDbgMarker.StoredDbgRecords.end(),
0663                       EmptyDbgMarker.StoredDbgRecords.end());
0664   }
0665 };
0666 
0667 inline raw_ostream &operator<<(raw_ostream &OS, const DbgMarker &Marker) {
0668   Marker.print(OS);
0669   return OS;
0670 }
0671 
0672 /// Inline helper to return a range of DbgRecords attached to a marker. It needs
0673 /// to be inlined as it's frequently called, but also come after the declaration
0674 /// of DbgMarker. Thus: it's pre-declared by users like Instruction, then an
0675 /// inlineable body defined here.
0676 inline iterator_range<simple_ilist<DbgRecord>::iterator>
0677 getDbgRecordRange(DbgMarker *DebugMarker) {
0678   if (!DebugMarker)
0679     return DbgMarker::getEmptyDbgRecordRange();
0680   return DebugMarker->getDbgRecordRange();
0681 }
0682 
0683 DEFINE_ISA_CONVERSION_FUNCTIONS(DbgRecord, LLVMDbgRecordRef)
0684 
0685 /// Used to temporarily set the debug info format of a function, module, or
0686 /// basic block for the duration of this object's lifetime, after which the
0687 /// prior state will be restored.
0688 template <typename T> class ScopedDbgInfoFormatSetter {
0689   T &Obj;
0690   bool OldState;
0691 
0692 public:
0693   ScopedDbgInfoFormatSetter(T &Obj, bool NewState)
0694       : Obj(Obj), OldState(Obj.IsNewDbgInfoFormat) {
0695     Obj.setIsNewDbgInfoFormat(NewState);
0696   }
0697   ~ScopedDbgInfoFormatSetter() { Obj.setIsNewDbgInfoFormat(OldState); }
0698 };
0699 
0700 template <typename T>
0701 ScopedDbgInfoFormatSetter(T &Obj,
0702                           bool NewState) -> ScopedDbgInfoFormatSetter<T>;
0703 
0704 } // namespace llvm
0705 
0706 #endif // LLVM_IR_DEBUGPROGRAMINSTRUCTION_H