LLVM  14.0.0git
PassTimingInfo.cpp
Go to the documentation of this file.
1 //===- PassTimingInfo.cpp - LLVM Pass Timing Implementation ---------------===//
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 // This file implements the LLVM Pass Timing infrastructure for both
10 // new and legacy pass managers.
11 //
12 // PassTimingInfo Class - This class is used to calculate information about the
13 // amount of time each pass takes to execute. This only happens when
14 // -time-passes is enabled on the command line.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/IR/PassTimingInfo.h"
19 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Pass.h"
23 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Mutex.h"
27 #include "llvm/Support/TypeName.h"
29 #include <string>
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "time-passes"
34 
35 namespace llvm {
36 
37 bool TimePassesIsEnabled = false;
38 bool TimePassesPerRun = false;
39 
42  cl::desc("Time each pass, printing elapsed time for each on exit"));
43 
45  "time-passes-per-run", cl::location(TimePassesPerRun), cl::Hidden,
46  cl::desc("Time each pass run, printing elapsed time for each run on exit"),
47  cl::callback([](const bool &) { TimePassesIsEnabled = true; }));
48 
49 namespace {
50 namespace legacy {
51 
52 //===----------------------------------------------------------------------===//
53 // Legacy pass manager's PassTimingInfo implementation
54 
55 /// Provides an interface for collecting pass timing information.
56 ///
57 /// It was intended to be generic but now we decided to split
58 /// interfaces completely. This is now exclusively for legacy-pass-manager use.
59 class PassTimingInfo {
60 public:
61  using PassInstanceID = void *;
62 
63 private:
64  StringMap<unsigned> PassIDCountMap; ///< Map that counts instances of passes
65  DenseMap<PassInstanceID, std::unique_ptr<Timer>> TimingData; ///< timers for pass instances
66  TimerGroup TG;
67 
68 public:
69  /// Default constructor for yet-inactive timeinfo.
70  /// Use \p init() to activate it.
71  PassTimingInfo();
72 
73  /// Print out timing information and release timers.
74  ~PassTimingInfo();
75 
76  /// Initializes the static \p TheTimeInfo member to a non-null value when
77  /// -time-passes is enabled. Leaves it null otherwise.
78  ///
79  /// This method may be called multiple times.
80  static void init();
81 
82  /// Prints out timing information and then resets the timers.
83  /// By default it uses the stream created by CreateInfoOutputFile().
84  void print(raw_ostream *OutStream = nullptr);
85 
86  /// Returns the timer for the specified pass if it exists.
87  Timer *getPassTimer(Pass *, PassInstanceID);
88 
89  static PassTimingInfo *TheTimeInfo;
90 
91 private:
92  Timer *newPassTimer(StringRef PassID, StringRef PassDesc);
93 };
94 
95 static ManagedStatic<sys::SmartMutex<true>> TimingInfoMutex;
96 
97 PassTimingInfo::PassTimingInfo()
98  : TG("pass", "... Pass execution timing report ...") {}
99 
100 PassTimingInfo::~PassTimingInfo() {
101  // Deleting the timers accumulates their info into the TG member.
102  // Then TG member is (implicitly) deleted, actually printing the report.
103  TimingData.clear();
104 }
105 
106 void PassTimingInfo::init() {
107  if (!TimePassesIsEnabled || TheTimeInfo)
108  return;
109 
110  // Constructed the first time this is called, iff -time-passes is enabled.
111  // This guarantees that the object will be constructed after static globals,
112  // thus it will be destroyed before them.
114  TheTimeInfo = &*TTI;
115 }
116 
117 /// Prints out timing information and then resets the timers.
118 void PassTimingInfo::print(raw_ostream *OutStream) {
119  TG.print(OutStream ? *OutStream : *CreateInfoOutputFile(), true);
120 }
121 
122 Timer *PassTimingInfo::newPassTimer(StringRef PassID, StringRef PassDesc) {
123  unsigned &num = PassIDCountMap[PassID];
124  num++;
125  // Appending description with a pass-instance number for all but the first one
126  std::string PassDescNumbered =
127  num <= 1 ? PassDesc.str() : formatv("{0} #{1}", PassDesc, num).str();
128  return new Timer(PassID, PassDescNumbered, TG);
129 }
130 
131 Timer *PassTimingInfo::getPassTimer(Pass *P, PassInstanceID Pass) {
132  if (P->getAsPMDataManager())
133  return nullptr;
134 
135  init();
136  sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
137  std::unique_ptr<Timer> &T = TimingData[Pass];
138 
139  if (!T) {
140  StringRef PassName = P->getPassName();
141  StringRef PassArgument;
142  if (const PassInfo *PI = Pass::lookupPassInfo(P->getPassID()))
143  PassArgument = PI->getPassArgument();
144  T.reset(newPassTimer(PassArgument.empty() ? PassName : PassArgument, PassName));
145  }
146  return T.get();
147 }
148 
149 PassTimingInfo *PassTimingInfo::TheTimeInfo;
150 } // namespace legacy
151 } // namespace
152 
155  if (legacy::PassTimingInfo::TheTimeInfo)
156  return legacy::PassTimingInfo::TheTimeInfo->getPassTimer(P, P);
157  return nullptr;
158 }
159 
160 /// If timing is enabled, report the times collected up to now and then reset
161 /// them.
163  if (legacy::PassTimingInfo::TheTimeInfo)
164  legacy::PassTimingInfo::TheTimeInfo->print(OutStream);
165 }
166 
167 //===----------------------------------------------------------------------===//
168 // Pass timing handling for the New Pass Manager
169 //===----------------------------------------------------------------------===//
170 
171 /// Returns the timer for the specified pass invocation of \p PassID.
172 /// Each time it creates a new timer.
174  if (!PerRun) {
175  TimerVector &Timers = TimingData[PassID];
176  if (Timers.size() == 0)
177  Timers.emplace_back(new Timer(PassID, PassID, TG));
178  return *Timers.front();
179  }
180 
181  // Take a vector of Timers created for this \p PassID and append
182  // one more timer to it.
183  TimerVector &Timers = TimingData[PassID];
184  unsigned Count = Timers.size() + 1;
185 
186  std::string FullDesc = formatv("{0} #{1}", PassID, Count).str();
187 
188  Timer *T = new Timer(PassID, FullDesc, TG);
189  Timers.emplace_back(T);
190  assert(Count == Timers.size() && "sanity check");
191 
192  return *T;
193 }
194 
196  : TG("pass", "... Pass execution timing report ..."), Enabled(Enabled),
197  PerRun(PerRun) {}
198 
201 
203  OutStream = &Out;
204 }
205 
207  if (!Enabled)
208  return;
209  TG.print(OutStream ? *OutStream : *CreateInfoOutputFile(), true);
210 }
211 
212 LLVM_DUMP_METHOD void TimePassesHandler::dump() const {
213  dbgs() << "Dumping timers for " << getTypeName<TimePassesHandler>()
214  << ":\n\tRunning:\n";
215  for (auto &I : TimingData) {
216  StringRef PassID = I.getKey();
217  const TimerVector& MyTimers = I.getValue();
218  for (unsigned idx = 0; idx < MyTimers.size(); idx++) {
219  const Timer* MyTimer = MyTimers[idx].get();
220  if (MyTimer && MyTimer->isRunning())
221  dbgs() << "\tTimer " << MyTimer << " for pass " << PassID << "(" << idx << ")\n";
222  }
223  }
224  dbgs() << "\tTriggered:\n";
225  for (auto &I : TimingData) {
226  StringRef PassID = I.getKey();
227  const TimerVector& MyTimers = I.getValue();
228  for (unsigned idx = 0; idx < MyTimers.size(); idx++) {
229  const Timer* MyTimer = MyTimers[idx].get();
230  if (MyTimer && MyTimer->hasTriggered() && !MyTimer->isRunning())
231  dbgs() << "\tTimer " << MyTimer << " for pass " << PassID << "(" << idx << ")\n";
232  }
233  }
234 }
235 
236 void TimePassesHandler::startTimer(StringRef PassID) {
237  Timer &MyTimer = getPassTimer(PassID);
238  TimerStack.push_back(&MyTimer);
239  if (!MyTimer.isRunning())
240  MyTimer.startTimer();
241 }
242 
243 void TimePassesHandler::stopTimer(StringRef PassID) {
244  assert(TimerStack.size() > 0 && "empty stack in popTimer");
245  Timer *MyTimer = TimerStack.pop_back_val();
246  assert(MyTimer && "timer should be present");
247  if (MyTimer->isRunning())
248  MyTimer->stopTimer();
249 }
250 
251 void TimePassesHandler::runBeforePass(StringRef PassID) {
252  if (isSpecialPass(PassID,
253  {"PassManager", "PassAdaptor", "AnalysisManagerProxy"}))
254  return;
255 
256  startTimer(PassID);
257 
258  LLVM_DEBUG(dbgs() << "after runBeforePass(" << PassID << ")\n");
259  LLVM_DEBUG(dump());
260 }
261 
262 void TimePassesHandler::runAfterPass(StringRef PassID) {
263  if (isSpecialPass(PassID,
264  {"PassManager", "PassAdaptor", "AnalysisManagerProxy"}))
265  return;
266 
267  stopTimer(PassID);
268 
269  LLVM_DEBUG(dbgs() << "after runAfterPass(" << PassID << ")\n");
270  LLVM_DEBUG(dump());
271 }
272 
274  if (!Enabled)
275  return;
276 
278  [this](StringRef P, Any) { this->runBeforePass(P); });
280  [this](StringRef P, Any, const PreservedAnalyses &) {
281  this->runAfterPass(P);
282  });
284  [this](StringRef P, const PreservedAnalyses &) {
285  this->runAfterPass(P);
286  });
288  [this](StringRef P, Any) { this->runBeforePass(P); });
290  [this](StringRef P, Any) { this->runAfterPass(P); });
291 }
292 
293 } // namespace llvm
llvm::PreservedAnalyses
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:155
LLVM_DUMP_METHOD
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:491
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
llvm::reportAndResetTimings
void reportAndResetTimings(raw_ostream *OutStream=nullptr)
If -time-passes has been specified, report the timings immediately and then reset the timers to zero.
Definition: PassTimingInfo.cpp:162
llvm::StringRef::empty
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:153
Pass
print lazy value Lazy Value Info Printer Pass
Definition: LazyValueInfo.cpp:1966
print
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Definition: ArchiveWriter.cpp:147
llvm::Timer::hasTriggered
bool hasTriggered() const
Check if startTimer() has ever been called on this timer.
Definition: Timer.h:122
llvm::cl::location
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:459
P
This currently compiles esp xmm0 movsd esp eax eax esp ret We should use not the dag combiner This is because dagcombine2 needs to be able to see through the X86ISD::Wrapper which DAGCombine can t really do The code for turning x load into a single vector load is target independent and should be moved to the dag combiner The code for turning x load into a vector load can only handle a direct load from a global or a direct load from the stack It should be generalized to handle any load from P
Definition: README-SSE.txt:411
Pass.h
llvm::PassInstrumentationCallbacks::registerBeforeNonSkippedPassCallback
void registerBeforeNonSkippedPassCallback(CallableT C)
Definition: PassInstrumentation.h:106
llvm::TimerGroup::print
void print(raw_ostream &OS, bool ResetAfterPrint=false)
Print any started timers in this group, optionally resetting timers after printing them.
Definition: Timer.cpp:427
Statistic.h
ManagedStatic.h
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:143
llvm::Timer
This class is used to track the amount of time spent between invocations of its startTimer()/stopTime...
Definition: Timer.h:82
llvm::TimePassesIsEnabled
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: PassTimingInfo.cpp:37
PIC
PassInstrumentationCallbacks PIC
Definition: PassBuilderBindings.cpp:55
llvm::PassInfo
PassInfo class - An instance of this class exists for every pass known by the system,...
Definition: PassInfo.h:30
T
#define T
Definition: Mips16ISelLowering.cpp:341
llvm::TimePassesHandler::TimePassesHandler
TimePassesHandler()
Definition: PassTimingInfo.cpp:199
llvm::Timer::startTimer
void startTimer()
Start the timer running.
Definition: Timer.cpp:190
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
llvm::CreateInfoOutputFile
std::unique_ptr< raw_fd_ostream > CreateInfoOutputFile()
Return a file stream to print our output on.
Definition: Timer.cpp:96
llvm::TimePassesHandler::print
void print()
Prints out timing information and then resets the timers.
Definition: PassTimingInfo.cpp:206
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::Lock
static sys::Mutex Lock
Definition: NVPTXUtilities.cpp:39
llvm::Timer::isRunning
bool isRunning() const
Check if the timer is currently running.
Definition: Timer.h:119
PassTimingInfo.h
CommandLine.h
llvm::formatv
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
Definition: FormatVariadic.h:250
llvm::EnableTimingPerRun
static cl::opt< bool, true > EnableTimingPerRun("time-passes-per-run", cl::location(TimePassesPerRun), cl::Hidden, cl::desc("Time each pass run, printing elapsed time for each run on exit"), cl::callback([](const bool &) { TimePassesIsEnabled=true;}))
PassInstrumentation.h
llvm::ManagedStatic
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
llvm::isSpecialPass
bool isSpecialPass(StringRef PassID, const std::vector< StringRef > &Specials)
Definition: PassInstrumentation.cpp:33
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
FormatVariadic.h
llvm::StringRef::str
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:245
llvm::StringMap< unsigned >
llvm::PassInstrumentationCallbacks::registerBeforeAnalysisCallback
void registerBeforeAnalysisCallback(CallableT C)
Definition: PassInstrumentation.h:120
llvm::TimePassesHandler::setOutStream
void setOutStream(raw_ostream &OutStream)
Set a custom output stream for subsequent reporting.
Definition: PassTimingInfo.cpp:202
llvm::cl::opt
Definition: CommandLine.h:1434
llvm::DenseMap
Definition: DenseMap.h:714
llvm::getPassTimer
Timer * getPassTimer(Pass *)
Request the timer for this legacy-pass-manager's pass instance.
Definition: PassTimingInfo.cpp:153
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::sys::SmartScopedLock
std::lock_guard< SmartMutex< mt_only > > SmartScopedLock
Definition: Mutex.h:71
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::Timer::stopTimer
void stopTimer()
Stop the timer.
Definition: Timer.cpp:197
TypeName.h
llvm::PassInstrumentationCallbacks::registerAfterAnalysisCallback
void registerAfterAnalysisCallback(CallableT C)
Definition: PassInstrumentation.h:125
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
llvm::TimePassesHandler::registerCallbacks
void registerCallbacks(PassInstrumentationCallbacks &PIC)
Definition: PassTimingInfo.cpp:273
Mutex.h
llvm::PassInstrumentationCallbacks::registerAfterPassInvalidatedCallback
void registerAfterPassInvalidatedCallback(CallableT C)
Definition: PassInstrumentation.h:115
llvm::TimePassesPerRun
bool TimePassesPerRun
If TimePassesPerRun is true, there would be one line of report for each pass invocation.
Definition: PassTimingInfo.cpp:38
llvm::Any
Definition: Any.h:26
llvm::TimerGroup
The TimerGroup class is used to group together related timers into a single report that is printed wh...
Definition: Timer.h:176
Enabled
static bool Enabled
Definition: Statistic.cpp:46
TTI
const DataLayout const TargetTransformInfo * TTI
Definition: InferAddressSpaces.cpp:242
llvm::PassInstrumentationCallbacks::registerAfterPassCallback
void registerAfterPassCallback(CallableT C)
Definition: PassInstrumentation.h:110
llvm::Pass
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:91
llvm::PassInstrumentationCallbacks
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
Definition: PassInstrumentation.h:66
llvm::TimePassesHandler
This class implements -time-passes functionality for new pass manager.
Definition: PassTimingInfo.h:46
llvm::EnableTiming
static cl::opt< bool, true > EnableTiming("time-passes", cl::location(TimePassesIsEnabled), cl::Hidden, cl::desc("Time each pass, printing elapsed time for each on exit"))
llvm::cl::callback
cb< typename detail::callback_traits< F >::result_type, typename detail::callback_traits< F >::arg_type > callback(F CB)
Definition: CommandLine.h:512
llvm::cl::desc
Definition: CommandLine.h:414
raw_ostream.h
Debug.h
PassName
static const char PassName[]
Definition: X86LowerAMXIntrinsics.cpp:669