Skip to content

cmd/compile: strings.HasSuffix has extra bounds check (len(s)-delta) #76304

@fice-t

Description

@fice-t

Go version

go version go1.26-devel_704f841 Thu Nov 13 15:16:31 2025 -0800 linux/amd64

Output of go env in your module/workspace:

Workspace is `go.godbolt.org` on `x86-64 gc (tip)` as above.

What did you do?

[Note: Code/output below was tested here]

Compile the following function from the strings library:

func HasSuffix(s, suffix string) bool {
	return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
}

What did you see happen?

Assembly contains an extra check that jumps to a section containing CALL runtime.panicBounds(SB).

What did you expect to see?

Assembly does not contain that check or section.

The relevant part:

        CMPQ    DI, BX
        JGT     command-line-arguments_HasSuffix_pc86
        MOVQ    BX, DX
        SUBQ    DI, BX
        CMPQ    DX, BX
        JCS     command-line-arguments_HasSuffix_pc94 ; <- panic section

Assuming DI and BX are both non-negative, then the JCS will never jump (as DI <= BX).

In searching for similar issues, I found #27251, which contains this commit explicitly mentioning HasSuffix that caused a regression. Hopefully there's a solution that doesn't regress on that front.

Edit: I misread the commit message: that commit is only for literal suffixes, and indeed the test case for the general case is still marked todo.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugReportIssues describing a possible bug in the Go implementation.compiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions