Skip to content

cmd/compile: treat bool-to-int conversion as a constant for optimization for more complex patterns #62049

@dsnet

Description

@dsnet

A common argument against #9367 and #45320 is that it's trivial to just write a helper function to convert bools to ints.

However, this breaks compiler optimizations related to constant propagation.

Consider the following benchmark:

type Option interface{ option() }

type flags uint64
func (flags) option() {}

func WithRed(v bool) Option {
	return flags(btoi(v) << 15)
}

func btoi(b bool) int {
	if b {
		return 1
	} else {
		return 0
	}
}

func WithGreen(v bool) Option {
	if v {
		return flags(1 << 15)
	} else {
		return flags(0)
	}
}

var sink Option

func BenchmarkRed(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		sink = WithRed(true)
	}
}

func BenchmarkGreen(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		sink = WithGreen(true)
	}
}

Both WithRed and WithGreen are semantically equivalent, but WithGreen is dramatically faster as it does not allocate.

BenchmarkRed
BenchmarkRed-24      	100000000	        10.50 ns/op	       8 B/op	       1 allocs/op
BenchmarkGreen
BenchmarkGreen-24    	1000000000	         0.4373 ns/op	       0 B/op	       0 allocs/op

Barring the acceptance of #9367 or #45320, we should make the compiler make constant propagation work across bool-to-int helpers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureRequestIssues asking for a new feature that does not need a proposal.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

    Status

    Todo

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions