Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:29

0001 //===- llvm/Support/DebugCounter.h - Debug counter support ------*- 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 /// \file
0009 /// This file provides an implementation of debug counters.  Debug
0010 /// counters are a tool that let you narrow down a miscompilation to a specific
0011 /// thing happening.
0012 ///
0013 /// To give a use case: Imagine you have a file, very large, and you
0014 /// are trying to understand the minimal transformation that breaks it. Bugpoint
0015 /// and bisection is often helpful here in narrowing it down to a specific pass,
0016 /// but it's still a very large file, and a very complicated pass to try to
0017 /// debug.  That is where debug counting steps in.  You can instrument the pass
0018 /// with a debug counter before it does a certain thing, and depending on the
0019 /// counts, it will either execute that thing or not.  The debug counter itself
0020 /// consists of a list of chunks (inclusive numeric ranges). `shouldExecute`
0021 /// returns true iff the list is empty or the current count is in one of the
0022 /// chunks.
0023 ///
0024 /// Note that a counter set to a negative number will always execute. For a
0025 /// concrete example, during predicateinfo creation, the renaming pass replaces
0026 /// each use with a renamed use.
0027 ////
0028 /// If I use DEBUG_COUNTER to create a counter called "predicateinfo", and
0029 /// variable name RenameCounter, and then instrument this renaming with a debug
0030 /// counter, like so:
0031 ///
0032 /// if (!DebugCounter::shouldExecute(RenameCounter)
0033 /// <continue or return or whatever not executing looks like>
0034 ///
0035 /// Now I can, from the command line, make it rename or not rename certain uses
0036 /// by setting the chunk list.
0037 /// So for example
0038 /// bin/opt -debug-counter=predicateinfo=47
0039 /// will skip renaming the first 47 uses, then rename one, then skip the rest.
0040 //===----------------------------------------------------------------------===//
0041 
0042 #ifndef LLVM_SUPPORT_DEBUGCOUNTER_H
0043 #define LLVM_SUPPORT_DEBUGCOUNTER_H
0044 
0045 #include "llvm/ADT/ArrayRef.h"
0046 #include "llvm/ADT/DenseMap.h"
0047 #include "llvm/ADT/StringRef.h"
0048 #include "llvm/ADT/UniqueVector.h"
0049 #include "llvm/Support/Debug.h"
0050 #include <string>
0051 
0052 namespace llvm {
0053 
0054 class raw_ostream;
0055 
0056 class DebugCounter {
0057 public:
0058   struct Chunk {
0059     int64_t Begin;
0060     int64_t End;
0061     void print(llvm::raw_ostream &OS);
0062     bool contains(int64_t Idx) { return Idx >= Begin && Idx <= End; }
0063   };
0064 
0065   static void printChunks(raw_ostream &OS, ArrayRef<Chunk>);
0066 
0067   /// Return true on parsing error and print the error message on the
0068   /// llvm::errs()
0069   static bool parseChunks(StringRef Str, SmallVector<Chunk> &Res);
0070 
0071   /// Returns a reference to the singleton instance.
0072   static DebugCounter &instance();
0073 
0074   // Used by the command line option parser to push a new value it parsed.
0075   void push_back(const std::string &);
0076 
0077   // Register a counter with the specified name.
0078   //
0079   // FIXME: Currently, counter registration is required to happen before command
0080   // line option parsing. The main reason to register counters is to produce a
0081   // nice list of them on the command line, but i'm not sure this is worth it.
0082   static unsigned registerCounter(StringRef Name, StringRef Desc) {
0083     return instance().addCounter(std::string(Name), std::string(Desc));
0084   }
0085   static bool shouldExecuteImpl(unsigned CounterName);
0086 
0087   inline static bool shouldExecute(unsigned CounterName) {
0088     if (!isCountingEnabled())
0089       return true;
0090     return shouldExecuteImpl(CounterName);
0091   }
0092 
0093   // Return true if a given counter had values set (either programatically or on
0094   // the command line).  This will return true even if those values are
0095   // currently in a state where the counter will always execute.
0096   static bool isCounterSet(unsigned ID) {
0097     return instance().Counters[ID].IsSet;
0098   }
0099 
0100   struct CounterState {
0101     int64_t Count;
0102     uint64_t ChunkIdx;
0103   };
0104 
0105   // Return the state of a counter. This only works for set counters.
0106   static CounterState getCounterState(unsigned ID) {
0107     auto &Us = instance();
0108     auto Result = Us.Counters.find(ID);
0109     assert(Result != Us.Counters.end() && "Asking about a non-set counter");
0110     return {Result->second.Count, Result->second.CurrChunkIdx};
0111   }
0112 
0113   // Set a registered counter to a given state.
0114   static void setCounterState(unsigned ID, CounterState State) {
0115     auto &Us = instance();
0116     auto &Counter = Us.Counters[ID];
0117     Counter.Count = State.Count;
0118     Counter.CurrChunkIdx = State.ChunkIdx;
0119   }
0120 
0121   // Dump or print the current counter set into llvm::dbgs().
0122   LLVM_DUMP_METHOD void dump() const;
0123 
0124   void print(raw_ostream &OS) const;
0125 
0126   // Get the counter ID for a given named counter, or return 0 if none is found.
0127   unsigned getCounterId(const std::string &Name) const {
0128     return RegisteredCounters.idFor(Name);
0129   }
0130 
0131   // Return the number of registered counters.
0132   unsigned int getNumCounters() const { return RegisteredCounters.size(); }
0133 
0134   // Return the name and description of the counter with the given ID.
0135   std::pair<std::string, std::string> getCounterInfo(unsigned ID) const {
0136     return std::make_pair(RegisteredCounters[ID], Counters.lookup(ID).Desc);
0137   }
0138 
0139   // Iterate through the registered counters
0140   typedef UniqueVector<std::string> CounterVector;
0141   CounterVector::const_iterator begin() const {
0142     return RegisteredCounters.begin();
0143   }
0144   CounterVector::const_iterator end() const { return RegisteredCounters.end(); }
0145 
0146   // Force-enables counting all DebugCounters.
0147   //
0148   // Since DebugCounters are incompatible with threading (not only do they not
0149   // make sense, but we'll also see data races), this should only be used in
0150   // contexts where we're certain we won't spawn threads.
0151   static void enableAllCounters() { instance().Enabled = true; }
0152 
0153   static bool isCountingEnabled() {
0154 // Compile to nothing when debugging is off
0155 #ifdef NDEBUG
0156     return false;
0157 #else
0158     return instance().Enabled || instance().ShouldPrintCounter;
0159 #endif
0160   }
0161 
0162 protected:
0163   unsigned addCounter(const std::string &Name, const std::string &Desc) {
0164     unsigned Result = RegisteredCounters.insert(Name);
0165     Counters[Result] = {};
0166     Counters[Result].Desc = Desc;
0167     return Result;
0168   }
0169   // Struct to store counter info.
0170   struct CounterInfo {
0171     int64_t Count = 0;
0172     uint64_t CurrChunkIdx = 0;
0173     bool IsSet = false;
0174     std::string Desc;
0175     SmallVector<Chunk> Chunks;
0176   };
0177 
0178   DenseMap<unsigned, CounterInfo> Counters;
0179   CounterVector RegisteredCounters;
0180 
0181   // Whether we should do DebugCounting at all. DebugCounters aren't
0182   // thread-safe, so this should always be false in multithreaded scenarios.
0183   bool Enabled = false;
0184 
0185   bool ShouldPrintCounter = false;
0186 
0187   bool BreakOnLast = false;
0188 };
0189 
0190 #define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)                              \
0191   static const unsigned VARNAME =                                              \
0192       DebugCounter::registerCounter(COUNTERNAME, DESC)
0193 
0194 } // namespace llvm
0195 #endif