MLIR  21.0.0git
Query.cpp
Go to the documentation of this file.
1 //===---- Query.cpp - -----------------------------------------------------===//
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 #include "mlir/Query/Query.h"
10 #include "QueryParser.h"
12 #include "mlir/IR/IRMapping.h"
15 #include "llvm/Support/SourceMgr.h"
16 #include "llvm/Support/raw_ostream.h"
17 
18 namespace mlir::query {
19 
20 QueryRef parse(llvm::StringRef line, const QuerySession &qs) {
21  return QueryParser::parse(line, qs);
22 }
23 
24 std::vector<llvm::LineEditor::Completion>
25 complete(llvm::StringRef line, size_t pos, const QuerySession &qs) {
26  return QueryParser::complete(line, pos, qs);
27 }
28 
29 static void printMatch(llvm::raw_ostream &os, QuerySession &qs, Operation *op,
30  const std::string &binding) {
31  auto fileLoc = op->getLoc()->findInstanceOf<FileLineColLoc>();
32  auto smloc = qs.getSourceManager().FindLocForLineAndColumn(
33  qs.getBufferId(), fileLoc.getLine(), fileLoc.getColumn());
34  qs.getSourceManager().PrintMessage(os, smloc, llvm::SourceMgr::DK_Note,
35  "\"" + binding + "\" binds here");
36 }
37 
38 // TODO: Extract into a helper function that can be reused outside query
39 // context.
40 static Operation *extractFunction(std::vector<Operation *> &ops,
41  MLIRContext *context,
42  llvm::StringRef functionName) {
43  context->loadDialect<func::FuncDialect>();
44  OpBuilder builder(context);
45 
46  // Collect data for function creation
47  std::vector<Operation *> slice;
48  std::vector<Value> values;
49  std::vector<Type> outputTypes;
50 
51  for (auto *op : ops) {
52  // Return op's operands are propagated, but the op itself isn't needed.
53  if (!isa<func::ReturnOp>(op))
54  slice.push_back(op);
55 
56  // All results are returned by the extracted function.
57  llvm::append_range(outputTypes, op->getResults().getTypes());
58 
59  // Track all values that need to be taken as input to function.
60  llvm::append_range(values, op->getOperands());
61  }
62 
63  // Create the function
64  FunctionType funcType =
65  builder.getFunctionType(TypeRange(ValueRange(values)), outputTypes);
66  auto loc = builder.getUnknownLoc();
67  func::FuncOp funcOp = func::FuncOp::create(loc, functionName, funcType);
68 
69  builder.setInsertionPointToEnd(funcOp.addEntryBlock());
70 
71  // Map original values to function arguments
72  IRMapping mapper;
73  for (const auto &arg : llvm::enumerate(values))
74  mapper.map(arg.value(), funcOp.getArgument(arg.index()));
75 
76  // Clone operations and build function body
77  std::vector<Operation *> clonedOps;
78  std::vector<Value> clonedVals;
79  for (Operation *slicedOp : slice) {
80  Operation *clonedOp =
81  clonedOps.emplace_back(builder.clone(*slicedOp, mapper));
82  clonedVals.insert(clonedVals.end(), clonedOp->result_begin(),
83  clonedOp->result_end());
84  }
85  // Add return operation
86  builder.create<func::ReturnOp>(loc, clonedVals);
87 
88  // Remove unused function arguments
89  size_t currentIndex = 0;
90  while (currentIndex < funcOp.getNumArguments()) {
91  if (funcOp.getArgument(currentIndex).use_empty())
92  funcOp.eraseArgument(currentIndex);
93  else
94  ++currentIndex;
95  }
96 
97  return funcOp;
98 }
99 
100 Query::~Query() = default;
101 
102 LogicalResult InvalidQuery::run(llvm::raw_ostream &os, QuerySession &qs) const {
103  os << errStr << "\n";
104  return mlir::failure();
105 }
106 
107 LogicalResult NoOpQuery::run(llvm::raw_ostream &os, QuerySession &qs) const {
108  return mlir::success();
109 }
110 
111 LogicalResult HelpQuery::run(llvm::raw_ostream &os, QuerySession &qs) const {
112  os << "Available commands:\n\n"
113  " match MATCHER, m MATCHER "
114  "Match the mlir against the given matcher.\n"
115  " quit "
116  "Terminates the query session.\n\n";
117  return mlir::success();
118 }
119 
120 LogicalResult QuitQuery::run(llvm::raw_ostream &os, QuerySession &qs) const {
121  qs.terminate = true;
122  return mlir::success();
123 }
124 
125 LogicalResult MatchQuery::run(llvm::raw_ostream &os, QuerySession &qs) const {
126  Operation *rootOp = qs.getRootOp();
127  int matchCount = 0;
128  std::vector<Operation *> matches =
130 
131  // An extract call is recognized by considering if the matcher has a name.
132  // TODO: Consider making the extract more explicit.
133  if (matcher.hasFunctionName()) {
134  auto functionName = matcher.getFunctionName();
135  Operation *function =
136  extractFunction(matches, rootOp->getContext(), functionName);
137  os << "\n" << *function << "\n\n";
138  function->erase();
139  return mlir::success();
140  }
141 
142  os << "\n";
143  for (Operation *op : matches) {
144  os << "Match #" << ++matchCount << ":\n\n";
145  // Placeholder "root" binding for the initial draft.
146  printMatch(os, qs, op, "root");
147  }
148  os << matchCount << (matchCount == 1 ? " match.\n\n" : " matches.\n\n");
149 
150  return mlir::success();
151 }
152 
153 } // namespace mlir::query
An instance of this location represents a tuple of file, line number, and column number.
Definition: Location.h:164
This is a utility class for mapping one set of IR entities to another.
Definition: IRMapping.h:26
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition: IRMapping.h:30
T findInstanceOf()
Return an instance of the given location type if one is nested under the current location.
Definition: Location.h:44
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
void loadDialect()
Load a dialect in the context.
Definition: MLIRContext.h:107
This class helps build Operations.
Definition: Builders.h:205
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
result_iterator result_begin()
Definition: Operation.h:413
MLIRContext * getContext()
Return the context this operation is associated with.
Definition: Operation.h:216
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, OpaqueProperties properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Definition: Operation.cpp:67
result_iterator result_end()
Definition: Operation.h:414
This class provides an abstraction over the various different ranges of value types.
Definition: TypeRange.h:37
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:387
static QueryRef parse(llvm::StringRef line, const QuerySession &qs)
static std::vector< llvm::LineEditor::Completion > complete(llvm::StringRef line, size_t pos, const QuerySession &qs)
llvm::SourceMgr & getSourceManager() const
Definition: QuerySession.h:29
static std::vector< Operation * > getMatches(Operation *root, DynMatcher matcher)
Definition: MatchFinder.h:25
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:344
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
Definition: Query.cpp:20
static Operation * extractFunction(std::vector< Operation * > &ops, MLIRContext *context, llvm::StringRef functionName)
Definition: Query.cpp:40
llvm::IntrusiveRefCntPtr< Query > QueryRef
Definition: Query.h:36
std::vector< llvm::LineEditor::Completion > complete(llvm::StringRef line, size_t pos, const QuerySession &qs)
Definition: Query.cpp:25
static void printMatch(llvm::raw_ostream &os, QuerySession &qs, Operation *op, const std::string &binding)
Definition: Query.cpp:29
llvm::LogicalResult run(llvm::raw_ostream &os, QuerySession &qs) const override
Definition: Query.cpp:111
llvm::LogicalResult run(llvm::raw_ostream &os, QuerySession &qs) const override
Definition: Query.cpp:102
std::string errStr
Definition: Query.h:50
llvm::LogicalResult run(llvm::raw_ostream &os, QuerySession &qs) const override
Definition: Query.cpp:125
const matcher::DynMatcher matcher
Definition: Query.h:97
llvm::LogicalResult run(llvm::raw_ostream &os, QuerySession &qs) const override
Definition: Query.cpp:107
llvm::LogicalResult run(llvm::raw_ostream &os, QuerySession &qs) const override
Definition: Query.cpp:120