forbid inlining in golang
Asked Answered
S

2

6

is there any way to instruct the go compiler to not inline?

$ cat primes.go
package main
import ("fmt")

func isPrime(p int) bool {
    for i := 2; i < p; i += 1 {
        for j := 2; j < p; j += 1 {
            if i*j == p {
                return false
            }
        }
    }
    return true
}

func main() {
    for p := 2; p < 100; p+= 1 {
        if isPrime(p) {
            fmt.Println(p)
        }
    }
}
$ go build primes.go
$ objdump -D -S primes > primes.human
$ grep -rn "isPrime" primes.human
210091:        if isPrime(p) {

the equivalent to gcc -O0 I guess - does it exist?

Suter answered 7/7, 2021 at 5:57 Comment(0)
C
13

You may use the //go:noinline pragma to disable inlining of specific functions. Place it before the function you wish to apply it on:

//go:noinline
func isPrime(p int) bool {
    // ...
}

If you want to disable all inlinings, you may use the -gcflags=-l flag, e.g.:

go build -gcflags=-l primes.go

See related blog post: Dave Cheney: Mid-stack inlining in Go

Corriecorriedale answered 7/7, 2021 at 6:21 Comment(0)
F
5

You can read the documentation of golang about compile

godoc/compile

//go:noinline

The //go:noinline directive must be followed by a function declaration. It specifies that calls to the function should not be inlined, overriding the compiler's usual optimization rules. This is typically only needed for special runtime functions or when debugging the compiler.

In short, you only need to add //go:noinline to the line above your isPrime function.

//go:noinline
func isPrime(p int) bool {
    // ...
}
Fallacious answered 7/7, 2021 at 6:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.