Skip to content

Commit bbb1bd8

Browse files
committed
optimized loop to nlog(n) time complexity!
1 parent 0ee0e03 commit bbb1bd8

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

llvm/lib/Analysis/DemandedBits.cpp

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,13 @@ void DemandedBits::determineLiveOperandBits(
8181
auto Shift = ShiftLeft ? static_cast<ShiftFn>(&APInt::shl)
8282
: static_cast<ShiftFn>(&APInt::lshr);
8383
AB = APInt::getZero(BitWidth);
84-
for (unsigned ShiftAmount = Min; ShiftAmount <= Max; ++ShiftAmount) {
85-
AB |= (AOut.*Shift)(ShiftAmount);
84+
uint8_t LoopRange = Max - Min;
85+
auto Mask = AOut;
86+
for (unsigned ShiftAmnt = 1; ShiftAmnt <= LoopRange; ShiftAmnt <<= 1) {
87+
APInt Shifted = (Mask.*Shift)(ShiftAmnt);
88+
Mask |= Shifted;
8689
}
90+
AB = (Mask.*Shift)(Min);
8791
};
8892

8993
switch (UserI->getOpcode()) {
@@ -221,13 +225,17 @@ void DemandedBits::determineLiveOperandBits(
221225
ComputeKnownBits(BitWidth, UserI->getOperand(1), nullptr);
222226
unsigned Min = Known.getMinValue().getLimitedValue(BitWidth - 1);
223227
unsigned Max = Known.getMaxValue().getLimitedValue(BitWidth - 1);
224-
// Suppose AOut == 0b0000 1001
228+
// Suppose AOut == 0b0000 0001
225229
// [min, max] = [1, 3]
226-
// shift by 1 we get 0b0001 0010
227-
// shift by 2 we get 0b0010 0100
228-
// shift by 3 we get 0b0100 1000
229-
// we take the or for every shift to cover all the positions.
230+
// iteration 1 shift by 1 mask is 0b0000 0011
231+
// iteration 2 shift by 2 mask is 0b0000 1111
232+
// iteration 3, shiftAmnt = 4 > max - min, we stop.
230233
//
234+
// After the iterations we need one more shift by min,
235+
// to move from 0b0000 1111 to --> 0b0001 1110.
236+
// The loop populates the mask relative to (0,...,max-min),
237+
// but we need coverage from (min, max).
238+
// This is why the shift by min is needed.
231239
GetShiftedRange(Min, Max, /*ShiftLeft=*/true);
232240
if (cast<LShrOperator>(UserI)->isExact())
233241
AB |= APInt::getLowBitsSet(BitWidth, Max);

0 commit comments

Comments
 (0)