[clang] [CIR] Upstream initial support for switch statements (PR #137106)
Andy Kaylor via cfe-commits
cfe-commits at lists.llvm.org
Fri Apr 25 16:57:53 PDT 2025
================
@@ -600,3 +721,99 @@ mlir::LogicalResult CIRGenFunction::emitWhileStmt(const WhileStmt &s) {
terminateBody(builder, whileOp.getBody(), getLoc(s.getEndLoc()));
return mlir::success();
}
+
+mlir::LogicalResult CIRGenFunction::emitSwitchBody(const Stmt *s) {
+ // It is rare but legal if the switch body is not a compound stmt. e.g.,
+ //
+ // switch(a)
+ // while(...) {
+ // case1
+ // ...
+ // case2
+ // ...
+ // }
+ if (!isa<CompoundStmt>(s))
+ return emitStmt(s, /*useCurrentScope=*/true);
+
+ auto *compoundStmt = cast<CompoundStmt>(s);
+
+ mlir::Block *swtichBlock = builder.getBlock();
+ for (auto *c : compoundStmt->body()) {
+ if (auto *switchCase = dyn_cast<SwitchCase>(c)) {
+ builder.setInsertionPointToEnd(swtichBlock);
+ // Reset insert point automatically, so that we can attach following
+ // random stmt to the region of previous built case op to try to make
+ // the being generated `cir.switch` to be in simple form.
+ if (mlir::failed(
+ emitSwitchCase(*switchCase, /*buildingTopLevelCase=*/true)))
+ return mlir::failure();
+
+ continue;
+ }
+
+ // Otherwise, just build the statements in the nearest case region.
+ if (mlir::failed(emitStmt(c, /*useCurrentScope=*/!isa<CompoundStmt>(c))))
+ return mlir::failure();
+ }
+
+ return mlir::success();
+}
+
+mlir::LogicalResult CIRGenFunction::emitSwitchStmt(const clang::SwitchStmt &s) {
+ // TODO: LLVM codegen does some early optimization to fold the condition and
+ // only emit live cases. CIR should use MLIR to achieve similar things,
+ // nothing to be done here.
+ // if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue))...
----------------
andykaylor wrote:
As long as the implementation is missing in the upstream repo, a MissingFeatures assert is appropriate.
https://github.com/llvm/llvm-project/pull/137106
More information about the cfe-commits
mailing list