[llvm] [IndVarSimplify] Keep additional nuw and nsw flags during LinearFunctionTestReplace (PR #177433)
Antonio Frighetto via llvm-commits
llvm-commits at lists.llvm.org
Mon May 4 01:08:15 PDT 2026
================
@@ -1110,10 +1110,46 @@ linearFunctionTestReplace(Loop *L, BasicBlock *ExitingBB,
// dead, it could not be poison on the first iteration in the first place.)
if (auto *BO = dyn_cast<BinaryOperator>(IncVar)) {
const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IncVar));
+
+ // However, if we successfully computed an ExitCount, we can infer nowrap
+ // properties from the original loop exit condition. If the original
+ // comparison was signed and SCEV computed an exit count, then NSW is safe.
+ // Similarly, if it was unsigned, NUW is safe. This is because SCEV's exit
+ // count analysis proves the loop exits before overflow occurs for that
+ // signedness.
+ bool KeepNSW = false;
+ bool KeepNUW = false;
+
+ CondBrInst *BI = cast<CondBrInst>(ExitingBB->getTerminator());
+ if (auto *OrigCmp = dyn_cast<ICmpInst>(BI->getCondition())) {
+ // Check if the chosen IV is actually used in the original comparison.
+ bool IVUsedInOriginalCmp = (OrigCmp->getOperand(0) == IndVar ||
+ OrigCmp->getOperand(0) == IncVar ||
+ OrigCmp->getOperand(1) == IndVar ||
+ OrigCmp->getOperand(1) == IncVar);
+
+ if (IVUsedInOriginalCmp) {
+ ICmpInst::Predicate Pred = OrigCmp->getPredicate();
+
+ // If the original comparison was signed, SCEV proved NSW is safe.
+ KeepNSW = ICmpInst::isSigned(Pred);
----------------
antoniofrighetto wrote:
Indeed the last incorrect refinement can be reproduced even without samesign: https://alive2.llvm.org/ce/z/w_YcsJ, which admittedly makes me a bit dubious on the premise that the PR does. Though maybe you are correct that we would never preserve `nsw` here, as slt gets canonicalized to samesign ult (and, even before, the predicate was canonicalized to unsigned as SCEV proved non-negative the pre-increment AddRec). I think I have no other concerns here, though I'd like @nikic to take another look at this well.
https://github.com/llvm/llvm-project/pull/177433
More information about the llvm-commits
mailing list