From 83c9b17ec5aa3644201b414cf72c3166fd2f1930 Mon Sep 17 00:00:00 2001
From: "J. Gareth \"Curious Kit\" Moreton" <gareth@moreton-family.com>
Date: Thu, 27 Feb 2025 01:18:57 +0000
Subject: [PATCH]   * x86: Fixed oversight in LeaLea2LeaLea optimisations where
 bad code is          generated if the intermediate register appears in the
 first reference

---
 compiler/x86/aoptx86.pas | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/compiler/x86/aoptx86.pas b/compiler/x86/aoptx86.pas
index 375a60eafe..6a6d380e9c 100644
--- a/compiler/x86/aoptx86.pas
+++ b/compiler/x86/aoptx86.pas
@@ -6425,7 +6425,12 @@ unit aoptx86;
                       (
                         { Don't optimise if size is a concern and the intermediate register remains in use }
                         IntermediateRegDiscarded or
-                        not (cs_opt_size in current_settings.optimizerswitches)
+                        (
+                          not (cs_opt_size in current_settings.optimizerswitches) and
+                          { If the intermediate register is not discarded, it must not
+                            appear in the first LEA's reference.  (Fixes #41166) }
+                          not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
+                        )
                       ) and
                       (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
                       (
@@ -6522,7 +6527,12 @@ unit aoptx86;
                     if (
                         { Don't optimise if size is a concern and the intermediate register remains in use }
                         IntermediateRegDiscarded or
-                        not (cs_opt_size in current_settings.optimizerswitches)
+                        (
+                          not (cs_opt_size in current_settings.optimizerswitches) and
+                          { If the intermediate register is not discarded, it must not
+                            appear in the first LEA's reference.  (Fixes #41166) }
+                          not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
+                        )
                       ) and
                       (
                         (