]> Cypherpunks repositories - gostls13.git/commitdiff
cmd/compile: optimize len check when make slice
authorCuong Manh Le <cuong.manhle.vn@gmail.com>
Tue, 31 Mar 2020 22:27:49 +0000 (05:27 +0700)
committerMatthew Dempsky <mdempsky@google.com>
Tue, 31 Mar 2020 23:39:12 +0000 (23:39 +0000)
In CL 226278, we did:

if len < 0 { panicmakeslicelen }
if len > cap { panicmakeslicecap }

But due to the fact that cap is constrained to [0,2^31), so it is safe
to do:

if uint64(len) > cap {
    if len < 0 { panicmakeslicelen() }
    panicmakeslicecap()
}

save us a comparison in common case when len is within range.

Passes toolstash-check.

Change-Id: I0ebd52914ccde4cbb45f16c9e020b0c8f42e0663
Reviewed-on: https://go-review.googlesource.com/c/go/+/226737
Run-TryBot: Cuong Manh Le <cuong.manhle.vn@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
src/cmd/compile/internal/gc/walk.go

index dfc9d9aa225f91685e6b30146d436c128d9b2645..14d088c7fd74c5e64583755074b970b8d8e7f276 100644 (file)
@@ -1338,15 +1338,16 @@ opswitch:
                                Fatalf("walkexpr: invalid index %v", r)
                        }
 
-                       // if len < 0 { panicmakeslicelen }
-                       nif := nod(OIF, nod(OLT, l, nodintconst(0)), nil)
-                       nif.Nbody.Set1(mkcall("panicmakeslicelen", nil, init))
-                       nif = typecheck(nif, ctxStmt)
-                       init.Append(nif)
-
-                       // if len > cap { panicmakeslicecap }
-                       nif = nod(OIF, nod(OGT, conv(l, types.Types[TUINT64]), nodintconst(i)), nil)
-                       nif.Nbody.Set1(mkcall("panicmakeslicecap", nil, init))
+                       // cap is constrained to [0,2^31), so it's safe to do:
+                       //
+                       // if uint64(len) > cap {
+                       //     if len < 0 { panicmakeslicelen() }
+                       //     panicmakeslicecap()
+                       // }
+                       nif := nod(OIF, nod(OGT, conv(l, types.Types[TUINT64]), nodintconst(i)), nil)
+                       niflen := nod(OIF, nod(OLT, l, nodintconst(0)), nil)
+                       niflen.Nbody.Set1(mkcall("panicmakeslicelen", nil, init))
+                       nif.Nbody.Append(niflen, mkcall("panicmakeslicecap", nil, init))
                        nif = typecheck(nif, ctxStmt)
                        init.Append(nif)