MLIR 24.0.0git
ControlFlowToLLVM.cpp
Go to the documentation of this file.
1//===- ControlFlowToLLVM.cpp - ControlFlow to LLVM dialect 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 MLIR standard and builtin dialects
10// into the LLVM IR dialect.
11//
12//===----------------------------------------------------------------------===//
13
15
26#include "mlir/IR/BuiltinOps.h"
28#include "mlir/Pass/Pass.h"
30
31namespace mlir {
32#define GEN_PASS_DEF_CONVERTCONTROLFLOWTOLLVMPASS
33#include "mlir/Conversion/Passes.h.inc"
34} // namespace mlir
35
36using namespace mlir;
37
38#define PASS_NAME "convert-cf-to-llvm"
39
40namespace {
41/// Lower `cf.assert`. The default lowering calls the `abort` function if the
42/// assertion is violated and has no effect otherwise. The failure message is
43/// ignored by the default lowering but should be propagated by any custom
44/// lowering.
45struct AssertOpLowering : public ConvertOpToLLVMPattern<cf::AssertOp> {
46 explicit AssertOpLowering(const LLVMTypeConverter &typeConverter,
47 bool abortOnFailedAssert = true,
48 SymbolTableCollection *symbolTables = nullptr)
49 : ConvertOpToLLVMPattern<cf::AssertOp>(typeConverter, /*benefit=*/1),
50 abortOnFailedAssert(abortOnFailedAssert), symbolTables(symbolTables) {}
51
52 LogicalResult
53 matchAndRewrite(cf::AssertOp op, OpAdaptor adaptor,
54 ConversionPatternRewriter &rewriter) const override {
55 auto loc = op.getLoc();
56 auto module = op->getParentOfType<ModuleOp>();
57
58 // Split block at `assert` operation.
59 Block *opBlock = rewriter.getInsertionBlock();
60 auto opPosition = rewriter.getInsertionPoint();
61 Block *continuationBlock = rewriter.splitBlock(opBlock, opPosition);
62
63 // Failed block: Generate IR to print the message and call `abort`.
64 Block *failureBlock = rewriter.createBlock(opBlock->getParent());
65 auto createResult = LLVM::createPrintStrCall(
66 rewriter, loc, module, "assert_msg", op.getMsg(), *getTypeConverter(),
67 /*addNewLine=*/false,
68 /*runtimeFunctionName=*/"puts", symbolTables);
69 if (createResult.failed())
70 return failure();
71
72 if (abortOnFailedAssert) {
73 // Insert the `abort` declaration if necessary.
74 auto abortFunc = module.lookupSymbol<LLVM::LLVMFuncOp>("abort");
75 if (!abortFunc) {
76 OpBuilder::InsertionGuard guard(rewriter);
77 rewriter.setInsertionPointToStart(module.getBody());
78 auto abortFuncTy = LLVM::LLVMFunctionType::get(getVoidType(), {});
79 abortFunc = LLVM::LLVMFuncOp::create(rewriter, rewriter.getUnknownLoc(),
80 "abort", abortFuncTy);
81 }
82 LLVM::CallOp::create(rewriter, loc, abortFunc, ValueRange());
83 LLVM::UnreachableOp::create(rewriter, loc);
84 } else {
85 LLVM::BrOp::create(rewriter, loc, ValueRange(), continuationBlock);
86 }
87
88 // Generate assertion test.
89 rewriter.setInsertionPointToEnd(opBlock);
90 rewriter.replaceOpWithNewOp<LLVM::CondBrOp>(
91 op, adaptor.getArg(), continuationBlock, failureBlock);
92
93 return success();
94 }
95
96private:
97 /// If set to `false`, messages are printed but program execution continues.
98 /// This is useful for testing asserts.
99 bool abortOnFailedAssert = true;
100
101 SymbolTableCollection *symbolTables = nullptr;
102};
103
104/// Helper function for converting branch ops. This function converts the
105/// signature of the given block. If the new block signature is different from
106/// `expectedTypes`, returns "failure".
107static FailureOr<Block *> getConvertedBlock(ConversionPatternRewriter &rewriter,
108 const TypeConverter *converter,
109 Operation *branchOp, Block *block,
110 TypeRange expectedTypes) {
111 assert(converter && "expected non-null type converter");
112 assert(!block->isEntryBlock() && "entry blocks have no predecessors");
113
114 // There is nothing to do if the types already match.
115 if (block->getArgumentTypes() == expectedTypes)
116 return block;
117
118 // Compute the new block argument types and convert the block.
119 std::optional<TypeConverter::SignatureConversion> conversion =
120 converter->convertBlockSignature(block);
121 if (!conversion)
122 return rewriter.notifyMatchFailure(branchOp,
123 "could not compute block signature");
124 if (expectedTypes != conversion->getConvertedTypes())
125 return rewriter.notifyMatchFailure(
126 branchOp,
127 "mismatch between adaptor operand types and computed block signature");
128 return rewriter.applySignatureConversion(block, *conversion, converter);
129}
130
131/// Flatten the given value ranges into a single vector of values.
134 for (const ValueRange &vals : values)
135 llvm::append_range(result, vals);
136 return result;
137}
138
139/// Set attributes on an operation using its inherent/discardable split.
140static void setConvertedAttrs(Operation *op, DictionaryAttr attrs) {
141 SmallVector<NamedAttribute> discardableAttrs;
142 for (NamedAttribute attr : attrs) {
143 if (op->getInherentAttr(attr.getName()).has_value())
144 op->setInherentAttr(attr.getName(), attr.getValue());
145 else
146 discardableAttrs.push_back(attr);
147 }
148 op->setDiscardableAttrs(discardableAttrs);
149}
150
151/// Convert the destination block signature (if necessary) and lower the branch
152/// op to llvm.br.
153struct BranchOpLowering : public ConvertOpToLLVMPattern<cf::BranchOp> {
156
157 LogicalResult
158 matchAndRewrite(cf::BranchOp op, Adaptor adaptor,
159 ConversionPatternRewriter &rewriter) const override {
160 SmallVector<Value> flattenedAdaptor = flattenValues(adaptor.getOperands());
161 FailureOr<Block *> convertedBlock =
162 getConvertedBlock(rewriter, getTypeConverter(), op, op.getSuccessor(),
163 TypeRange(ValueRange(flattenedAdaptor)));
164 if (failed(convertedBlock))
165 return failure();
166 DictionaryAttr attrs = op->getDiscardableAttrDictionary();
167 auto loopAnnotation = op->getAttrOfType<LLVM::LoopAnnotationAttr>(
169 Operation *newOp = rewriter.replaceOpWithNewOp<LLVM::BrOp>(
170 op, flattenedAdaptor, loopAnnotation, *convertedBlock);
171 // TODO: We should not just forward all attributes like that. But there are
172 // existing Flang tests that depend on this behavior.
173 setConvertedAttrs(newOp, attrs);
174 return success();
175 }
176};
177
178/// Convert the destination block signatures (if necessary) and lower the
179/// branch op to llvm.cond_br.
180struct CondBranchOpLowering : public ConvertOpToLLVMPattern<cf::CondBranchOp> {
183
184 LogicalResult
185 matchAndRewrite(cf::CondBranchOp op, Adaptor adaptor,
186 ConversionPatternRewriter &rewriter) const override {
187 SmallVector<Value> flattenedAdaptorTrue =
188 flattenValues(adaptor.getTrueDestOperands());
189 SmallVector<Value> flattenedAdaptorFalse =
190 flattenValues(adaptor.getFalseDestOperands());
191 if (!llvm::hasSingleElement(adaptor.getCondition()))
192 return rewriter.notifyMatchFailure(op,
193 "expected single element condition");
194 FailureOr<Block *> convertedTrueBlock =
195 getConvertedBlock(rewriter, getTypeConverter(), op, op.getTrueDest(),
196 TypeRange(ValueRange(flattenedAdaptorTrue)));
197 if (failed(convertedTrueBlock))
198 return failure();
199 FailureOr<Block *> convertedFalseBlock =
200 getConvertedBlock(rewriter, getTypeConverter(), op, op.getFalseDest(),
201 TypeRange(ValueRange(flattenedAdaptorFalse)));
202 if (failed(convertedFalseBlock))
203 return failure();
204 DictionaryAttr attrs = op->getDiscardableAttrDictionary();
205 auto loopAnnotation = op->getAttrOfType<LLVM::LoopAnnotationAttr>(
207 auto newOp = rewriter.replaceOpWithNewOp<LLVM::CondBrOp>(
208 op, llvm::getSingleElement(adaptor.getCondition()),
209 flattenedAdaptorTrue, flattenedAdaptorFalse, op.getBranchWeightsAttr(),
210 loopAnnotation, *convertedTrueBlock, *convertedFalseBlock);
211 // TODO: We should not just forward all attributes like that. But there are
212 // existing Flang tests that depend on this behavior.
213 setConvertedAttrs(newOp, attrs);
214 return success();
215 }
216};
217
218/// Convert the destination block signatures (if necessary) and lower the
219/// switch op to llvm.switch.
220struct SwitchOpLowering : public ConvertOpToLLVMPattern<cf::SwitchOp> {
222
223 LogicalResult
224 matchAndRewrite(cf::SwitchOp op, cf::SwitchOp::Adaptor adaptor,
225 ConversionPatternRewriter &rewriter) const override {
226 // Get or convert default block.
227 FailureOr<Block *> convertedDefaultBlock = getConvertedBlock(
228 rewriter, getTypeConverter(), op, op.getDefaultDestination(),
229 TypeRange(adaptor.getDefaultOperands()));
230 if (failed(convertedDefaultBlock))
231 return failure();
232
233 // Get or convert all case blocks.
234 SmallVector<Block *> caseDestinations;
235 SmallVector<ValueRange> caseOperands = adaptor.getCaseOperands();
236 for (auto it : llvm::enumerate(op.getCaseDestinations())) {
237 Block *b = it.value();
238 FailureOr<Block *> convertedBlock =
239 getConvertedBlock(rewriter, getTypeConverter(), op, b,
240 TypeRange(caseOperands[it.index()]));
241 if (failed(convertedBlock))
242 return failure();
243 caseDestinations.push_back(*convertedBlock);
244 }
245
246 rewriter.replaceOpWithNewOp<LLVM::SwitchOp>(
247 op, adaptor.getFlag(), *convertedDefaultBlock,
248 adaptor.getDefaultOperands(), adaptor.getCaseValuesAttr(),
249 caseDestinations, caseOperands);
250 return success();
251 }
252};
253
254} // namespace
255
257 const LLVMTypeConverter &converter, RewritePatternSet &patterns) {
258 // clang-format off
259 patterns.add<
260 BranchOpLowering,
261 CondBranchOpLowering,
262 SwitchOpLowering>(converter);
263 // clang-format on
264}
265
267 const LLVMTypeConverter &converter, RewritePatternSet &patterns,
268 bool abortOnFailure, SymbolTableCollection *symbolTables) {
269 patterns.add<AssertOpLowering>(converter, abortOnFailure, symbolTables);
270}
271
272//===----------------------------------------------------------------------===//
273// Pass Definition
274//===----------------------------------------------------------------------===//
275
276namespace {
277/// A pass converting MLIR operations into the LLVM IR dialect.
278struct ConvertControlFlowToLLVM
279 : public impl::ConvertControlFlowToLLVMPassBase<ConvertControlFlowToLLVM> {
280
281 using Base::Base;
282
283 /// Run the dialect converter on the module.
284 void runOnOperation() override {
285 MLIRContext *ctx = &getContext();
287 // This pass lowers only CF dialect ops, but it also modifies block
288 // signatures inside other ops. These ops should be treated as legal. They
289 // are lowered by other passes.
290 target.markUnknownOpDynamicallyLegal([&](Operation *op) {
291 return op->getDialect() !=
292 ctx->getLoadedDialect<cf::ControlFlowDialect>();
293 });
294
295 const auto &dataLayoutAnalysis = getAnalysis<DataLayoutAnalysis>();
297 dataLayoutAnalysis.getAtOrAbove(getOperation()));
298 if (indexBitwidth != kDeriveIndexBitwidthFromDataLayout)
299 options.overrideIndexBitwidth(indexBitwidth);
300
301 LLVMTypeConverter converter(ctx, options, &dataLayoutAnalysis);
302 RewritePatternSet patterns(ctx);
305
306 if (failed(applyPartialConversion(getOperation(), target,
307 std::move(patterns))))
308 signalPassFailure();
309 }
310};
311} // namespace
312
313//===----------------------------------------------------------------------===//
314// ConvertToLLVMPatternInterface implementation
315//===----------------------------------------------------------------------===//
316
317namespace {
318/// Implement the interface to convert MemRef to LLVM.
319struct ControlFlowToLLVMDialectInterface
320 : public ConvertToLLVMPatternInterface {
321 ControlFlowToLLVMDialectInterface(Dialect *dialect)
322 : ConvertToLLVMPatternInterface(dialect) {}
323
324 void loadDependentDialects(MLIRContext *context) const final {
325 context->loadDialect<LLVM::LLVMDialect>();
326 }
327
328 /// Hook for derived dialect interface to provide conversion patterns
329 /// and mark dialect legal for the conversion target.
330 void populateConvertToLLVMConversionPatterns(
331 ConversionTarget &target, LLVMTypeConverter &typeConverter,
332 RewritePatternSet &patterns) const final {
334 patterns);
336 }
337};
338} // namespace
339
341 DialectRegistry &registry) {
342 registry.addExtension(+[](MLIRContext *ctx, cf::ControlFlowDialect *dialect) {
343 dialect->addInterfaces<ControlFlowToLLVMDialectInterface>();
344 });
345}
return success()
static SmallVector< Value > flattenValues(ArrayRef< ValueRange > values)
Flatten the given value ranges into a single vector of values.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getContext())
static llvm::ManagedStatic< PassManagerOptions > options
Block represents an ordered list of Operations.
Definition Block.h:34
ValueTypeRange< BlockArgListType > getArgumentTypes()
Return a range containing the types of the arguments for this block.
Definition Block.cpp:154
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition Block.cpp:27
bool isEntryBlock()
Return if this block is the entry block in the parent region.
Definition Block.cpp:36
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
Definition Pattern.h:233
typename SourceOp::template GenericAdaptor< ArrayRef< ValueRange > > OneToNOpAdaptor
Definition Pattern.h:236
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.
Derived class that automatically populates legalization information for different LLVM ops.
Conversion from types to the LLVM IR dialect.
Options to control the LLVM lowering.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
void setInherentAttr(StringAttr name, Attribute value)
Set an inherent attribute by name.
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Definition Operation.h:237
std::optional< Attribute > getInherentAttr(StringRef name)
Access an inherent attribute by name: returns an empty optional if there is no inherent attribute wit...
void setDiscardableAttrs(DictionaryAttr newAttrs)
Set the discardable attribute dictionary on this operation.
Definition Operation.h:577
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class represents a collection of SymbolTables.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
constexpr llvm::StringLiteral getLoopAnnotationAttrName()
Canonical name used when attaching LoopAnnotationAttr as a discardable attribute on operations that d...
Definition LLVMAttrs.h:122
LogicalResult createPrintStrCall(OpBuilder &builder, Location loc, ModuleOp moduleOp, StringRef symbolName, StringRef string, const LLVMTypeConverter &typeConverter, bool addNewline=true, std::optional< StringRef > runtimeFunctionName={}, SymbolTableCollection *symbolTables=nullptr)
Generate IR that prints the given string to stdout.
void registerConvertControlFlowToLLVMInterface(DialectRegistry &registry)
void populateControlFlowToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns)
Collect the patterns to convert from the ControlFlow dialect to LLVM.
void populateAssertToLLVMConversionPattern(const LLVMTypeConverter &converter, RewritePatternSet &patterns, bool abortOnFailure=true, SymbolTableCollection *symbolTables=nullptr)
Populate the cf.assert to LLVM conversion pattern.
Include the generated interface declarations.
static constexpr unsigned kDeriveIndexBitwidthFromDataLayout
Value to pass as bitwidth for the index type when the converter is expected to derive the bitwidth fr...