How is the size of the shamt checked for SLL?

Hello,

according to the specification

SLL, SRL, and SRA perform logical left, logical right, and arithmetic right shifts on the value in register rs1 by the shift amount held in the lower 5 bits of register rs2 .

But if I look at the pattern and the selectShiftMask, I cannot see where the check is for rs2. Can somebody explain how LLVM knows that the value of the register will not be higher than 5 bits? I think that I understand the first case with ISD::AND but I don’t understand why the function returns true when no condition applies (the last return).

Thank you!

Hardware only uses the lower 5-bits. The upper bits can have any value. Think of it as there being an implicit AND with 31 in the hardware. LLVM doesn’t need to check anything.

LLVM IR and SelectionDAG have undefined behavior if we can prove the shift amount is larger than 31. It’s also undefined behavior for C and C++.

Sometimes the user may have written & 31 to prevent an out of bounds shift. Since the hardware has an implicit AND we can remove the explicit AND as an optimization. That’s what the code you referenced does.

Thank you!