32#define GEN_PASS_DEF_CONVERTCONTROLFLOWTOLLVMPASS
33#include "mlir/Conversion/Passes.h.inc"
38#define PASS_NAME "convert-cf-to-llvm"
47 bool abortOnFailedAssert =
true,
50 abortOnFailedAssert(abortOnFailedAssert), symbolTables(symbolTables) {}
53 matchAndRewrite(cf::AssertOp op, OpAdaptor adaptor,
54 ConversionPatternRewriter &rewriter)
const override {
55 auto loc = op.getLoc();
56 auto module = op->getParentOfType<ModuleOp>();
59 Block *opBlock = rewriter.getInsertionBlock();
60 auto opPosition = rewriter.getInsertionPoint();
61 Block *continuationBlock = rewriter.splitBlock(opBlock, opPosition);
66 rewriter, loc, module,
"assert_msg", op.getMsg(), *getTypeConverter(),
68 "puts", symbolTables);
69 if (createResult.failed())
72 if (abortOnFailedAssert) {
74 auto abortFunc =
module.lookupSymbol<LLVM::LLVMFuncOp>("abort");
77 rewriter.setInsertionPointToStart(module.getBody());
78 auto abortFuncTy = LLVM::LLVMFunctionType::get(getVoidType(), {});
79 abortFunc = LLVM::LLVMFuncOp::create(rewriter, rewriter.getUnknownLoc(),
80 "abort", abortFuncTy);
82 LLVM::CallOp::create(rewriter, loc, abortFunc,
ValueRange());
83 LLVM::UnreachableOp::create(rewriter, loc);
85 LLVM::BrOp::create(rewriter, loc,
ValueRange(), continuationBlock);
89 rewriter.setInsertionPointToEnd(opBlock);
90 rewriter.replaceOpWithNewOp<LLVM::CondBrOp>(
91 op, adaptor.getArg(), continuationBlock, failureBlock);
99 bool abortOnFailedAssert =
true;
107static FailureOr<Block *> getConvertedBlock(ConversionPatternRewriter &rewriter,
111 assert(converter &&
"expected non-null type converter");
112 assert(!block->
isEntryBlock() &&
"entry blocks have no predecessors");
119 std::optional<TypeConverter::SignatureConversion> conversion =
120 converter->convertBlockSignature(block);
122 return rewriter.notifyMatchFailure(branchOp,
123 "could not compute block signature");
124 if (expectedTypes != conversion->getConvertedTypes())
125 return rewriter.notifyMatchFailure(
127 "mismatch between adaptor operand types and computed block signature");
128 return rewriter.applySignatureConversion(block, *conversion, converter);
135 llvm::append_range(
result, vals);
140static void setConvertedAttrs(
Operation *op, DictionaryAttr attrs) {
146 discardableAttrs.push_back(attr);
158 matchAndRewrite(cf::BranchOp op, Adaptor adaptor,
159 ConversionPatternRewriter &rewriter)
const override {
161 FailureOr<Block *> convertedBlock =
162 getConvertedBlock(rewriter, getTypeConverter(), op, op.getSuccessor(),
164 if (failed(convertedBlock))
166 DictionaryAttr attrs = op->getDiscardableAttrDictionary();
167 auto loopAnnotation = op->getAttrOfType<LLVM::LoopAnnotationAttr>(
169 Operation *newOp = rewriter.replaceOpWithNewOp<LLVM::BrOp>(
170 op, flattenedAdaptor, loopAnnotation, *convertedBlock);
173 setConvertedAttrs(newOp, attrs);
185 matchAndRewrite(cf::CondBranchOp op, Adaptor adaptor,
186 ConversionPatternRewriter &rewriter)
const override {
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(),
197 if (failed(convertedTrueBlock))
199 FailureOr<Block *> convertedFalseBlock =
200 getConvertedBlock(rewriter, getTypeConverter(), op, op.getFalseDest(),
202 if (failed(convertedFalseBlock))
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);
213 setConvertedAttrs(newOp, attrs);
224 matchAndRewrite(cf::SwitchOp op, cf::SwitchOp::Adaptor adaptor,
225 ConversionPatternRewriter &rewriter)
const override {
227 FailureOr<Block *> convertedDefaultBlock = getConvertedBlock(
228 rewriter, getTypeConverter(), op, op.getDefaultDestination(),
229 TypeRange(adaptor.getDefaultOperands()));
230 if (failed(convertedDefaultBlock))
236 for (
auto it : llvm::enumerate(op.getCaseDestinations())) {
238 FailureOr<Block *> convertedBlock =
239 getConvertedBlock(rewriter, getTypeConverter(), op,
b,
241 if (failed(convertedBlock))
243 caseDestinations.push_back(*convertedBlock);
246 rewriter.replaceOpWithNewOp<LLVM::SwitchOp>(
247 op, adaptor.getFlag(), *convertedDefaultBlock,
248 adaptor.getDefaultOperands(), adaptor.getCaseValuesAttr(),
249 caseDestinations, caseOperands);
261 CondBranchOpLowering,
262 SwitchOpLowering>(converter);
278struct ConvertControlFlowToLLVM
284 void runOnOperation()
override {
295 const auto &dataLayoutAnalysis = getAnalysis<DataLayoutAnalysis>();
297 dataLayoutAnalysis.getAtOrAbove(getOperation()));
299 options.overrideIndexBitwidth(indexBitwidth);
306 if (failed(applyPartialConversion(getOperation(),
target,
307 std::move(patterns))))
319struct ControlFlowToLLVMDialectInterface
320 :
public ConvertToLLVMPatternInterface {
321 ControlFlowToLLVMDialectInterface(Dialect *dialect)
322 : ConvertToLLVMPatternInterface(dialect) {}
324 void loadDependentDialects(MLIRContext *context)
const final {
325 context->loadDialect<LLVM::LLVMDialect>();
330 void populateConvertToLLVMConversionPatterns(
331 ConversionTarget &
target, LLVMTypeConverter &typeConverter,
332 RewritePatternSet &patterns)
const final {
343 dialect->addInterfaces<ControlFlowToLLVMDialectInterface>();
static SmallVector< Value > flattenValues(ArrayRef< ValueRange > values)
Flatten the given value ranges into a single vector of values.
static llvm::ManagedStatic< PassManagerOptions > options
Block represents an ordered list of Operations.
ValueTypeRange< BlockArgListType > getArgumentTypes()
Return a range containing the types of the arguments for this block.
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
bool isEntryBlock()
Return if this block is the entry block in the parent region.
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
typename SourceOp::template GenericAdaptor< ArrayRef< ValueRange > > OneToNOpAdaptor
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.
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
NamedAttribute represents a combination of a name and an Attribute value.
RAII guard to reset the insertion point of the builder when destroyed.
Operation is the basic unit of execution within MLIR.
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...
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.
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.
This class provides an abstraction over the different types of ranges over Values.
constexpr llvm::StringLiteral getLoopAnnotationAttrName()
Canonical name used when attaching LoopAnnotationAttr as a discardable attribute on operations that d...
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 ®istry)
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...