]> Cypherpunks.ru repositories - gostls13.git/commitdiff
cmd/compile: avoid slicebytetostring call in len(string([]byte))
authorCuong Manh Le <cuong.manhle.vn@gmail.com>
Tue, 23 May 2023 04:23:48 +0000 (11:23 +0700)
committerGopher Robot <gobot@golang.org>
Tue, 23 May 2023 19:27:38 +0000 (19:27 +0000)
Change-Id: Ie04503e61400a793a6a29a4b58795254deabe472
Reviewed-on: https://go-review.googlesource.com/c/go/+/497276
Reviewed-by: Keith Randall <khr@golang.org>
Auto-Submit: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Run-TryBot: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Reviewed-by: Keith Randall <khr@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
src/cmd/compile/internal/walk/builtin.go
test/codegen/strings.go

index 528296e99dd8ffe2d0809a9e869764d09d5cfdb9..5c924a90c5cbe848d8363dcc66adbd23c876afa3 100644 (file)
@@ -250,6 +250,10 @@ func walkLenCap(n *ir.UnaryExpr, init *ir.Nodes) ir.Node {
                // Replace len([]rune(string)) with runtime.countrunes(string).
                return mkcall("countrunes", n.Type(), init, typecheck.Conv(n.X.(*ir.ConvExpr).X, types.Types[types.TSTRING]))
        }
+       if isByteCount(n) {
+               _, len := backingArrayPtrLen(cheapExpr(n.X.(*ir.ConvExpr).X, init))
+               return len
+       }
 
        n.X = walkExpr(n.X, init)
 
@@ -862,3 +866,9 @@ func writebarrierfn(name string, l *types.Type, r *types.Type) ir.Node {
 func isRuneCount(n ir.Node) bool {
        return base.Flag.N == 0 && !base.Flag.Cfg.Instrumenting && n.Op() == ir.OLEN && n.(*ir.UnaryExpr).X.Op() == ir.OSTR2RUNES
 }
+
+// isByteCount reports whether n is of the form len(string([]byte)).
+func isByteCount(n ir.Node) bool {
+       return base.Flag.N == 0 && !base.Flag.Cfg.Instrumenting && n.Op() == ir.OLEN &&
+               (n.(*ir.UnaryExpr).X.Op() == ir.OBYTES2STR || n.(*ir.UnaryExpr).X.Op() == ir.OBYTES2STRTMP)
+}
index a2c2fc0a629b0cfd256527b6c40e69623dbe8d75..94512f5cd3253bfa0c3c9aabd6eac3086b8d281c 100644 (file)
@@ -14,6 +14,11 @@ func CountRunes(s string) int { // Issue #24923
        return len([]rune(s))
 }
 
+func CountBytes(s []byte) int {
+       // amd64:-`.*runtime.slicebytetostring`
+       return len(string(s))
+}
+
 func ToByteSlice() []byte { // Issue #24698
        // amd64:`LEAQ\ttype:\[3\]uint8`
        // amd64:`CALL\truntime\.newobject`