Is it possible to include inline assembly in Go code?

后端 未结 5 1984
眼角桃花
眼角桃花 2021-01-30 10:52

Is it possible to include inline assembly in Go code?

5条回答
  •  无人及你
    2021-01-30 11:20

    No, you can't, but it is easy to provide an assembly implementation of just one function by using the go compiler. There is no need to use "Import C" to use assembly.

    Take a look at an example from the math library:

    http://golang.org/src/pkg/math/abs.go : The Abs function is declared in this go file. (There is also an implementation of abs in go in this file, but this isn't exported as it has a lower-case name.)

    package math
    
    // Abs returns the absolute value of x.
    //
    // Special cases are:
    //  Abs(±Inf) = +Inf
    //  Abs(NaN) = NaN
    func Abs(x float64) float64
    

    Then, in http://golang.org/src/pkg/math/abs_amd64.s , Abs is implemented for intel 64 bit in this file:

    #include "textflag.h"
    
    // func Abs(x float64) float64
    TEXT ·Abs(SB),NOSPLIT,$0
        MOVQ   $(1<<63), BX
        MOVQ   BX, X0 // movsd $(-0.0), x0
        MOVSD  x+0(FP), X1
        ANDNPD X1, X0
        MOVSD  X0, ret+8(FP)
        RET
    

    One problem with assembly functions like this is that they aren't inlined by the go compiler, so there's a limit to how much performance you can gain if you're calling a small function many times. The abs function is no longer implemented in assembly in the go library. I would say that the go compiler has improved such that with inlining it is faster for compiling the abs function without assembly in more recent go releases.

提交回复
热议问题