[llvm] [CodeGenPrepare] Fix signed overflow (PR #141487)

via llvm-commits llvm-commits at lists.llvm.org
Tue May 27 00:50:40 PDT 2025


https://github.com/mikael-nilsson-arm updated https://github.com/llvm/llvm-project/pull/141487

>From 27723bb6aa1b5299a1a536c501f4ea5dc606171f Mon Sep 17 00:00:00 2001
From: Mikael Nilsson <mikael.nilsson at arm.com>
Date: Tue, 27 May 2025 09:49:35 +0200
Subject: [PATCH] [CodeGenPrepare] Fix signed overflow

---
 llvm/lib/CodeGen/CodeGenPrepare.cpp | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 52263026d6cea..822ed6283117c 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -5447,11 +5447,17 @@ bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
       TPT.getRestorationPoint();
   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
     if (CI->getValue().isSignedIntN(64)) {
-      // Fold in immediates if legal for the target.
-      AddrMode.BaseOffs += CI->getSExtValue();
-      if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
-        return true;
-      AddrMode.BaseOffs -= CI->getSExtValue();
+      // Check if the addition would result in a signed overflow.
+      int64_t Result;
+      bool Overflow =
+          AddOverflow(AddrMode.BaseOffs, CI->getSExtValue(), Result);
+      if (!Overflow) {
+        // Fold in immediates if legal for the target.
+        AddrMode.BaseOffs = Result;
+        if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
+          return true;
+        AddrMode.BaseOffs -= CI->getSExtValue();
+      }
     }
   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
     // If this is a global variable, try to fold it into the addressing mode.



More information about the llvm-commits mailing list