Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CIR][CodeGen] Adds SwitchOp flattening #549

Merged
merged 9 commits into from
Apr 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions clang/include/clang/CIR/Dialect/IR/CIROps.td
Original file line number Diff line number Diff line change
Expand Up @@ -3604,6 +3604,45 @@ def IsConstantOp : CIR_Op<"is_constant", [Pure]> {
}];
}


def SwitchFlatOp : CIR_Op<"switch.flat", [AttrSizedOperandSegments, Terminator]> {

let description = [{
The `cir.switch.flat` operation is a region-less and simplified version of the `cir.switch`.
It's representation is closer to LLVM IR dialect than the C/C++ language feature.
}];

let arguments = (ins
CIR_IntType:$condition,
Variadic<AnyType>:$defaultOperands,
VariadicOfVariadic<AnyType, "case_operand_segments">:$caseOperands,
ArrayAttr:$case_values,
DenseI32ArrayAttr:$case_operand_segments
);

let successors = (successor
AnySuccessor:$defaultDestination,
VariadicSuccessor<AnySuccessor>:$caseDestinations
);

let assemblyFormat = [{
$condition `:` type($condition) `,`
$defaultDestination (`(` $defaultOperands^ `:` type($defaultOperands) `)`)?
custom<SwitchFlatOpCases>(ref(type($condition)), $case_values, $caseDestinations,
$caseOperands, type($caseOperands))
attr-dict
}];

let builders = [
OpBuilder<(ins "Value":$condition,
"Block *":$defaultDestination,
"ValueRange":$defaultOperands,
CArg<"ArrayRef<APInt>", "{}">:$caseValues,
CArg<"BlockRange", "{}">:$caseDestinations,
CArg<"ArrayRef<ValueRange>", "{}">:$caseOperands)>
];
}

//===----------------------------------------------------------------------===//
// Atomic operations
//===----------------------------------------------------------------------===//
Expand Down
95 changes: 95 additions & 0 deletions clang/lib/CIR/Dialect/IR/CIRDialect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include "clang/CIR/Dialect/IR/CIRTypes.h"
#include "clang/CIR/Interfaces/CIRLoopOpInterface.h"
#include "llvm/Support/ErrorHandling.h"
#include <numeric>
#include <optional>

#include "mlir/Dialect/Func/IR/FuncOps.h"
Expand Down Expand Up @@ -1221,6 +1222,100 @@ void SwitchOp::build(
switchBuilder(builder, result.location, result);
}

//===----------------------------------------------------------------------===//
// SwitchFlatOp
//===----------------------------------------------------------------------===//

void SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
Value value, Block *defaultDestination,
ValueRange defaultOperands, ArrayRef<APInt> caseValues,
BlockRange caseDestinations,
ArrayRef<ValueRange> caseOperands) {

std::vector<mlir::Attribute> caseValuesAttrs;
for (auto &val : caseValues) {
caseValuesAttrs.push_back(mlir::cir::IntAttr::get(value.getType(), val));
}
auto attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);

build(builder, result, value, defaultOperands, caseOperands, attrs,
defaultDestination, caseDestinations);
}

/// <cases> ::= `[` (case (`,` case )* )? `]`
/// <case> ::= integer `:` bb-id (`(` ssa-use-and-type-list `)`)?
static ParseResult parseSwitchFlatOpCases(
OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
SmallVectorImpl<Block *> &caseDestinations,
SmallVectorImpl<SmallVector<OpAsmParser::UnresolvedOperand>> &caseOperands,
SmallVectorImpl<SmallVector<Type>> &caseOperandTypes) {
if (failed(parser.parseLSquare()))
return failure();
if (succeeded(parser.parseOptionalRSquare()))
return success();
SmallVector<mlir::Attribute> values;

auto parseCase = [&]() {
int64_t value = 0;
if (failed(parser.parseInteger(value)))
return failure();

values.push_back(IntAttr::get(flagType, value));

Block *destination;
SmallVector<OpAsmParser::UnresolvedOperand> operands;
SmallVector<Type> operandTypes;
if (parser.parseColon() || parser.parseSuccessor(destination))
return failure();
if (!parser.parseOptionalLParen()) {
if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
/*allowResultNumber=*/false) ||
parser.parseColonTypeList(operandTypes) || parser.parseRParen())
return failure();
}
caseDestinations.push_back(destination);
caseOperands.emplace_back(operands);
caseOperandTypes.emplace_back(operandTypes);
return success();
};
if (failed(parser.parseCommaSeparatedList(parseCase)))
return failure();

caseValues = ArrayAttr::get(flagType.getContext(), values);

return parser.parseRSquare();
}

static void printSwitchFlatOpCases(OpAsmPrinter &p, SwitchFlatOp op,
Type flagType, mlir::ArrayAttr caseValues,
SuccessorRange caseDestinations,
OperandRangeRange caseOperands,
const TypeRangeRange &caseOperandTypes) {
p << '[';
p.printNewline();
if (!caseValues) {
p << ']';
return;
}

size_t index = 0;
llvm::interleave(
llvm::zip(caseValues, caseDestinations),
[&](auto i) {
p << " ";
mlir::Attribute a = std::get<0>(i);
p << a.cast<mlir::cir::IntAttr>().getValue();
p << ": ";
p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
},
[&] {
p << ',';
p.printNewline();
});
p.printNewline();
p << ']';
}

