Source file src/simd/godebug_test.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build goexperiment.simdstable
     6  
     7  package simd_test
     8  
     9  import (
    10  	"flag"
    11  	"fmt"
    12  	"internal/cpu"
    13  	"internal/testenv"
    14  	"os"
    15  	"os/exec"
    16  	"runtime"
    17  	"simd"
    18  	"slices"
    19  	"strings"
    20  	"testing"
    21  )
    22  
    23  var (
    24  	listGODEBUGs = flag.Bool("list-godebugs", false, "print the GODEBUG settings to also run the tests under, then exit")
    25  	runGODEBUGs  = flag.Bool("run-godebugs", false, "run the tests under the current GODEBUG setting and each one that -list-godebugs prints")
    26  	printConfig  = flag.Bool("print-config", false, "print how the simd package is configured, then exit")
    27  )
    28  
    29  func TestMain(m *testing.M) {
    30  	flag.Parse()
    31  	switch {
    32  	case *listGODEBUGs:
    33  		// "go tool dist test" runs the tests again under each of
    34  		// these. It looks for lines that start with "GODEBUG=".
    35  		for _, s := range godebugSettings() {
    36  			if !s.current {
    37  				fmt.Println("GODEBUG=" + s.godebug)
    38  			}
    39  		}
    40  	case *runGODEBUGs:
    41  		os.Exit(runUnderGODEBUGs())
    42  	case *printConfig:
    43  		fmt.Println(config())
    44  	default:
    45  		os.Exit(m.Run())
    46  	}
    47  }
    48  
    49  // runUnderGODEBUGs runs the test binary under each of the godebugSettings,
    50  // with the same flags as this process, and returns the exit status for this
    51  // process: 0 if all of the runs passed.
    52  //
    53  // This is "go test simd -run-godebugs", a way to test every implementation
    54  // with one command. "go tool dist test" doesn't use it, because it wants a
    55  // separate result for each test under each setting.
    56  func runUnderGODEBUGs() int {
    57  	exe, err := os.Executable()
    58  	if err != nil {
    59  		fmt.Println("FAIL: -run-godebugs:", err)
    60  		return 1
    61  	}
    62  	// Strip the -run-godebugs flag.
    63  	var args []string
    64  	for _, arg := range os.Args[1:] {
    65  		if name, _, _ := strings.Cut(strings.TrimLeft(arg, "-"), "="); name == "run-godebugs" {
    66  			continue
    67  		}
    68  		args = append(args, arg)
    69  	}
    70  	status := 0
    71  	for _, s := range godebugSettings() {
    72  		fmt.Printf("# GODEBUG=%s\n", s.godebug)
    73  		cmd := exec.Command(exe, args...)
    74  		cmd.Env = append(os.Environ(), "GODEBUG="+s.godebug)
    75  		cmd.Stdout = os.Stdout
    76  		cmd.Stderr = os.Stderr
    77  		if err := cmd.Run(); err != nil {
    78  			fmt.Printf("FAIL: GODEBUG=%s: %v\n", s.godebug, err)
    79  			status = 1
    80  		}
    81  	}
    82  	return status
    83  }
    84  
    85  // A godebugSetting is a GODEBUG setting that selects one of the
    86  // implementations of the simd package that this machine can run.
    87  type godebugSetting struct {
    88  	godebug string // the value of GODEBUG, including any settings it already has
    89  	current bool   // this is the setting that this process is running under
    90  
    91  	// wantConfig is the space-separated parts of config() that the
    92  	// setting must produce. It is not set for the current setting.
    93  	wantConfig string
    94  }
    95  
    96  // godebugSettings returns the GODEBUG settings that select each
    97  // implementation of the simd package that this machine can run. The first is
    98  // the current setting.
    99  //
   100  // The simd package selects an implementation based on the CPU, such as the
   101  // largest vector size the CPU supports, so by default the tests only test
   102  // that one. The others are what programs use on CPUs with fewer features.
   103  // To test them too, "go tool dist test" uses the -list-godebugs flag to get
   104  // the other settings and runs the tests again under each one. Which settings
   105  // work depends on the CPU, which is why dist has to ask. The -run-godebugs
   106  // flag runs the tests under all of them from a single "go test".
   107  func godebugSettings() []godebugSetting {
   108  	current := os.Getenv("GODEBUG")
   109  	settings := []godebugSetting{{godebug: current, current: true}}
   110  	if simd.Emulated() {
   111  		// The emulation is the only implementation.
   112  		return settings
   113  	}
   114  	// Each setting adds to the value that GODEBUG already has. Where
   115  	// that value sets the same name, the addition wins, because it comes
   116  	// later in the value.
   117  	prefix := current
   118  	if prefix != "" {
   119  		prefix += ","
   120  	}
   121  	// Each smaller vector size, which CPUs with narrower vectors use.
   122  	for bits := simd.VectorBits() / 2; bits >= 128; bits /= 2 {
   123  		settings = append(settings, godebugSetting{
   124  			godebug:    prefix + fmt.Sprintf("simd=%d", bits),
   125  			wantConfig: fmt.Sprintf("VectorBits=%d Emulated=false", bits),
   126  		})
   127  	}
   128  	// The emulation, which CPUs without SIMD use.
   129  	settings = append(settings, godebugSetting{
   130  		godebug:    prefix + "simd=0",
   131  		wantConfig: "Emulated=true",
   132  	})
   133  	// The rest of the settings turn off CPU features.
   134  	if !cpuOptionsWork() {
   135  		return settings
   136  	}
   137  	// The fallbacks for carryless multiply, which archsimd uses on CPUs
   138  	// that lack the instruction for it.
   139  	switch runtime.GOARCH {
   140  	case "amd64":
   141  		// Each vector size has its own instruction and fallbacks. If
   142  		// the CPU lacks an instruction, the tests already test its
   143  		// fallback.
   144  		for bits := simd.VectorBits(); bits >= 128; bits /= 2 {
   145  			size := prefix + fmt.Sprintf("simd=%d,", bits)
   146  			want := fmt.Sprintf("VectorBits=%d Emulated=false", bits)
   147  			if bits > 128 && cpu.X86.HasVPCLMULQDQ {
   148  				// Without VPCLMULQDQ, archsimd applies the Uint64x2
   149  				// instruction to each 128-bit part of wider vectors.
   150  				settings = append(settings, godebugSetting{godebug: size + "cpu.vpclmulqdq=off", wantConfig: want + " CLMUL=Uint64x2"})
   151  			}
   152  			if cpu.X86.HasPCLMULQDQ {
   153  				// Without PCLMULQDQ, archsimd uses software.
   154  				settings = append(settings, godebugSetting{godebug: size + "cpu.pclmulqdq=off", wantConfig: want + " CLMUL=software"})
   155  			}
   156  		}
   157  	case "arm64":
   158  		// Without PMULL, archsimd emulates carryless multiply using
   159  		// the 8-bit PMULL on Uint8x16. If PMULL is already off, because
   160  		// the CPU lacks it or because GODEBUG turns it off, the
   161  		// current setting tests that.
   162  		if cpu.ARM64.HasPMULL {
   163  			settings = append(settings, godebugSetting{
   164  				godebug:    prefix + "cpu.pmull=off",
   165  				wantConfig: "Emulated=false CLMUL=Uint8x16",
   166  			})
   167  		}
   168  	}
   169  	return settings
   170  }
   171  
   172  // cpuOptionsWork reports whether GODEBUG=cpu.X=off settings take effect on
   173  // this operating system. The runtime only applies them where it can read
   174  // the environment early enough in startup, and ignores them elsewhere, such
   175  // as on Windows. See getGodebugEarly in package runtime.
   176  func cpuOptionsWork() bool {
   177  	switch runtime.GOOS {
   178  	case "aix", "darwin", "ios", "dragonfly", "freebsd", "netbsd", "openbsd", "illumos", "solaris", "linux":
   179  		return true
   180  	}
   181  	return false
   182  }
   183  
   184  // config returns how the simd package is configured in this process.
   185  func config() string {
   186  	return fmt.Sprintf("VectorBits=%d Emulated=%t CLMUL=%s",
   187  		simd.VectorBits(), simd.Emulated(), simd.InternalCLMULImpl())
   188  }
   189  
   190  // TestGODEBUGSettings checks that each of the godebugSettings configures the
   191  // simd package the way it is meant to, so that running the tests under it
   192  // tests what it is meant to.
   193  func TestGODEBUGSettings(t *testing.T) {
   194  	settings := godebugSettings()
   195  	if len(settings) == 1 {
   196  		t.Log("simd is emulated, so there are no other implementations to select")
   197  		return
   198  	}
   199  	exe := testenv.Executable(t)
   200  	for _, s := range settings {
   201  		if s.current {
   202  			continue
   203  		}
   204  		t.Run(s.godebug, func(t *testing.T) {
   205  			cmd := testenv.Command(t, exe, "-print-config")
   206  			cmd.Env = append(cmd.Environ(), "GODEBUG="+s.godebug)
   207  			out, err := cmd.CombinedOutput()
   208  			if err != nil {
   209  				t.Fatalf("with GODEBUG=%s: %v\n%s", s.godebug, err, out)
   210  			}
   211  			// Check that the fields in s.wantConfig are a subset
   212  			// of what -print-config printed.
   213  			got := strings.Fields(string(out))
   214  			for _, want := range strings.Fields(s.wantConfig) {
   215  				if !slices.Contains(got, want) {
   216  					t.Errorf("with GODEBUG=%s, simd is configured as %q, want %s", s.godebug, strings.TrimSpace(string(out)), want)
   217  				}
   218  			}
   219  		})
   220  	}
   221  }
   222  

View as plain text