Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions tools/customlint/implicitfma.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package customlint

import (
"go/ast"
"go/token"
"go/types"

"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/buildssa"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/ssa"
)

var implicitFMAAnalyzer = &analysis.Analyzer{
Name: "implicitfma",
Doc: "finds floating-point additions and subtractions that may use implicit FMA",
Requires: []*analysis.Analyzer{
buildssa.Analyzer,
inspect.Analyzer,
},
Run: func(pass *analysis.Pass) (any, error) {
return (&implicitFMAPass{pass: pass}).run()
},
}

type implicitFMAPass struct {
pass *analysis.Pass
expressionsByOpPos map[token.Pos]*ast.BinaryExpr
explicitlyRoundedMultiply map[token.Pos]bool
}

func (f *implicitFMAPass) run() (any, error) {
in := f.pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
f.expressionsByOpPos = make(map[token.Pos]*ast.BinaryExpr)
f.explicitlyRoundedMultiply = make(map[token.Pos]bool)

for cursor := range in.Root().Preorder((*ast.BinaryExpr)(nil)) {
expr := cursor.Node().(*ast.BinaryExpr)
f.expressionsByOpPos[expr.OpPos] = expr
if expr.Op == token.MUL {
typeAndValue := f.pass.TypesInfo.Types[expr]
if typeAndValue.Value == nil &&
isFloatingPointType(typeAndValue.Type) &&
f.hasExplicitRoundingConversion(cursor) {
// buildssa removes representation-preserving conversions, even though an
// explicit floating-point conversion forces rounding under the Go spec.
f.explicitlyRoundedMultiply[expr.OpPos] = true
Comment thread
Copilot marked this conversation as resolved.
Outdated
}
}
}

ssaResult := f.pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA)
reported := make(map[token.Pos]bool)
for _, function := range ssaResult.SrcFuncs {
for _, block := range function.Blocks {
for _, instruction := range block.Instrs {
binOp, ok := instruction.(*ssa.BinOp)
if !ok || binOp.Op != token.ADD && binOp.Op != token.SUB || !isFloatingPointType(binOp.Type()) {
continue
}
if !f.reachedByUnroundedMultiplication(binOp.X, make(map[ssa.Value]bool)) &&
!f.reachedByUnroundedMultiplication(binOp.Y, make(map[ssa.Value]bool)) {
continue
}
if reported[binOp.Pos()] {
continue
}
reported[binOp.Pos()] = true

pos := binOp.Pos()
end := pos + 1
if expr := f.expressionsByOpPos[pos]; expr != nil {
pos = expr.Pos()
end = expr.End()
}
f.pass.Report(analysis.Diagnostic{
Pos: pos,
End: end,
Message: "explicitly round the floating-point multiplication result to prevent implicit FMA",
})
}
}
}

return nil, nil
}

func (f *implicitFMAPass) reachedByUnroundedMultiplication(value ssa.Value, seen map[ssa.Value]bool) bool {
if seen[value] {
return false
}
seen[value] = true

switch value := value.(type) {
case *ssa.BinOp:
return value.Op == token.MUL && !f.explicitlyRoundedMultiply[value.Pos()]
case *ssa.ChangeInterface:
return f.reachedByUnroundedMultiplication(value.X, seen)
case *ssa.ChangeType:
return f.reachedByUnroundedMultiplication(value.X, seen)
case *ssa.Phi:
for _, edge := range value.Edges {
if f.reachedByUnroundedMultiplication(edge, seen) {
return true
}
}
case *ssa.UnOp:
if value.Op == token.ADD || value.Op == token.SUB {
return f.reachedByUnroundedMultiplication(value.X, seen)
}
}
return false
}

func (f *implicitFMAPass) hasExplicitRoundingConversion(cursor inspector.Cursor) bool {
for {
parent := cursor.Parent()
switch node := parent.Node().(type) {
case *ast.ParenExpr:
cursor = parent
case *ast.CallExpr:
if len(node.Args) != 1 || node.Args[0] != cursor.Node() {
return false
}
funTypeAndValue, ok := f.pass.TypesInfo.Types[node.Fun]
return ok && funTypeAndValue.IsType() && isFloatingPointType(f.pass.TypesInfo.TypeOf(node))
default:
return false
}
}
}

