Skip to content

Commit eca7daf

Browse files
[CodeGenPrepare] Fix signed overflow
1 parent 1cf5466 commit eca7daf

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

llvm/lib/CodeGen/CodeGenPrepare.cpp

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5447,11 +5447,18 @@ bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
54475447
TPT.getRestorationPoint();
54485448
if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
54495449
if (CI->getValue().isSignedIntN(64)) {
5450-
// Fold in immediates if legal for the target.
5451-
AddrMode.BaseOffs += CI->getSExtValue();
5452-
if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5453-
return true;
5454-
AddrMode.BaseOffs -= CI->getSExtValue();
5450+
// Check if the addition would result in a signed overflow.
5451+
bool Overflow = false;
5452+
APInt BaseOffs(64, AddrMode.BaseOffs, true);
5453+
APInt CIVal(64, CI->getValue().getSExtValue(), true);
5454+
auto Result = BaseOffs.sadd_ov(CIVal, Overflow);
5455+
if (!Overflow) {
5456+
// Fold in immediates if legal for the target.
5457+
AddrMode.BaseOffs = Result.getSExtValue();
5458+
if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5459+
return true;
5460+
AddrMode.BaseOffs -= CI->getSExtValue();
5461+
}
54555462
}
54565463
} else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
54575464
// If this is a global variable, try to fold it into the addressing mode.

0 commit comments

Comments
 (0)