Skip to content

Commit 22e1f66

Browse files
committed
[SCCP] add helper function for replacing signed operations; NFC
Preliminary refactoring for planned enhancement in D133198.
1 parent bddbd40 commit 22e1f66

File tree

1 file changed

+38
-17
lines changed

1 file changed

+38
-17
lines changed

llvm/lib/Transforms/Scalar/SCCP.cpp

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,41 @@ static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
154154
return true;
155155
}
156156

157+
/// Try to replace signed instructions with their unsigned equivalent.
158+
static bool replaceSignedInst(SCCPSolver &Solver,
159+
SmallPtrSetImpl<Value *> &InsertedValues,
160+
Instruction &Inst) {
161+
// Determine if a signed value is known to be >= 0.
162+
auto isNonNegative = [&Solver](Value *V) {
163+
const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
164+
return IV.isConstantRange(/*UndefAllowed=*/false) &&
165+
IV.getConstantRange().isAllNonNegative();
166+
};
167+
168+
Instruction *NewInst = nullptr;
169+
switch (Inst.getOpcode()) {
170+
case Instruction::SExt: {
171+
// If the source value is not negative, this is a zext.
172+
Value *Op0 = Inst.getOperand(0);
173+
if (isa<Constant>(Op0) || InsertedValues.count(Op0) || !isNonNegative(Op0))
174+
return false;
175+
NewInst = new ZExtInst(Op0, Inst.getType(), "", &Inst);
176+
break;
177+
}
178+
default:
179+
return false;
180+
}
181+
182+
// Wire up the new instruction and update state.
183+
assert(NewInst && "Expected replacement instruction");
184+
NewInst->takeName(&Inst);
185+
InsertedValues.insert(NewInst);
186+
Inst.replaceAllUsesWith(NewInst);
187+
Solver.removeLatticeValueFor(&Inst);
188+
Inst.eraseFromParent();
189+
return true;
190+
}
191+
157192
static bool simplifyInstsInBlock(SCCPSolver &Solver, BasicBlock &BB,
158193
SmallPtrSetImpl<Value *> &InsertedValues,
159194
Statistic &InstRemovedStat,
@@ -168,23 +203,9 @@ static bool simplifyInstsInBlock(SCCPSolver &Solver, BasicBlock &BB,
168203

169204
MadeChanges = true;
170205
++InstRemovedStat;
171-
} else if (isa<SExtInst>(&Inst)) {
172-
Value *ExtOp = Inst.getOperand(0);
173-
if (isa<Constant>(ExtOp) || InsertedValues.count(ExtOp))
174-
continue;
175-
const ValueLatticeElement &IV = Solver.getLatticeValueFor(ExtOp);
176-
if (!IV.isConstantRange(/*UndefAllowed=*/false))
177-
continue;
178-
if (IV.getConstantRange().isAllNonNegative()) {
179-
auto *ZExt = new ZExtInst(ExtOp, Inst.getType(), "", &Inst);
180-
ZExt->takeName(&Inst);
181-
InsertedValues.insert(ZExt);
182-
Inst.replaceAllUsesWith(ZExt);
183-
Solver.removeLatticeValueFor(&Inst);
184-
Inst.eraseFromParent();
185-
InstReplacedStat++;
186-
MadeChanges = true;
187-
}
206+
} else if (replaceSignedInst(Solver, InsertedValues, Inst)) {
207+
MadeChanges = true;
208+
++InstReplacedStat;
188209
}
189210
}
190211
return MadeChanges;

0 commit comments

Comments
 (0)