From fc4857e98c1c315a92ed687bc45ff895f0eb9600 Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Sat, 4 Apr 2020 14:58:56 +0200 Subject: [PATCH] runtime: avoid recursion in printuint64 function This function is called from runtime.printitf, which is called from runtime._panic, and is therefore the leaf function of many call paths. This makes analyzing stack usage very difficult. Also forwarding printuint32 to printuint64 as it reduces code size in the few examples I've tested. Printing numbers is not often done so it doesn't matter if it's a bit slow (the serial connection is probably slower anyway). --- src/runtime/print.go | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/runtime/print.go b/src/runtime/print.go index 37a6a5821..e4d715176 100644 --- a/src/runtime/print.go +++ b/src/runtime/print.go @@ -47,23 +47,8 @@ func printint16(n int16) { printint32(int32(n)) } -//go:nobounds func printuint32(n uint32) { - digits := [10]byte{} // enough to hold (2^32)-1 - // Fill in all 10 digits. - firstdigit := 9 // digit index that isn't zero (by default, the last to handle '0' correctly) - for i := 9; i >= 0; i-- { - digit := byte(n%10 + '0') - digits[i] = digit - if digit != '0' { - firstdigit = i - } - n /= 10 - } - // Print digits without the leading zeroes. - for i := firstdigit; i < 10; i++ { - putchar(digits[i]) - } + printuint64(uint64(n)) } func printint32(n int32) { @@ -76,12 +61,23 @@ func printint32(n int32) { printuint32(uint32(n)) } +//go:nobounds func printuint64(n uint64) { - prevdigits := n / 10 - if prevdigits != 0 { - printuint64(prevdigits) + digits := [20]byte{} // enough to hold (2^64)-1 + // Fill in all 10 digits. + firstdigit := 19 // digit index that isn't zero (by default, the last to handle '0' correctly) + for i := 19; i >= 0; i-- { + digit := byte(n%10 + '0') + digits[i] = digit + if digit != '0' { + firstdigit = i + } + n /= 10 + } + // Print digits without the leading zeroes. + for i := firstdigit; i < 20; i++ { + putchar(digits[i]) } - putchar(byte((n % 10) + '0')) } func printint64(n int64) {