Skip to content

cmd/compile: loop optimization #24240

Open
@MichaelTJones

Description

@MichaelTJones

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

master (1.11 dev)

Does this issue reproduce with the latest release?

this is a compilation strategy proposal

What operating system and processor architecture are you using (go env)?

amd64 / Darwin (macbook pro)

What did you do?

I have code that iterates without referencing the loop variable. Changing that from:

for i := 0; i < n; i++ {
// no access to i
}

...to...

for i := -n; i < 0; i++ {
// no access to i
}

saves me 4%-5% in my test cases.

Looking at the .S files, I see that there are two gains (as expected): one is that the loop limit needs only be addressable and referenced at the start of the loop--which frees a register over the body of the loop; and also, because the test is against zero and there are dedicated instructions for that rather than loading immediate literals or otherwise.

It seems (from afar) that there could be a rule along the lines of:

if loop variable not referenced in body
and assignment has block structure (i:=)
and type of loop variable is signed
and incr RHS does not depend on additive offset to variable (i++ ok, i*=2 not),
then transform "for v := low; v OP high; incr" into "for v := low-high; v OP 0; incr"

I don't have any comprehensive data about how common this situation may be, but it does help.

What did you expect to see?

no change because i expected the compiler to be doing this.

What did you see instead?

5% speedup

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.Performancecompiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions