[llvm] [AMDGPU][NewInsertWaitcnt] Add Event Tracker (PR #226970)
via llvm-commits
llvm-commits at lists.llvm.org
Mon Sep 28 05:35:18 PDT 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-backend-amdgpu
Author: Pierre van Houtryve (Pierre-vh)
<details>
<summary>Changes</summary>
See #<!-- -->226335
## Introduction
Adds the basic infrastructure needed to track in-flight records for each `InstCounterType`.
This is not a full functional replacement of `SIInsertWaitcnts::WaitcntBrackets` and it does not
aim to be one, as we'd like to break up its functionality into multiple different pieces.
One goal with the new implementation is to avoid having a single "tracker" class
that does everything. Instead, the `EventTracker` aims to do one thing and do it right:
preserve the history of a counter (instructions + events issued) and the value of the counter.
Any specific queries, such as "what STORE_CNT do I need to use this RU" is something that belongs
to helper methods in the client of the class or a utils file.
## Class Design
This class is designed to use a single "source of truth" for all information, which is a compact
timeline of events per `InstCounterType`. The intent is that we'll just iterate the timeline to answer certain queries
instead of baking-in a bunch of `DenseMaps` for every query dimension we need.
This considerably simplifies the implementation. Most of the code in the files here are
boilerplate, assertions, debug dumps, verification methods, and so on. There is very little "critical" logic.
The design/API presented here is _not_ final - it'll evolve as we aim for feature parity with
`SIInsertWaitcnts` in the `NewInsertWaitcnts` pass.
## Performance
As this design leans on iterating the timeline possibly multiple times per instruction, I made sure it'd be fast
by keeping the record type small (16B right now, may grow to 32) and stored contiguously.
I also did some profiling on very big test cases by shadowing `WaitcntBrackets` and doing many (dozens) of timeline
iteration each instruction for every counter, and there is no visible spike in the flame graph of the profiler.
Note that the average timeline is less than a dozen entries. In the rare cases we go to the max value that can be encoded for a given counter/waitcnt, we are still well below 100 entries.
Linear scans are not going to be a performance issue before multiple hundreds, if not thousands of entries. Far more if we are smart about how many times we iterate the timeline instead of iterating it multiple times per instruction.
## Testing
I tested this implementation by shadowing the `WaitcntBrackets` class in a downstream branch and checking
my results against it, until I was confident that the values given by the `EventTracker` were as precise or
more precise than the values given by `WaitcntBrackets` for the entire test suite.
## Use of AI
AI was exclusively used for 2 things:
- As a design companion, helping me flesh out architecture ideas in "plan mode" so I could iterate fast.
I also used it as a research tool to find prior art, gather data for me to verify, etc.
- As a refactoring/boilerplate generation tool, such as creating files with basic boilerplate,
generating scaffolding like methods/class declarations/etc.
AI was not used to write any serious code/algorithms in any function of either the unit tests or the implementation files. It did not write any documentation or commit message either.
Assisted-by: Claude Opus (4.8/5.5) and Sonnet (5)
---
Patch is 51.48 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/226970.diff
6 Files Affected:
- (added) llvm/lib/Target/AMDGPU/AMDGPUEventTracking.cpp (+477)
- (added) llvm/lib/Target/AMDGPU/AMDGPUEventTracking.h (+354)
- (modified) llvm/lib/Target/AMDGPU/AMDGPUHWEvents.h (+27)
- (modified) llvm/lib/Target/AMDGPU/CMakeLists.txt (+1)
- (added) llvm/unittests/Target/AMDGPU/AMDGPUEventTrackingTest.cpp (+618)
- (modified) llvm/unittests/Target/AMDGPU/CMakeLists.txt (+1)
``````````diff
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUEventTracking.cpp b/llvm/lib/Target/AMDGPU/AMDGPUEventTracking.cpp
new file mode 100644
index 0000000000000..8b383b45de67a
--- /dev/null
+++ b/llvm/lib/Target/AMDGPU/AMDGPUEventTracking.cpp
@@ -0,0 +1,477 @@
+//===- AMDGPUEventTracking.cpp ----------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "AMDGPUEventTracking.h"
+#include "AMDGPUHWEvents.h"
+#include "AMDGPUWaitcntUtils.h"
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineInstr.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include <algorithm>
+#include <optional>
+
+#define DEBUG_TYPE "amdgpu-event-tracking"
+
+namespace llvm {
+
+/// Mimic legacy (coarse) tracking of counter state.
+static cl::opt<bool> MimicLegacyTracking("amdgpu-event-legacy-tracking",
+ cl::init(false));
+
+#ifndef NDEBUG
+static cl::opt<bool> EventTrackerPrintAll(
+ "amdgpu-event-tracker-print-all", cl::init(false),
+ cl::desc("When using -debug, print the full set of live events every time "
+ "an event is added or removed"));
+#endif
+
+namespace AMDGPU {
+namespace eventtracking {
+
+namespace {
+static bool greaterThan(const EventTrackerRecord &A,
+ const EventTrackerRecord &B) {
+ return A.getScore() > B.getScore();
+}
+} // namespace
+
+EventTrackerRecord::EventTrackerRecord(EventTrackingContext &Ctx,
+ MachineInstr *MI, SingleHWEvent Kind,
+ uint32_t Score)
+ : EventTrackerRecord(Ctx.nextDynamicInstanceID(), MI, Kind, Score) {}
+
+void EventTrackerRecord::print(raw_ostream &OS, bool PrintMI,
+ unsigned Indent) const {
+ OS.indent(Indent) << "#" << ID << " " << Kind << " (Score=" << Score << "): ";
+ if (PrintMI && MI)
+ OS << *MI;
+ else
+ OS << "MI@" << (void *)MI << "\n";
+}
+
+#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
+LLVM_DUMP_METHOD void EventTrackerRecord::dump() const {
+ dbgs() << "\n";
+ print(dbgs(), /*PrintMI=*/true);
+ dbgs() << "\n";
+}
+#endif
+
+EventTracker::EventTracker(MachineBasicBlock &MBB, EventTrackingContext &ETC)
+ : MBB(&MBB), Ctx(&ETC) {
+ Counters.resize(ETC.counters().size());
+ for (const CounterInfo &Info : ETC.counters())
+ Counters[Info.CounterT].CI = &Info;
+}
+
+void EventTracker::enterBlock() {
+ LLVM_DEBUG(dbgs() << "\n[EventTracker] Entering ";
+ MBB->printAsOperand(dbgs()); dbgs() << "\n");
+
+ // FIXME: This is a bit hacky, but we need to save the old state in case the
+ // MBB is also its own predecessor. Revisit when the design and clients of
+ // this class are set in stone.
+
+ SmallVector<EventTracker *> Preds;
+ bool IsSelfPred = false;
+ if (Preds.empty() && !MBB->pred_empty()) {
+ for (MachineBasicBlock *Pred : MBB->predecessors()) {
+ if (Pred == MBB)
+ IsSelfPred = true;
+ else
+ Preds.push_back(&(*Ctx)[Pred]);
+ }
+ }
+
+ if (IsSelfPred) {
+ EventTracker SelfCopy = *this;
+ Preds.push_back(&SelfCopy);
+ clear();
+ recordIncomings(*Ctx, Preds);
+ } else {
+ clear();
+ recordIncomings(*Ctx, Preds);
+ }
+}
+
+void EventTracker::leaveBlock() {
+ LLVM_DEBUG(dbgs() << "[EventTracker] Leaving "; MBB->printAsOperand(dbgs());
+ dbgs() << "\n");
+}
+
+void EventTracker::record(MachineInstr &MI, SingleHWEvent Event) {
+ LLVM_DEBUG(dbgs() << "[EventTracker] Recording " << Event << ": " << MI);
+
+ EventTrackerRecord Rec = EventTrackerRecord(*Ctx, &MI, Event);
+ [[maybe_unused]] bool FoundMatch = false;
+ for (auto &CD : Counters) {
+ if (!CD.CI->Events.contains(Event))
+ continue;
+
+ FoundMatch = true;
+ ++CD.Count;
+ CD.LegacyPendingEvents |= Event;
+
+ // Do not age records if we are out-of-order.
+ if (!CD.IsOutOfOrder) {
+ // NB: There is an intentional tradeoff here. We could avoid this loop by
+ // instead storing a timestamp in each record, and having a
+ // constantly-increasing clock to infer the score (clock-timestamp is
+ // score). However, it'd:
+ // - Complexify fetching the score (`EventTrackerRecord` cannot answer it
+ // on its own anymore and we need a separate query/wrapper).
+ // - Make merge of incoming records a bit more annoying (we'd need to
+ // rebase the `clock`).
+ // - Potentially demand (much) more space in EventTrackerRecord to store
+ // bigger numbers.
+ //
+ // All in all, I think this small loop is fine for now, but we can still
+ // change the system if we have data backed up by profiling to
+ // justify the change.
+ for (auto &Live : CD.LiveRecords)
+ Live.setScore(Live.getScore() + 1); // Age all existing events.
+ }
+
+ CD.LiveRecords.push_back(Rec);
+
+#ifndef NDEBUG
+ LLVM_DEBUG(if (EventTrackerPrintAll) {
+ dbgs().indent(2) << "Updated Timeline:\n";
+ print(dbgs(), CD, /*Indent=*/4);
+ });
+#endif
+ }
+
+ assert(FoundMatch && "Event has no matching InstCounterType!");
+}
+
+void EventTracker::wait(InstCounterType T, unsigned N) {
+ auto &CD = get(T);
+ LLVM_DEBUG(dbgs() << "[EventTracker] Wait on " << getInstCounterName(T)
+ << " for " << N << "\n");
+
+ // Fast path for clearing the counter
+ if (N == 0) {
+ CD.LiveRecords.clear();
+ CD.Count = 0;
+ CD.IsIndeterminate = false;
+ CD.IsOutOfOrder = false;
+ CD.LegacyPendingEvents = HWEvents();
+ return;
+ }
+
+ CD.Count = std::min(CD.Count, N);
+
+ // Don't bother erasing stuff if we are out-of-order. All records have a score
+ // of zero in such cases.
+ if (!CD.IsOutOfOrder) {
+ auto *RmIt = remove_if(CD.LiveRecords, [&](EventTrackerRecord &E) {
+ if (E.getScore() < N)
+ return false;
+ LLVM_DEBUG(dbgs() << " | Removing "; E.print(dbgs()));
+ return true;
+ });
+ CD.LiveRecords.erase(RmIt, CD.LiveRecords.end());
+ }
+
+ LLVM_DEBUG(dbgs() << " | => Updated Count:" << CD.Count << "\n");
+
+#ifndef NDEBUG
+ LLVM_DEBUG(if (EventTrackerPrintAll) {
+ dbgs().indent(2) << "Updated Timeline:\n";
+ print(dbgs(), CD, /*Indent=*/4);
+ });
+#endif
+}
+
+void EventTracker::markIndeterminate(InstCounterType T) {
+ LLVM_DEBUG(dbgs() << "[EventTracker] Marking " << getInstCounterName(T)
+ << " as indeterminate!\n");
+ auto &CD = get(T);
+ CD.IsIndeterminate = true;
+ markOutOfOrder(T);
+}
+
+void EventTracker::markOutOfOrder(InstCounterType T) {
+ LLVM_DEBUG(dbgs() << "[EventTracker] Marking " << getInstCounterName(T)
+ << " as out-of-order!\n");
+ auto &CD = get(T);
+ CD.IsOutOfOrder = true;
+ for (auto &Rec : CD.LiveRecords)
+ Rec.setScore(0);
+}
+
+std::optional<unsigned> EventTracker::count(InstCounterType T) const {
+ auto &CD = get(T);
+ if (CD.IsIndeterminate)
+ return std::nullopt;
+ return get(T).Count;
+}
+
+bool EventTracker::isIndeterminate(InstCounterType T) const {
+ return get(T).IsIndeterminate;
+}
+
+bool EventTracker::isOutOfOrder(InstCounterType T) const {
+ return get(T).IsOutOfOrder;
+}
+
+HWEvents EventTracker::getPendingEvents(InstCounterType T) const {
+ const auto &CD = get(T);
+ if (CD.IsIndeterminate)
+ return CD.CI->Events; // return all events
+
+ if (MimicLegacyTracking)
+ return CD.LegacyPendingEvents;
+
+ HWEvents Res;
+ for (const auto &E : get(T).LiveRecords)
+ Res |= E.getKind();
+ return Res;
+}
+
+ArrayRef<EventTrackerRecord>
+EventTracker::getLiveRecords(InstCounterType T) const {
+ return get(T).LiveRecords;
+}
+
+void EventTracker::print(raw_ostream &OS, InstCounterType T) const {
+ print(OS, get(T));
+}
+
+bool EventTracker::mimicsLegacyTracking() { return MimicLegacyTracking; }
+
+#if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
+void EventTracker::verify() const {
+ assert(MBB && Ctx && "Invalid internal state!");
+
+ for (auto &C : Counters) {
+ const auto OnError = [&]() {
+ dbgs() << "EventTracker verification error\n";
+ print(dbgs(), C);
+ };
+
+ if (C.IsIndeterminate) {
+ if (!C.IsOutOfOrder) {
+ OnError();
+ assert(false && "IsIndeterminate but not IsOutOfOrder");
+ }
+ continue;
+ }
+
+ if (C.IsOutOfOrder) {
+ if (!all_of(C.LiveRecords, [](auto &R) { return R.getScore() == 0; })) {
+ OnError();
+ assert(false &&
+ "IsOutOfOrder but some records do not have a score of 0!");
+ }
+ }
+
+ if (C.Count > C.LiveRecords.size() && !mimicsLegacyTracking()) {
+ OnError();
+ assert(false &&
+ "'Count' is inconsistent with the number of live records");
+ }
+
+ for (auto &E : C.LiveRecords) {
+ if (E.getScore() > C.Count) {
+ OnError();
+ dbgs() << "Concerning Record:";
+ E.print(dbgs());
+ assert(false && "record score is out of range");
+ }
+ }
+
+ // Check live records are sorted
+ if (!is_sorted(C.LiveRecords, greaterThan)) {
+ OnError();
+ assert(false && "live records are not sorted!");
+ }
+ }
+}
+#endif
+
+void EventTracker::print(raw_ostream &OS, bool IgnoreEmpty,
+ unsigned Indent) const {
+ OS.indent(Indent) << "EventTracker for ";
+ MBB->printAsOperand(OS);
+ OS << ":";
+ if (IgnoreEmpty) {
+ if (all_of(Counters, [](const auto &CD) { return CD.Count == 0; })) {
+ OS << " (empty)\n";
+ return;
+ }
+ }
+
+ OS << "\n";
+ for (auto &C : Counters) {
+ if (IgnoreEmpty && C.Count == 0)
+ continue;
+ print(dbgs(), C, Indent + 2);
+ }
+}
+
+#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
+LLVM_DUMP_METHOD void EventTracker::dump() const {
+ dbgs() << "\n";
+ print(dbgs());
+ dbgs() << "\n";
+}
+#endif
+
+void EventTracker::clear() {
+ for (auto &C : Counters) {
+ C.LiveRecords.clear();
+ C.Count = 0;
+ C.IsIndeterminate = false;
+ C.IsOutOfOrder = false;
+ }
+}
+
+void EventTracker::recordIncomings(EventTrackingContext &ETC,
+ ArrayRef<EventTracker *> Preds) {
+ LLVM_DEBUG(if (!Preds.empty()) {
+ dbgs() << "[EventTracker] Recording incoming events (merge) from "
+ "predecessors:\n";
+ for (EventTracker *Pred : Preds) {
+ Pred->print(dbgs(), /*IgnoreEmpty=*/true, /*Indent=*/2);
+ }
+ });
+
+ /// Iterate over all counters that are available to us.
+ for (auto &CI : ETC.counters()) {
+ auto &CData = Counters[CI.CounterT];
+ assert(CData.LiveRecords.empty());
+
+ DenseMap<EventTrackerRecord::DynamicInstanceID, EventTrackerRecord> Acc;
+
+ for (EventTracker *Pred : Preds) {
+ auto &PredCData = Pred->Counters[CI.CounterT];
+
+ // Merge domain for the count value:
+ CData.Count = std::max(CData.Count, PredCData.Count);
+ // Merge domain for the legacy pending events.
+ CData.LegacyPendingEvents |= PredCData.LegacyPendingEvents;
+ // Merge domain for the indeterminate state.
+ CData.IsIndeterminate |= PredCData.IsIndeterminate;
+ // Merge domain for the out-of-order state.
+ CData.IsOutOfOrder |= PredCData.IsOutOfOrder;
+
+ for (EventTrackerRecord &PredEntry : PredCData.LiveRecords) {
+ EventTrackerRecord::DynamicInstanceID ID = PredEntry.getID();
+ auto It = Acc.find(ID);
+ if (It != Acc.end()) {
+ auto &AccVal = It->second;
+ AccVal.setScore(std::min(AccVal.getScore(), PredEntry.getScore()));
+ assert(
+ PredEntry.getMI() == AccVal.getMI() &&
+ PredEntry.getKind() == AccVal.getKind() &&
+ "EventTrackerRecord have same DynamicInstanceID, but different "
+ "MachineInstr/HWEvent kind, which should not be possible");
+ } else
+ Acc.insert({ID, PredEntry});
+ }
+ }
+
+ if (MimicLegacyTracking) {
+ CData.PersistentUpperBound =
+ std::max(CData.PersistentUpperBound, CData.Count);
+ CData.Count = CData.PersistentUpperBound;
+ }
+
+ auto AccVals = Acc.values();
+ CData.LiveRecords.append(AccVals.begin(), AccVals.end());
+
+ // Sort records by Score (descending) for consistent iteration.
+ stable_sort(CData.LiveRecords, greaterThan);
+ }
+
+ LLVM_DEBUG(if (!Preds.empty()) {
+ dbgs() << "[EventTracker] Timeline after recording incomings:\n";
+ print(dbgs(), /*IgnoreEmpty=*/true, /*Indent=*/2);
+ });
+}
+
+void EventTracker::print(raw_ostream &OS, const CounterData &CD,
+ unsigned Indent) {
+ OS.indent(Indent) << getInstCounterName(CD.CI->CounterT)
+ << " (Count=" << CD.Count
+ << ", PersistentUpperBound=" << CD.PersistentUpperBound
+ << ", LiveRecords=" << CD.LiveRecords.size()
+ << ", IsOutOfOrder=" << CD.IsOutOfOrder
+ << ", IsIndeterminate=" << CD.IsIndeterminate << ")\n";
+ for (const auto &E : CD.LiveRecords) {
+ OS.indent(Indent + 2);
+ E.print(OS);
+ }
+}
+
+EventTrackingContext::EventTrackingContext(MachineFunction &MF,
+ ArrayRef<CounterInfo> Counters)
+ : CounterInfos(Counters) {
+ LLVM_DEBUG(dbgs() << "\n[EventTrackingContext] CounterInfos for "
+ << MF.getName() << "\n";
+ for (const auto &CI
+ : CounterInfos) {
+ dbgs().indent(2)
+ << AMDGPU::getInstCounterName(CI.CounterT) << " ";
+ if (CI.Events.none()) {
+ dbgs() << " (unused - no HWEvents assigned)\n";
+ } else {
+ dbgs() << "(Limit=" << CI.Limit << ") " << CI.Events << "\n";
+ }
+ });
+
+ Trackers.reserve(MF.size());
+ for (MachineBasicBlock &MBB : MF)
+ Trackers[&MBB] = std::make_unique<EventTracker>(MBB, *this);
+}
+
+EventTracker &EventTrackingContext::operator[](MachineBasicBlock *MBB) {
+ assert(MBB);
+ return *Trackers.at(MBB);
+}
+
+#if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
+void EventTrackingContext::verify() const {
+ for (const auto &[MBB, Tracker] : Trackers) {
+ assert(MBB && "Unexpected nullptr entry!");
+ Tracker->verify();
+ }
+
+ // Check CounterInfos is sane.
+ for (auto [Idx, CI] : enumerate(CounterInfos)) {
+ assert(Idx == CI.CounterT && "CounterInfo is in wrong position!");
+ assert(CI.Events.any() &&
+ "InstCounterType has no event associated with it!");
+ }
+}
+#endif
+
+void EventTrackingContext::print(raw_ostream &OS) const {
+ for (const auto &[MBB, Tracker] : Trackers) {
+ MBB->printAsOperand(OS);
+ OS << ":\n";
+ Tracker->print(OS, /*Indent=*/2);
+ }
+}
+
+#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
+LLVM_DUMP_METHOD void EventTrackingContext::dump() const {
+ dbgs() << "\n";
+ print(dbgs());
+ dbgs() << "\n";
+}
+#endif
+
+} // namespace eventtracking
+} // namespace AMDGPU
+
+} // namespace llvm
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUEventTracking.h b/llvm/lib/Target/AMDGPU/AMDGPUEventTracking.h
new file mode 100644
index 0000000000000..c1e56fc184569
--- /dev/null
+++ b/llvm/lib/Target/AMDGPU/AMDGPUEventTracking.h
@@ -0,0 +1,354 @@
+//===- AMDGPUEventTracking.h ------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+/// \file Tracks a per-InstCounterType event timeline which preserves
+/// information about previously encountered MachineInstr and HWEvents.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIB_TARGET_AMDGPU_UTILS_AMDGPUEVENTTRACKING_H
+#define LLVM_LIB_TARGET_AMDGPU_UTILS_AMDGPUEVENTTRACKING_H
+
+#include "AMDGPUHWEvents.h"
+#include "AMDGPUWaitcntUtils.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Twine.h"
+#include <memory>
+
+namespace llvm {
+class raw_ostream;
+class MachineBasicBlock;
+class MachineOperand;
+class MachineFunction;
+
+namespace AMDGPU {
+namespace eventtracking {
+
+class EventTrackingContext;
+class EventTracker;
+
+/// FIXME: Make this a generic util?
+struct CounterInfo {
+ constexpr CounterInfo(InstCounterType T, HWEvents Events, unsigned Limit)
+ : CounterT(T), Events(Events), Limit(Limit) {}
+
+ /// Type of counter this is.
+ /// This must match the index in the container, e.g. CounterT=2 must be at
+ /// index 2.
+ InstCounterType CounterT;
+ /// HWEvents for this counter.
+ HWEvents Events;
+ /// Hardware limit for this counter.
+ unsigned Limit;
+};
+
+/// Represents entries in the \ref EventTracker.
+///
+/// Records are all uniquely identified by a \ref DynamicInstanceID. For each
+/// unique \ref DynamicInstanceID value, all \ref EventTrackerRecord that use
+/// that ID should have the same MI and Kind. This is enforced by exposing these
+/// as read-only, and making the constructor assign a new \ref DynamicInstanceID
+/// every time.
+///
+/// Only the score can change as it may be unique to each instance
+/// of \ref EventTracker that carry it.
+class EventTrackerRecord {
+public:
+ /// An always-increasing counter used to represent a dynamic instance of a
+ /// record.
+ ///
+ /// Whenever we add a new \ref EventTrackerRecord, even if it's one we already
+ /// have seen in a previous dataflow iteration, this counter is increased so
+ /// that the new record has a unique `DynamicInstanceID`.
+ using DynamicInstanceID = uint32_t;
+
+ EventTrackerRecord(EventTrackingContext &Ctx, MachineInstr *MI,
+ SingleHWEvent Kind, uint32_t Score = 0);
+
+ /// \returns the ID uniquely identifying this record across an entire
+ /// EventTrackingContext. Whenever we revisit an instruction (when iterating
+ /// until a fixpoint is reached), we give it a new ID. This is used to
+ /// represent records carried over from previous iterations of the same basic
+ /// block.
+ DynamicInstanceID getID() const { return ID; }
+
+ /// \returns the MachineInstr that originated this record.
+ MachineInstr *getMI() const { return MI; }
+
+ /// \returns the kind of record this is, as a \ref SingleHWEvent.
+ SingleHWEvent getKind() const { return Kind; }
+
+ /// \returns the score of this record.
+ uint32_t getScore() const { return Score; }
+
+ /// Sets the score of this record to \p NewScore.
+ void setScore(uint32_t NewScore) {
+ Score = NewScore;
+ assert(Score == NewScore && "Score overflow!");
+ }
+
+ void print(raw_ostream &OS, bool PrintMI = true, unsigned Indent = 0) const;
+
+#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
+ LLVM_DUMP_METHOD void dump() const;
+#endif
+
+private:
+ EventTrackerRecord(DynamicInstanceID ID, MachineInstr *MI, SingleHWEvent Kind,
+ uint32_t Score = 0)
+ : MI(MI), ID(ID), Kind(Kind) {
+ setScore(Score);
+ }
+
+ MachineInstr *MI;
+ DynamicInstanceID ID;
+ SingleHWEvent Kind;
+ // Score should already never exceed uint8_t limit in normal circumstances as
+ // most counter types only use up to 6 bits encoding for the waitcnts. 16 bit
+ // is a very generous limit, we can probably shrink that at some point.
+ uint16_t Score;
+};
+
+/// This assert serves as a reminder to be mindful of the size of the object.
+static_assert(sizeof(EventTrackerRecord) == 16,
+ "EventTrackerRecord should remain small to optimize its layout "
+ "within cache lines, for maximum iteration speed");
+
+/// Per-MBB tracking context.
+///
+/// Tracks data across the following domains:
+/// - Current value (count) of each instruction counter.
+/// - In-flight (alive) \ref EventTrackerRecord of each instruction counter.
+///
+/// This class is only responsible for tracking records for every
+/// InstCounterType. It does not deal with calculating the waitcnts nee...
[truncated]
``````````
</details>
https://github.com/llvm/llvm-project/pull/226970
More information about the llvm-commits
mailing list