Please find attached a rather trivial fix for this PR.

The patch passes regression testing on FC44/x86_64. OK for mainline?

Paul
From 4e25ce26c38c83996871745506c5441049556497 Mon Sep 17 00:00:00 2001
From: Paul Thomas <[email protected]>
Date: Thu, 20 Aug 2026 09:24:40 +0100
Subject: [PATCH] Fortran: Lost statement label in a program with a CONTAINS
 section [PR126909]

2026-08-20  Paul Thomas  <[email protected]>

gcc/fortran
	PR fortran/126909
	* parse.cc (accept_statement): After a contains section, a new
	namespace is started and the new statement label is stored
	there. Find a label for the new statement and free the old one.

gcc/testsuite
	PR fortran/126909
	* gfortran.dg/pr126909.f90: New test.
---
 gcc/fortran/parse.cc                   | 19 +++++++++++++++++++
 gcc/testsuite/gfortran.dg/pr126909.f90 | 21 +++++++++++++++++++++
 2 files changed, 40 insertions(+)
 create mode 100644 gcc/testsuite/gfortran.dg/pr126909.f90

diff --git a/gcc/fortran/parse.cc b/gcc/fortran/parse.cc
index 47b443c4a5f..c7968e7b8fb 100644
--- a/gcc/fortran/parse.cc
+++ b/gcc/fortran/parse.cc
@@ -3253,6 +3253,25 @@ accept_statement (gfc_statement st)
     case ST_END_SUBROUTINE:
       if (gfc_statement_label != NULL)
 	{
+	  if (st == ST_END_PROGRAM
+	      && gfc_state_stack->head == NULL
+	      && gfc_state_stack->previous
+	      && gfc_state_stack->previous->sym
+	      && gfc_state_stack->previous->sym->attr.is_main_program)
+	    {
+	      /* After a contains section, a new namespace is started and the
+		 new statement label is stored there. Find a label for the new
+		 statement and free the old one.  */
+	      int value = gfc_current_ns->st_labels->value;
+	      gfc_namespace *old_ns = gfc_current_ns;
+	      pop_state ();
+	      gfc_current_ns = gfc_state_stack->sym->ns;
+	      new_st.here = gfc_get_st_label (value);
+	      new_st.here->defined = ST_LABEL_TARGET;
+	      gfc_current_ns = old_ns;
+	      free (gfc_current_ns->st_labels);
+	      gfc_current_ns->st_labels = NULL;
+	    }
 	  new_st.op = EXEC_RETURN;
 	  add_statement ();
 	}
diff --git a/gcc/testsuite/gfortran.dg/pr126909.f90 b/gcc/testsuite/gfortran.dg/pr126909.f90
new file mode 100644
index 00000000000..32593c894f7
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr126909.f90
@@ -0,0 +1,21 @@
+! {dg-do compile }
+! { dg-options "-fdump-tree-original" }
+!
+! Test the fix for PR126909, in which the END PROGRAM label was not being
+! generated correctly.
+!
+! Contributed by Steve Kargl  <[email protected]>
+!
+program lost
+   print *, "Calling sub()"
+   call sub()
+   goto 10
+   print *, 'More Dead code'
+   contains
+      subroutine sub()
+         print *, 'Entered sub()'
+         goto 11
+         print *, 'Dead code'
+11    end subroutine sub
+10 end program lost
+! { dg-final { scan-tree-dump-times "label.000010" 2 "original" } }
-- 
2.55.0

Reply via email to