From: Martin Möhrmann Date: Sun, 6 May 2018 10:19:25 +0000 (+0200) Subject: strconv: add comment explaining bounded shift in formatBits X-Git-Tag: go1.12beta1~764 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=f81d73e8d57c99d32744e61940dad08c4ec07111;p=gostls13.git strconv: add comment explaining bounded shift in formatBits The compiler can generate better code for shifts bounded to be less than 32 and thereby known to be less than any register width. See https://golang.org/cl/109776. Change-Id: I0c4c9f0faafa065fce3c10fd328830deb92f9e38 Reviewed-on: https://go-review.googlesource.com/c/111735 Run-TryBot: Martin Möhrmann TryBot-Result: Gobot Gobot Reviewed-by: Robert Griesemer Reviewed-by: Brad Fitzpatrick --- diff --git a/src/strconv/itoa.go b/src/strconv/itoa.go index 8afe7af251..4aaf57830c 100644 --- a/src/strconv/itoa.go +++ b/src/strconv/itoa.go @@ -152,10 +152,14 @@ func formatBits(dst []byte, u uint64, base int, neg, append_ bool) (d []byte, s } } else if isPowerOfTwo(base) { - // It is known that base is a power of two and - // 2 <= base <= len(digits). // Use shifts and masks instead of / and %. - shift := uint(bits.TrailingZeros(uint(base))) & 31 + // Base is a power of 2 and 2 <= base <= len(digits) where len(digits) is 36. + // The largest power of 2 below or equal to 36 is 32, which is 1 << 5; + // i.e., the largest possible shift count is 5. By &-ind that value with + // the constant 7 we tell the compiler that the shift count is always + // less than 8 which is smaller than any register width. This allows + // the compiler to generate better code for the shift operation. + shift := uint(bits.TrailingZeros(uint(base))) & 7 b := uint64(base) m := uint(base) - 1 // == 1<= b {