//===----------------------------------------------------------------------===//
// CatchOp
//===----------------------------------------------------------------------===//
Expand Down
108 changes: 104 additions & 4 deletions clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,105 @@ class CIRLoopOpInterfaceFlattening
}
};

class CIRSwitchOpFlattening
: public mlir::OpRewritePattern<mlir::cir::SwitchOp> {
public:
using OpRewritePattern<mlir::cir::SwitchOp>::OpRewritePattern;

inline void rewriteYieldOp(mlir::PatternRewriter &rewriter,
mlir::cir::YieldOp yieldOp,
mlir::Block *destination) const {
rewriter.setInsertionPoint(yieldOp);
rewriter.replaceOpWithNewOp<mlir::cir::BrOp>(yieldOp, yieldOp.getOperands(),
destination);
}

mlir::LogicalResult
matchAndRewrite(mlir::cir::SwitchOp op,
mlir::PatternRewriter &rewriter) const override {
// Empty switch statement: just erase it.
if (!op.getCases().has_value() || op.getCases()->empty()) {
rewriter.eraseOp(op);
return mlir::success();
}

// Create exit block.
rewriter.setInsertionPointAfter(op);
auto *exitBlock =
rewriter.splitBlock(rewriter.getBlock(), rewriter.getInsertionPoint());

// Allocate required data structures (disconsider default case in
// vectors).
llvm::SmallVector<mlir::APInt, 8> caseValues;
llvm::SmallVector<mlir::Block *, 8> caseDestinations;
llvm::SmallVector<mlir::ValueRange, 8> caseOperands;

// Initialize default case as optional.
mlir::Block *defaultDestination = exitBlock;
mlir::ValueRange defaultOperands = exitBlock->getArguments();

// Track fallthrough between cases.
mlir::cir::YieldOp fallthroughYieldOp = nullptr;

// Digest the case statements values and bodies.
for (size_t i = 0; i < op.getCases()->size(); ++i) {
auto &region = op.getRegion(i);
auto caseAttr = op.getCases()->getValue()[i].cast<mlir::cir::CaseAttr>();

// Found default case: save destination and operands.
if (caseAttr.getKind().getValue() == mlir::cir::CaseOpKind::Default) {
defaultDestination = &region.front();
defaultOperands = region.getArguments();
} else {
// AnyOf cases kind can have multiple values, hence the loop below.
for (auto &value : caseAttr.getValue()) {
caseValues.push_back(value.cast<mlir::cir::IntAttr>().getValue());
caseOperands.push_back(region.getArguments());
caseDestinations.push_back(&region.front());
}
}

// Previous case is a fallthrough: branch it to this case.
if (fallthroughYieldOp) {
rewriteYieldOp(rewriter, fallthroughYieldOp, &region.front());
fallthroughYieldOp = nullptr;
}

for (auto &blk : region.getBlocks()) {
if (blk.getNumSuccessors())
continue;

// Handle switch-case yields.
if (auto yieldOp = dyn_cast<mlir::cir::YieldOp>(blk.getTerminator()))
fallthroughYieldOp = yieldOp;
}

// Handle break statements.
walkRegionSkipping<mlir::cir::LoopOpInterface, mlir::cir::SwitchOp>(
region, [&](mlir::Operation *op) {
if (isa<mlir::cir::BreakOp>(op))
lowerTerminator(op, exitBlock, rewriter);
});

// Extract region contents before erasing the switch op.
rewriter.inlineRegionBefore(region, exitBlock);
}

// Last case is a fallthrough: branch it to exit.
if (fallthroughYieldOp) {
rewriteYieldOp(rewriter, fallthroughYieldOp, exitBlock);
fallthroughYieldOp = nullptr;
}

// Set switch op to branch to the newly created blocks.
rewriter.setInsertionPoint(op);
rewriter.replaceOpWithNewOp<mlir::cir::SwitchFlatOp>(
op, op.getCondition(), defaultDestination, defaultOperands, caseValues,
caseDestinations, caseOperands);

return mlir::success();
}
};
class CIRTernaryOpFlattening
: public mlir::OpRewritePattern<mlir::cir::TernaryOp> {
public:
Expand Down Expand Up @@ -294,9 +393,10 @@ class CIRTernaryOpFlattening
};

void populateFlattenCFGPatterns(RewritePatternSet &patterns) {
patterns.add<CIRIfFlattening, CIRLoopOpInterfaceFlattening,
CIRScopeOpFlattening, CIRTernaryOpFlattening>(
patterns.getContext());
patterns
.add<CIRIfFlattening, CIRLoopOpInterfaceFlattening, CIRScopeOpFlattening,
CIRSwitchOpFlattening, CIRTernaryOpFlattening>(
patterns.getContext());
}

void FlattenCFGPass::runOnOperation() {
Expand All @@ -306,7 +406,7 @@ void FlattenCFGPass::runOnOperation() {
// Collect operations to apply patterns.
SmallVector<Operation *, 16> ops;
getOperation()->walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
if (isa<IfOp, ScopeOp, LoopOpInterface, TernaryOp>(op))
if (isa<IfOp, ScopeOp, SwitchOp, LoopOpInterface, TernaryOp>(op))
ops.push_back(op);
});

Expand Down
Loading
Loading