MLIR  19.0.0git
CLOptionsSetup.cpp
Go to the documentation of this file.
1 //===- CLOptionsSetup.cpp - Helpers to setup debug CL options ---*- 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 
10 
11 #include "mlir/Debug/Counter.h"
16 #include "mlir/IR/MLIRContext.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/ToolOutputFile.h"
20 
21 using namespace mlir;
22 using namespace mlir::tracing;
23 using namespace llvm;
24 
25 namespace {
26 struct DebugConfigCLOptions : public DebugConfig {
27  DebugConfigCLOptions() {
28  static cl::opt<std::string, /*ExternalStorage=*/true> logActionsTo{
29  "log-actions-to",
30  cl::desc("Log action execution to a file, or stderr if "
31  " '-' is passed"),
32  cl::location(logActionsToFlag)};
33 
34  static cl::opt<std::string, /*ExternalStorage=*/true> profileActionsTo{
35  "profile-actions-to",
36  cl::desc("Profile action execution to a file, or stderr if "
37  " '-' is passed"),
38  cl::location(profileActionsToFlag)};
39 
40  static cl::list<std::string> logActionLocationFilter(
41  "log-mlir-actions-filter",
42  cl::desc(
43  "Comma separated list of locations to filter actions from logging"),
44  cl::CommaSeparated,
45  cl::cb<void, std::string>([&](const std::string &location) {
46  static bool registerOnce = [&] {
47  addLogActionLocFilter(&locBreakpointManager);
48  return true;
49  }();
50  (void)registerOnce;
51  static std::vector<std::string> locations;
52  locations.push_back(location);
53  StringRef locStr = locations.back();
54 
55  // Parse the individual location filters and set the breakpoints.
56  auto diag = [](Twine msg) { llvm::errs() << msg << "\n"; };
57  auto locBreakpoint =
59  if (failed(locBreakpoint)) {
60  llvm::errs() << "Invalid location filter: " << locStr << "\n";
61  exit(1);
62  }
63  auto [file, line, col] = *locBreakpoint;
64  locBreakpointManager.addBreakpoint(file, line, col);
65  }));
66  }
67  tracing::FileLineColLocBreakpointManager locBreakpointManager;
68 };
69 
70 } // namespace
71 
72 static ManagedStatic<DebugConfigCLOptions> clOptionsConfig;
74 
76 
78 public:
79  Impl(MLIRContext &context, const DebugConfig &config) {
80  if (config.getLogActionsTo().empty() &&
81  config.getProfileActionsTo().empty() &&
82  !config.isDebuggerActionHookEnabled()) {
85  return;
86  }
87  errs() << "ExecutionContext registered on the context";
89  emitError(UnknownLoc::get(&context),
90  "Debug counters are incompatible with --log-actions-to and "
91  "--mlir-enable-debugger-hook options and are disabled");
92  if (!config.getLogActionsTo().empty()) {
93  std::string errorMessage;
94  logActionsFile = openOutputFile(config.getLogActionsTo(), &errorMessage);
95  if (!logActionsFile) {
96  emitError(UnknownLoc::get(&context),
97  "Opening file for --log-actions-to failed: ")
98  << errorMessage << "\n";
99  return;
100  }
101  logActionsFile->keep();
102  raw_fd_ostream &logActionsStream = logActionsFile->os();
103  actionLogger = std::make_unique<tracing::ActionLogger>(logActionsStream);
104  for (const auto *locationBreakpoint : config.getLogActionsLocFilters())
105  actionLogger->addBreakpointManager(locationBreakpoint);
106  executionContext.registerObserver(actionLogger.get());
107  }
108 
109  if (!config.getProfileActionsTo().empty()) {
110  std::string errorMessage;
111  profileActionsFile =
112  openOutputFile(config.getProfileActionsTo(), &errorMessage);
113  if (!profileActionsFile) {
114  emitError(UnknownLoc::get(&context),
115  "Opening file for --profile-actions-to failed: ")
116  << errorMessage << "\n";
117  return;
118  }
119  profileActionsFile->keep();
120  raw_fd_ostream &profileActionsStream = profileActionsFile->os();
121  actionProfiler =
122  std::make_unique<tracing::ActionProfiler>(profileActionsStream);
123  executionContext.registerObserver(actionProfiler.get());
124  }
125 
126  if (config.isDebuggerActionHookEnabled()) {
127  errs() << " (with Debugger hook)";
128  setupDebuggerExecutionContextHook(executionContext);
129  }
130  errs() << "\n";
131  context.registerActionHandler(executionContext);
132  }
133 
134 private:
135  std::unique_ptr<ToolOutputFile> logActionsFile;
136  tracing::ExecutionContext executionContext;
137  std::unique_ptr<tracing::ActionLogger> actionLogger;
138  std::vector<std::unique_ptr<tracing::FileLineColLocBreakpoint>>
139  locationBreakpoints;
140  std::unique_ptr<ToolOutputFile> profileActionsFile;
141  std::unique_ptr<tracing::ActionProfiler> actionProfiler;
142 };
143 
145  const DebugConfig &config)
146  : impl(std::make_unique<Impl>(context, config)) {}
147 
static ManagedStatic< DebugConfigCLOptions > clOptionsConfig
static std::string diag(const llvm::Value &value)
Impl(MLIRContext &context, const DebugConfig &config)
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
void registerActionHandler(HandlerTy handler)
Register a handler for handling actions that are dispatched through this context.
static DebugConfig createFromCLOptions()
Create a new config with the default set from the CL options.
StringRef getLogActionsTo() const
Get the filename to use for logging actions.
StringRef getProfileActionsTo() const
Get the filename to use for profiling actions.
static void registerCLOptions()
Register the options as global LLVM command line options.
bool isDebuggerActionHookEnabled() const
Return true if the debugger action hook is enabled.
ArrayRef< tracing::BreakpointManager * > getLogActionsLocFilters() const
Get the location breakpoint managers to use to filter out action logging.
This class implements an action handler that attaches a counter value to debug actions and enables/di...
Definition: Counter.h:29
static bool isActivated()
Returns true if any of the CL options are activated.
The ExecutionContext is the main orchestration of the infrastructure, it acts as a handler in the MLI...
This breakpoint manager is responsible for matching FileLineColLocBreakpoint.
static FailureOr< std::tuple< StringRef, int64_t, int64_t > > parseFromString(StringRef str, llvm::function_ref< void(Twine)> diag=[](Twine) {})
Parse a string representation in the form of "<file>:<line>:<col>".
InstallDebugHandler(MLIRContext &context, const DebugConfig &config)
Include the generated interface declarations.
Definition: CallGraph.h:229
Include the generated interface declarations.
void setupDebuggerExecutionContextHook(tracing::ExecutionContext &executionContext)
std::unique_ptr< llvm::ToolOutputFile > openOutputFile(llvm::StringRef outputFilename, std::string *errorMessage=nullptr)
Open the file specified by its name for writing.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
bool failed(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a failure value.
Definition: LogicalResult.h:72