Skip to content

cmd/compile: optimize division for positive integers #36159

Closed
@rillig

Description

@rillig

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

go version go1.13.1 windows/amd64

Does this issue reproduce with the latest release?

yes

What did you do?

func Indent(width int) string {
	const tabsAndSpaces = "\t\t\t\t\t\t\t\t\t       "
	middle := len(tabsAndSpaces) - 7
	if width >= 0 && width <= 8*middle+7 {
		start := middle - width/8
		end := middle + width%8
		return tabsAndSpaces[start:end]
	}
	return strings.Repeat("\t", width/8) + "       "[:width%8]
}

What did you expect to see?

Since the variable width has bounds checks and is thus guaranteed to be positive, the generated code omits the extra instructions for negative numbers.

In general, I prefer to write arithmetic expressions in my code instead of bit manipulations because the expressions width/8 and width%8 pair up nicely. In contrast, width>>3 and width&7 requires more thought.

What did you see instead?

  util.go:7   MOVQ BX, SI				
  util.go:7   SARQ $0x3f, BX				
  util.go:7   SHRQ $0x3d, BX				
  util.go:7   ADDQ SI, BX				
  util.go:7   SARQ $0x3, BX				
  util.go:8   MOVQ BX, DI				
  util.go:8   SHLQ $0x3, BX				
  util.go:8   SUBQ BX, SI				
  util.go:8   LEAQ 0x9(SI), CX			

The SARQ and SHRQ are not necessary here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.Performance

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions