================
@@ -263,6 +264,72 @@ static void terminateBody(CIRGenBuilderTy &builder, 
mlir::Region &r,
     b->erase();
 }
 
+mlir::LogicalResult CIRGenFunction::emitIfStmt(const IfStmt &s) {
+  mlir::LogicalResult res = mlir::success();
+  // The else branch of a consteval if statement is always the only branch
+  // that can be runtime evaluated.
+  const Stmt *ConstevalExecuted;
+  if (s.isConsteval()) {
+    ConstevalExecuted = s.isNegatedConsteval() ? s.getThen() : s.getElse();
+    if (!ConstevalExecuted) {
+      // No runtime code execution required
+      return res;
+    }
+  }
+
+  // C99 6.8.4.1: The first substatement is executed if the expression
+  // compares unequal to 0.  The condition must be a scalar type.
+  auto ifStmtBuilder = [&]() -> mlir::LogicalResult {
+    if (s.isConsteval())
+      return emitStmt(ConstevalExecuted, /*useCurrentScope=*/true);
+
+    if (s.getInit())
+      if (emitStmt(s.getInit(), /*useCurrentScope=*/true).failed())
+        return mlir::failure();
+
+    if (s.getConditionVariable())
+      emitDecl(*s.getConditionVariable());
+
+    // During LLVM codegen, if the condition constant folds and can be elided,
+    // it tries to avoid emitting the condition and the dead arm of the 
if/else.
+    // TODO(cir): we skip this in CIRGen, but should implement this as part of
+    // SSCP or a specific CIR pass.
+    bool CondConstant;
+    if (ConstantFoldsToSimpleInteger(s.getCond(), CondConstant,
----------------
andykaylor wrote:

> Doing it in MLIR is probably nicer, but if we can "easily" (not too compile 
> time intensive) do it during CIRGen, shouldn't we?

I guess this is a philosophical question, but I'm of the opinion that the front 
end should strictly be producing IR that represents the semantics of the source 
code and has no business doing any sort of optimization. It took me a while to 
come to this conclusion when I was working on the optimizer, because it was 
jarring how inefficient the IR looked coming out of the front end (things like 
storing a variable to an alloca slot and then immediately reloading it, but I 
eventually came to realize that the front end was doing that because those were 
the unvarnished semantics of the source code. Taking that to the extreme, if 
the source code says "if (true)..." what business does the front end have 
removing that? Optimizations should be left to the optimizer.

https://github.com/llvm/llvm-project/pull/134333
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to