Skip to content

[CIR] Upstream support for FlattenCFG switch and SwitchFlatOp #139154

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

Merged
merged 8 commits into from
May 16, 2025
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
46 changes: 46 additions & 0 deletions clang/include/clang/CIR/Dialect/IR/CIROps.td
Original file line number Diff line number Diff line change
Expand Up @@ -971,6 +971,52 @@ def SwitchOp : CIR_Op<"switch",
}];
}

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

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`.
Its 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:$caseValues,
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)), $caseValues,
$caseDestinations, $caseOperands,
type($caseOperands))
attr-dict
}];

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

//===----------------------------------------------------------------------===//
// BrOp
//===----------------------------------------------------------------------===//
Expand Down
96 changes: 96 additions & 0 deletions clang/lib/CIR/Dialect/IR/CIRDialect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
#include "clang/CIR/MissingFeatures.h"
#include <numeric>

using namespace mlir;
using namespace cir;
Expand Down Expand Up @@ -962,6 +963,101 @@ bool cir::SwitchOp::isSimpleForm(llvm::SmallVectorImpl<CaseOp> &cases) {
});
}

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

void cir::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 (const APInt &val : caseValues)
caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
mlir::ArrayAttr 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<llvm::SmallVector<OpAsmParser::UnresolvedOperand>>
&caseOperands,
SmallVectorImpl<llvm::SmallVector<Type>> &caseOperandTypes) {
if (failed(parser.parseLSquare()))
return failure();
if (succeeded(parser.parseOptionalRSquare()))
return success();
llvm::SmallVector<mlir::Attribute> values;

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

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

Block *destination;
llvm::SmallVector<OpAsmParser::UnresolvedOperand> operands;
llvm::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, cir::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 << mlir::cast<cir::IntAttr>(a).getValue();
p << ": ";
p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
},
[&] {
p << ',';
p.printNewline();
});
p.printNewline();
p << ']';
}

//===----------------------------------------------------------------------===//
// GlobalOp
//===----------------------------------------------------------------------===//
Expand Down
17 changes: 15 additions & 2 deletions clang/lib/CIR/Dialect/Transforms/CIRCanonicalize.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,19 @@ struct RemoveEmptyScope : public OpRewritePattern<ScopeOp> {
}
};

struct RemoveEmptySwitch : public OpRewritePattern<SwitchOp> {
using OpRewritePattern<SwitchOp>::OpRewritePattern;

LogicalResult matchAndRewrite(SwitchOp op,
PatternRewriter &rewriter) const final {
if (!(op.getBody().empty() || isa<YieldOp>(op.getBody().front().front())))
return failure();

rewriter.eraseOp(op);
return success();
}
};

//===----------------------------------------------------------------------===//
// CIRCanonicalizePass
//===----------------------------------------------------------------------===//
Expand Down Expand Up @@ -127,8 +140,8 @@ void CIRCanonicalizePass::runOnOperation() {
assert(!cir::MissingFeatures::callOp());
// CastOp, UnaryOp and VecExtractOp are here to perform a manual `fold` in
// applyOpPatternsGreedily.
if (isa<BrOp, BrCondOp, CastOp, ScopeOp, SelectOp, UnaryOp, VecExtractOp>(
op))
if (isa<BrOp, BrCondOp, CastOp, ScopeOp, SwitchOp, SelectOp, UnaryOp,
VecExtractOp>(op))
ops.push_back(op);
});

Expand Down
Loading