MLIR  22.0.0git
SCFToEmitC.cpp
Go to the documentation of this file.
1 //===- SCFToEmitC.cpp - SCF to EmitC conversion ---------------------------===//
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 a pass to convert scf.if ops into emitc ops.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 
19 #include "mlir/IR/Builders.h"
20 #include "mlir/IR/MLIRContext.h"
21 #include "mlir/IR/PatternMatch.h"
23 #include "mlir/Transforms/Passes.h"
24 
25 namespace mlir {
26 #define GEN_PASS_DEF_SCFTOEMITC
27 #include "mlir/Conversion/Passes.h.inc"
28 } // namespace mlir
29 
30 using namespace mlir;
31 using namespace mlir::scf;
32 
33 namespace {
34 
35 /// Implement the interface to convert SCF to EmitC.
36 struct SCFToEmitCDialectInterface : public ConvertToEmitCPatternInterface {
38 
39  /// Hook for derived dialect interface to provide conversion patterns
40  /// and mark dialect legal for the conversion target.
41  void populateConvertToEmitCConversionPatterns(
42  ConversionTarget &target, TypeConverter &typeConverter,
43  RewritePatternSet &patterns) const final {
44  populateEmitCSizeTTypeConversions(typeConverter);
46  }
47 };
48 } // namespace
49 
51  registry.addExtension(+[](MLIRContext *ctx, scf::SCFDialect *dialect) {
52  dialect->addInterfaces<SCFToEmitCDialectInterface>();
53  });
54 }
55 
56 namespace {
57 
58 struct SCFToEmitCPass : public impl::SCFToEmitCBase<SCFToEmitCPass> {
59  void runOnOperation() override;
60 };
61 
62 // Lower scf::for to emitc::for, implementing result values using
63 // emitc::variable's updated within the loop body.
64 struct ForLowering : public OpConversionPattern<ForOp> {
66 
67  LogicalResult
68  matchAndRewrite(ForOp forOp, OpAdaptor adaptor,
69  ConversionPatternRewriter &rewriter) const override;
70 };
71 
72 // Create an uninitialized emitc::variable op for each result of the given op.
73 template <typename T>
74 static LogicalResult
75 createVariablesForResults(T op, const TypeConverter *typeConverter,
76  ConversionPatternRewriter &rewriter,
77  SmallVector<Value> &resultVariables) {
78  if (!op.getNumResults())
79  return success();
80 
81  Location loc = op->getLoc();
82  MLIRContext *context = op.getContext();
83 
84  OpBuilder::InsertionGuard guard(rewriter);
85  rewriter.setInsertionPoint(op);
86 
87  for (OpResult result : op.getResults()) {
88  Type resultType = typeConverter->convertType(result.getType());
89  if (!resultType)
90  return rewriter.notifyMatchFailure(op, "result type conversion failed");
91  Type varType = emitc::LValueType::get(resultType);
92  emitc::OpaqueAttr noInit = emitc::OpaqueAttr::get(context, "");
93  emitc::VariableOp var =
94  emitc::VariableOp::create(rewriter, loc, varType, noInit);
95  resultVariables.push_back(var);
96  }
97 
98  return success();
99 }
100 
101 // Create a series of assign ops assigning given values to given variables at
102 // the current insertion point of given rewriter.
103 static void assignValues(ValueRange values, ValueRange variables,
104  ConversionPatternRewriter &rewriter, Location loc) {
105  for (auto [value, var] : llvm::zip(values, variables))
106  emitc::AssignOp::create(rewriter, loc, var, value);
107 }
108 
109 SmallVector<Value> loadValues(const SmallVector<Value> &variables,
110  PatternRewriter &rewriter, Location loc) {
111  return llvm::map_to_vector<>(variables, [&](Value var) {
112  Type type = cast<emitc::LValueType>(var.getType()).getValueType();
113  return emitc::LoadOp::create(rewriter, loc, type, var).getResult();
114  });
115 }
116 
117 static LogicalResult lowerYield(Operation *op, ValueRange resultVariables,
118  ConversionPatternRewriter &rewriter,
119  scf::YieldOp yield) {
120  Location loc = yield.getLoc();
121 
122  OpBuilder::InsertionGuard guard(rewriter);
123  rewriter.setInsertionPoint(yield);
124 
125  SmallVector<Value> yieldOperands;
126  if (failed(rewriter.getRemappedValues(yield.getOperands(), yieldOperands))) {
127  return rewriter.notifyMatchFailure(op, "failed to lower yield operands");
128  }
129 
130  assignValues(yieldOperands, resultVariables, rewriter, loc);
131 
132  emitc::YieldOp::create(rewriter, loc);
133  rewriter.eraseOp(yield);
134 
135  return success();
136 }
137 
138 // Lower the contents of an scf::if/scf::index_switch regions to an
139 // emitc::if/emitc::switch region. The contents of the lowering region is
140 // moved into the respective lowered region, but the scf::yield is replaced not
141 // only with an emitc::yield, but also with a sequence of emitc::assign ops that
142 // set the yielded values into the result variables.
143 static LogicalResult lowerRegion(Operation *op, ValueRange resultVariables,
144  ConversionPatternRewriter &rewriter,
145  Region &region, Region &loweredRegion) {
146  rewriter.inlineRegionBefore(region, loweredRegion, loweredRegion.end());
147  Operation *terminator = loweredRegion.back().getTerminator();
148  return lowerYield(op, resultVariables, rewriter,
149  cast<scf::YieldOp>(terminator));
150 }
151 
152 LogicalResult
153 ForLowering::matchAndRewrite(ForOp forOp, OpAdaptor adaptor,
154  ConversionPatternRewriter &rewriter) const {
155  Location loc = forOp.getLoc();
156 
157  // Create an emitc::variable op for each result. These variables will be
158  // assigned to by emitc::assign ops within the loop body.
159  SmallVector<Value> resultVariables;
160  if (failed(createVariablesForResults(forOp, getTypeConverter(), rewriter,
161  resultVariables)))
162  return rewriter.notifyMatchFailure(forOp,
163  "create variables for results failed");
164 
165  assignValues(adaptor.getInitArgs(), resultVariables, rewriter, loc);
166 
167  emitc::ForOp loweredFor =
168  emitc::ForOp::create(rewriter, loc, adaptor.getLowerBound(),
169  adaptor.getUpperBound(), adaptor.getStep());
170 
171  Block *loweredBody = loweredFor.getBody();
172 
173  // Erase the auto-generated terminator for the lowered for op.
174  rewriter.eraseOp(loweredBody->getTerminator());
175 
176  IRRewriter::InsertPoint ip = rewriter.saveInsertionPoint();
177  rewriter.setInsertionPointToEnd(loweredBody);
178 
179  SmallVector<Value> iterArgsValues =
180  loadValues(resultVariables, rewriter, loc);
181 
182  rewriter.restoreInsertionPoint(ip);
183 
184  // Convert the original region types into the new types by adding unrealized
185  // casts in the beginning of the loop. This performs the conversion in place.
186  if (failed(rewriter.convertRegionTypes(&forOp.getRegion(),
187  *getTypeConverter(), nullptr))) {
188  return rewriter.notifyMatchFailure(forOp, "region types conversion failed");
189  }
190 
191  // Register the replacements for the block arguments and inline the body of
192  // the scf.for loop into the body of the emitc::for loop.
193  Block *scfBody = &(forOp.getRegion().front());
194  SmallVector<Value> replacingValues;
195  replacingValues.push_back(loweredFor.getInductionVar());
196  replacingValues.append(iterArgsValues.begin(), iterArgsValues.end());
197  rewriter.mergeBlocks(scfBody, loweredBody, replacingValues);
198 
199  auto result = lowerYield(forOp, resultVariables, rewriter,
200  cast<scf::YieldOp>(loweredBody->getTerminator()));
201 
202  if (failed(result)) {
203  return result;
204  }
205 
206  // Load variables into SSA values after the for loop.
207  SmallVector<Value> resultValues = loadValues(resultVariables, rewriter, loc);
208 
209  rewriter.replaceOp(forOp, resultValues);
210  return success();
211 }
212 
213 // Lower scf::if to emitc::if, implementing result values as emitc::variable's
214 // updated within the then and else regions.
215 struct IfLowering : public OpConversionPattern<IfOp> {
217 
218  LogicalResult
219  matchAndRewrite(IfOp ifOp, OpAdaptor adaptor,
220  ConversionPatternRewriter &rewriter) const override;
221 };
222 
223 } // namespace
224 
225 LogicalResult
226 IfLowering::matchAndRewrite(IfOp ifOp, OpAdaptor adaptor,
227  ConversionPatternRewriter &rewriter) const {
228  Location loc = ifOp.getLoc();
229 
230  // Create an emitc::variable op for each result. These variables will be
231  // assigned to by emitc::assign ops within the then & else regions.
232  SmallVector<Value> resultVariables;
233  if (failed(createVariablesForResults(ifOp, getTypeConverter(), rewriter,
234  resultVariables)))
235  return rewriter.notifyMatchFailure(ifOp,
236  "create variables for results failed");
237 
238  // Utility function to lower the contents of an scf::if region to an emitc::if
239  // region. The contents of the scf::if regions is moved into the respective
240  // emitc::if regions, but the scf::yield is replaced not only with an
241  // emitc::yield, but also with a sequence of emitc::assign ops that set the
242  // yielded values into the result variables.
243  auto lowerRegion = [&resultVariables, &rewriter,
244  &ifOp](Region &region, Region &loweredRegion) {
245  rewriter.inlineRegionBefore(region, loweredRegion, loweredRegion.end());
246  Operation *terminator = loweredRegion.back().getTerminator();
247  auto result = lowerYield(ifOp, resultVariables, rewriter,
248  cast<scf::YieldOp>(terminator));
249  if (failed(result)) {
250  return result;
251  }
252  return success();
253  };
254 
255  Region &thenRegion = adaptor.getThenRegion();
256  Region &elseRegion = adaptor.getElseRegion();
257 
258  bool hasElseBlock = !elseRegion.empty();
259 
260  auto loweredIf =
261  emitc::IfOp::create(rewriter, loc, adaptor.getCondition(), false, false);
262 
263  Region &loweredThenRegion = loweredIf.getThenRegion();
264  auto result = lowerRegion(thenRegion, loweredThenRegion);
265  if (failed(result)) {
266  return result;
267  }
268 
269  if (hasElseBlock) {
270  Region &loweredElseRegion = loweredIf.getElseRegion();
271  auto result = lowerRegion(elseRegion, loweredElseRegion);
272  if (failed(result)) {
273  return result;
274  }
275  }
276 
277  rewriter.setInsertionPointAfter(ifOp);
278  SmallVector<Value> results = loadValues(resultVariables, rewriter, loc);
279 
280  rewriter.replaceOp(ifOp, results);
281  return success();
282 }
283 
284 // Lower scf::index_switch to emitc::switch, implementing result values as
285 // emitc::variable's updated within the case and default regions.
286 struct IndexSwitchOpLowering : public OpConversionPattern<IndexSwitchOp> {
288 
289  LogicalResult
290  matchAndRewrite(IndexSwitchOp indexSwitchOp, OpAdaptor adaptor,
291  ConversionPatternRewriter &rewriter) const override;
292 };
293 
295  IndexSwitchOp indexSwitchOp, OpAdaptor adaptor,
296  ConversionPatternRewriter &rewriter) const {
297  Location loc = indexSwitchOp.getLoc();
298 
299  // Create an emitc::variable op for each result. These variables will be
300  // assigned to by emitc::assign ops within the case and default regions.
301  SmallVector<Value> resultVariables;
302  if (failed(createVariablesForResults(indexSwitchOp, getTypeConverter(),
303  rewriter, resultVariables))) {
304  return rewriter.notifyMatchFailure(indexSwitchOp,
305  "create variables for results failed");
306  }
307 
308  auto loweredSwitch =
309  emitc::SwitchOp::create(rewriter, loc, adaptor.getArg(),
310  adaptor.getCases(), indexSwitchOp.getNumCases());
311 
312  // Lowering all case regions.
313  for (auto pair :
314  llvm::zip(adaptor.getCaseRegions(), loweredSwitch.getCaseRegions())) {
315  if (failed(lowerRegion(indexSwitchOp, resultVariables, rewriter,
316  *std::get<0>(pair), std::get<1>(pair)))) {
317  return failure();
318  }
319  }
320 
321  // Lowering default region.
322  if (failed(lowerRegion(indexSwitchOp, resultVariables, rewriter,
323  adaptor.getDefaultRegion(),
324  loweredSwitch.getDefaultRegion()))) {
325  return failure();
326  }
327 
328  rewriter.setInsertionPointAfter(indexSwitchOp);
329  SmallVector<Value> results = loadValues(resultVariables, rewriter, loc);
330 
331  rewriter.replaceOp(indexSwitchOp, results);
332  return success();
333 }
334 
336  TypeConverter &typeConverter) {
337  patterns.add<ForLowering>(typeConverter, patterns.getContext());
338  patterns.add<IfLowering>(typeConverter, patterns.getContext());
339  patterns.add<IndexSwitchOpLowering>(typeConverter, patterns.getContext());
340 }
341 
342 void SCFToEmitCPass::runOnOperation() {
344  TypeConverter typeConverter;
345  // Fallback for other types.
346  typeConverter.addConversion([](Type type) -> std::optional<Type> {
347  if (!emitc::isSupportedEmitCType(type))
348  return {};
349  return type;
350  });
351  populateEmitCSizeTTypeConversions(typeConverter);
353 
354  // Configure conversion to lower out SCF operations.
355  ConversionTarget target(getContext());
356  target.addIllegalOp<scf::ForOp, scf::IfOp, scf::IndexSwitchOp>();
357  target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });
358  if (failed(
359  applyPartialConversion(getOperation(), target, std::move(patterns))))
360  signalPassFailure();
361 }
static MLIRContext * getContext(OpFoldResult val)
Block represents an ordered list of Operations.
Definition: Block.h:33
Operation * getTerminator()
Get the terminator operation of this block.
Definition: Block.cpp:244
This class implements a pattern rewriter for use with ConversionPatterns.
void replaceOp(Operation *op, ValueRange newValues) override
Replace the given operation with the new values.
LogicalResult getRemappedValues(ValueRange keys, SmallVectorImpl< Value > &results)
Return the converted values that replace 'keys' with types defined by the type converter of the curre...
FailureOr< Block * > convertRegionTypes(Region *region, const TypeConverter &converter, TypeConverter::SignatureConversion *entryConversion=nullptr)
Apply a signature conversion to each block in the given region.
void eraseOp(Operation *op) override
PatternRewriter hook for erasing a dead operation.
This class describes a specific conversion target.
ConvertToEmitCPatternInterface(Dialect *dialect)
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:346
InsertPoint saveInsertionPoint() const
Return a saved insertion point.
Definition: Builders.h:383
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:396
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition: Builders.h:434
void restoreInsertionPoint(InsertPoint ip)
Restore the insert point to a previously saved point.
Definition: Builders.h:388
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition: Builders.h:410
OpConversionPattern is a wrapper around ConversionPattern that allows for matching and rewriting agai...
OpConversionPattern(MLIRContext *context, PatternBenefit benefit=1)
This is a value defined by a result of an operation.
Definition: Value.h:447
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:783
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
bool empty()
Definition: Region.h:60
iterator end()
Definition: Region.h:56
Block & back()
Definition: Region.h:64
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
Definition: PatternMatch.h:716
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
void inlineRegionBefore(Region &region, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
Type conversion class.
void addConversion(FnT &&callback)
Register a conversion function.
LogicalResult convertType(Type t, SmallVectorImpl< Type > &results) const
Convert the given type.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:387
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:105
bool isSupportedEmitCType(mlir::Type type)
Determines whether type is valid in EmitC.
Definition: EmitC.cpp:59
Include the generated interface declarations.
void populateEmitCSizeTTypeConversions(TypeConverter &converter)
void populateSCFToEmitCConversionPatterns(RewritePatternSet &patterns, TypeConverter &typeConverter)
Collect a set of patterns to convert SCF operations to the EmitC dialect.
Definition: SCFToEmitC.cpp:335
const FrozenRewritePatternSet & patterns
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
LogicalResult applyPartialConversion(ArrayRef< Operation * > ops, const ConversionTarget &target, const FrozenRewritePatternSet &patterns, ConversionConfig config=ConversionConfig())
Below we define several entry points for operation conversion.
void registerConvertSCFToEmitCInterface(DialectRegistry &registry)
Definition: SCFToEmitC.cpp:50
LogicalResult matchAndRewrite(IndexSwitchOp indexSwitchOp, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override
Methods that operate on the SourceOp type.
Definition: SCFToEmitC.cpp:294