func isFloatingPointType(t types.Type) bool {
t = types.Unalias(t)
if t == nil {
return false
}

switch t := t.Underlying().(type) {
case *types.Basic:
return t.Info()&types.IsFloat != 0
case *types.Interface:
for embedded := range t.EmbeddedTypes() {
if isFloatingPointType(embedded) {
return true
}
}
return false
case *types.Union:
for term := range t.Terms() {
if isFloatingPointType(term.Type()) {
return true
}
}
return false
default:
return false
}
}
1 change: 1 addition & 0 deletions tools/customlint/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ func (f *plugin) BuildAnalyzers() ([]*analysis.Analyzer, error) {
cleanupAnalyzer,
emptyCaseAnalyzer,
forbidParentAccessAnalyzer,
implicitFMAAnalyzer,
shadowAnalyzer,
unexportedAPIAnalyzer,
}, nil
Expand Down
66 changes: 66 additions & 0 deletions tools/customlint/testdata/implicitfma/implicitfma.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package implicitfma

type namedFloat64 float64

func badFloat64(x, y, z float64) float64 {
return x*y + z
}

func badFloat32(x, y, z float32) float32 {
product := x * y
return z + product
}

func badNamed(x, y, z namedFloat64) namedFloat64 {
return x*y - z*x
}

func badGeneric[T ~float32 | ~float64](x, y, z T) T {
product := x * y
product += z
return product
}

func badConversionAroundSum(x, y, z float64) float64 {
return float64(x*y + z)
}

func goodStandalone(x, y float64) float64 {
return x * y
}

func goodFloat64(x, y, z float64) float64 {
return float64(x*y) + z
}

func goodBothProducts(x, y, z float64) float64 {
return float64(x*y) - float64(z*x)
}

func goodFloatToInt(x, y float64) int {
return int(x * y)
}

func goodReturnRounded(x, y float64) float64 {
return float64(x * y)
}

func goodParenthesized(x, y float64) float64 {
return float64((x * y))
}

func goodNamed(x, y namedFloat64) namedFloat64 {
return namedFloat64(x * y)
}

func goodConversionToNamed(x, y, z float64) namedFloat64 {
return namedFloat64(x*y) + namedFloat64(z)
}

func goodConstant() float64 {
return 1.5 * 2.5
}

func goodInteger(x, y int) int {
return x * y
}
77 changes: 77 additions & 0 deletions tools/customlint/testdata/implicitfma/implicitfma.go.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package implicitfma

type namedFloat64 float64

func badFloat64(x, y, z float64) float64 {
return x*y + z
~~~~~~~
!!! implicitfma: explicitly round the floating-point multiplication result to prevent implicit FMA
}

func badFloat32(x, y, z float32) float32 {
product := x * y
return z + product
~~~~~~~~~~~
!!! implicitfma: explicitly round the floating-point multiplication result to prevent implicit FMA
}

func badNamed(x, y, z namedFloat64) namedFloat64 {
return x*y - z*x
~~~~~~~~~
!!! implicitfma: explicitly round the floating-point multiplication result to prevent implicit FMA
}

func badGeneric[T ~float32 | ~float64](x, y, z T) T {
product := x * y
product += z
~
!!! implicitfma: explicitly round the floating-point multiplication result to prevent implicit FMA
return product
}

func badConversionAroundSum(x, y, z float64) float64 {
return float64(x*y + z)
~~~~~~~
!!! implicitfma: explicitly round the floating-point multiplication result to prevent implicit FMA
}

func goodStandalone(x, y float64) float64 {
return x * y
}

func goodFloat64(x, y, z float64) float64 {
return float64(x*y) + z
}

func goodBothProducts(x, y, z float64) float64 {
return float64(x*y) - float64(z*x)
}

func goodFloatToInt(x, y float64) int {
return int(x * y)
}

func goodReturnRounded(x, y float64) float64 {
return float64(x * y)
}

func goodParenthesized(x, y float64) float64 {
return float64((x * y))
}

func goodNamed(x, y namedFloat64) namedFloat64 {
return namedFloat64(x * y)
}

func goodConversionToNamed(x, y, z float64) namedFloat64 {
return namedFloat64(x*y) + namedFloat64(z)
}

func goodConstant() float64 {
return 1.5 * 2.5
}

func goodInteger(x, y int) int {
return x * y
}

4 changes: 3 additions & 1 deletion tsc/internal/compiler/checkerpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,9 @@ func getCheckerAssociationsInOrder(fileWeights []int, adjacentFiles [][]int, fil
}
oldWeight := float64(checkerWeight)
newWeight := float64(checkerWeight + fileWeights[fileIndex])
penalty := alpha * (newWeight*math.Sqrt(newWeight) - oldWeight*math.Sqrt(oldWeight))
newPenalty := float64(newWeight * math.Sqrt(newWeight))
oldPenalty := float64(oldWeight * math.Sqrt(oldWeight))
penalty := float64(alpha * (newPenalty - oldPenalty))
score := float64(neighborCounts[checkerIndex]) - penalty
if score > bestScore || score == bestScore && (bestChecker < 0 || checkerWeight < checkerWeights[bestChecker]) {
bestChecker = checkerIndex
Expand Down
Loading