[llvm] [CodeGenPrepare] Fix signed overflow (PR #141487)
via llvm-commits
llvm-commits at lists.llvm.org
Mon May 26 05:42:22 PDT 2025
https://github.com/mikael-nilsson-arm created https://github.com/llvm/llvm-project/pull/141487
The signed addition could overflow which is undefined behavior, now the code checks for it.
>From eca7dafaa3d4c29c4e8dac77f16a63c159ba4dd9 Mon Sep 17 00:00:00 2001
From: Mikael Nilsson <mikael.nilsson at arm.com>
Date: Mon, 26 May 2025 14:06:56 +0200
Subject: [PATCH] [CodeGenPrepare] Fix signed overflow
---
llvm/lib/CodeGen/CodeGenPrepare.cpp | 17 ++++++++++++-----
1 file changed, 12 insertions(+), 5 deletions(-)
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 52263026d6cea..c723a9cb3dcb5 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -5447,11 +5447,18 @@ 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.
+ bool Overflow = false;
+ APInt BaseOffs(64, AddrMode.BaseOffs, true);
+ APInt CIVal(64, CI->getValue().getSExtValue(), true);
+ auto Result = BaseOffs.sadd_ov(CIVal, Overflow);
+ if (!Overflow) {
+ // Fold in immediates if legal for the target.
+ AddrMode.BaseOffs = Result.getSExtValue();
+ 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