[flang-commits] [flang] 47ef3d0 - [Flang] Avoid crash when a function return is undefined (#151577)

via flang-commits flang-commits at lists.llvm.org
Tue Aug 5 06:53:22 PDT 2025


Author: Carlos Seo
Date: 2025-08-05T10:53:18-03:00
New Revision: 47ef3d069bcfb8ec31c06cdd619557c84d1084ad

URL: https://github.com/llvm/llvm-project/commit/47ef3d069bcfb8ec31c06cdd619557c84d1084ad
DIFF: https://github.com/llvm/llvm-project/commit/47ef3d069bcfb8ec31c06cdd619557c84d1084ad.diff

LOG: [Flang] Avoid crash when a function return is undefined (#151577)

Properly terminate the StatementContext cleanup when a function return
value is undefined.

Fixes #126452

Added: 
    flang/test/Lower/undef-func-result.f90

Modified: 
    flang/lib/Lower/Bridge.cpp

Removed: 
    


################################################################################
diff  --git a/flang/lib/Lower/Bridge.cpp b/flang/lib/Lower/Bridge.cpp
index e630841ca1a45..ce68e549fa73e 100644
--- a/flang/lib/Lower/Bridge.cpp
+++ b/flang/lib/Lower/Bridge.cpp
@@ -1732,7 +1732,13 @@ class FirConverter : public Fortran::lower::AbstractConverter {
     Fortran::lower::SymbolBox resultSymBox = lookupSymbol(resultSym);
     mlir::Location loc = toLocation();
     if (!resultSymBox) {
-      mlir::emitError(loc, "internal error when processing function return");
+      // Create a dummy undefined value of the expected return type.
+      // This prevents improper cleanup of StatementContext, which would lead
+      // to a crash due to a block with no terminator. See issue #126452.
+      mlir::FunctionType funcType = builder->getFunction().getFunctionType();
+      mlir::Type resultType = funcType.getResult(0);
+      mlir::Value undefResult = builder->create<fir::UndefOp>(loc, resultType);
+      genExitRoutine(false, undefResult);
       return;
     }
     mlir::Value resultVal = resultSymBox.match(

diff  --git a/flang/test/Lower/undef-func-result.f90 b/flang/test/Lower/undef-func-result.f90
new file mode 100644
index 0000000000000..e3d3e23614a53
--- /dev/null
+++ b/flang/test/Lower/undef-func-result.f90
@@ -0,0 +1,7 @@
+!RUN: %flang -c %s -### 2>&1
+function s(x) result(i)
+!CHECK-WARNING: Function result is never defined
+integer::x
+procedure():: i
+end function
+end


        


More information about the flang-commits mailing list