[clang] [CIR] Upstream initial support for switch statements (PR #137106)
via cfe-commits
cfe-commits at lists.llvm.org
Thu Apr 24 14:05:21 PDT 2025
================
@@ -802,6 +804,132 @@ Block *cir::BrCondOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
return nullptr;
}
+//===----------------------------------------------------------------------===//
+// CaseOp
+//===----------------------------------------------------------------------===//
+
+void cir::CaseOp::getSuccessorRegions(
+ mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
+ if (!point.isParent()) {
+ regions.push_back(RegionSuccessor());
+ return;
+ }
+ regions.push_back(RegionSuccessor(&getCaseRegion()));
+}
+
+void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
+ ArrayAttr value, CaseOpKind kind,
+ OpBuilder::InsertPoint &insertPoint) {
+ OpBuilder::InsertionGuard guardSwitch(builder);
+ result.addAttribute("value", value);
+ result.getOrAddProperties<Properties>().kind =
+ cir::CaseOpKindAttr::get(builder.getContext(), kind);
+ Region *caseRegion = result.addRegion();
+ builder.createBlock(caseRegion);
+
+ insertPoint = builder.saveInsertionPoint();
+}
+
+LogicalResult cir::CaseOp::verify() { return success(); }
----------------
Andres-Salamanca wrote:
This verify() function was introduced when `cir.case` was added in [this commit](https://github.com/llvm/clangir/commit/92403f9797738a611ce128256a785a986127a9c8). Before that, cases in a `cir.switch` were represented as attributes and handled in the `parseSwitchOp` function see [this version of the file](https://github.com/llvm/clangir/blob/580885200e25bec4377356bade2e39660b897c56/clang/lib/CIR/Dialect/IR/CIRDialect.cpp#L1493).
With the introduction of `cir.case`, that logic was refactored. Now, cases are modeled as proper operations rather than attributes. Most of the case handling logic was moved to [CIRGenFunction::buildCaseDefaultCascade](https://github.com/llvm/clangir/blob/92403f9797738a611ce128256a785a986127a9c8/clang/lib/CIR/CodeGen/CIRGenStmt.cpp#L671) and [CIRGenFunction::foldCaseStmt](https://github.com/llvm/clangir/blob/d071f2fbda9fbae87904c1d2f9f66005fb867791/clang/lib/CIR/CodeGen/CIRGenStmt.cpp#L678C12-L678C23).
>From what I understand, the rationale for this change is:
"Then we can get the cases by traversing the body of the cir.switch operation easily instead of counting the regions and the attributes."
In the current setup, [CIRGenFunction::emitSwitchBody](https://github.com/llvm/clangir/blob/d071f2fbda9fbae87904c1d2f9f66005fb867791/clang/lib/CIR/CodeGen/CIRGenStmt.cpp#L1095C21-L1095C51) is responsible for creating the `cir.case` ops within the body of the `cir.switch`, and `buildCaseDefaultCascade` handles the logic for constructing and verifying that the case layout is correct. @bcardosolopes is this correct, or is there something I’m missing?
https://github.com/llvm/llvm-project/pull/137106
More information about the cfe-commits
mailing list