[llvm] [SCEV] Avoid erase+insert in constant folding (PR #101642)
Philip Reames via llvm-commits
llvm-commits at lists.llvm.org
Thu Aug 15 08:55:55 PDT 2024
================
@@ -844,34 +844,39 @@ static const SCEV *
constantFoldAndGroupOps(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT,
SmallVectorImpl<const SCEV *> &Ops, FoldT Fold,
IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
- const SCEVConstant *Folded = nullptr;
+ bool HasConst = false;
for (unsigned Idx = 0; Idx < Ops.size();) {
const SCEV *Op = Ops[Idx];
if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
- if (!Folded)
- Folded = C;
- else
- Folded = cast<SCEVConstant>(
- SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
- Ops.erase(Ops.begin() + Idx);
- continue;
+ if (!HasConst) {
+ // Move the constant to the start.
+ std::swap(Ops[0], Ops[Idx]);
+ HasConst = true;
+ } else {
+ Ops[0] = SE.getConstant(
+ Fold(cast<SCEVConstant>(Ops[0])->getAPInt(), C->getAPInt()));
+ Ops.erase(Ops.begin() + Idx);
+ // Revisit this index.
+ continue;
+ }
}
++Idx;
}
- if (Ops.empty()) {
- assert(Folded && "Must have folded value");
- return Folded;
- }
+ if (Ops.size() == 1)
+ return Ops[0];
- if (Folded && IsAbsorber(Folded->getAPInt()))
- return Folded;
+ if (HasConst && IsIdentity(cast<SCEVConstant>(Ops[0])->getAPInt())) {
+ Ops.erase(Ops.begin());
+ HasConst = false;
+ }
- GroupByComplexity(Ops, &LI, DT);
- if (Folded && !IsIdentity(Folded->getAPInt()))
- Ops.insert(Ops.begin(), Folded);
+ if (Ops.size() == 1 ||
+ (HasConst && IsAbsorber(cast<SCEVConstant>(Ops[0])->getAPInt())))
----------------
preames wrote:
Minor, but you can move this up inside a HasConstant check, along side the IsIdentity. We know that a single value can't be both identity and absorber, so there's an implicit else-if there.
https://github.com/llvm/llvm-project/pull/101642
More information about the llvm-commits
mailing list