On Wed, Feb 22, 2017 at 12:22 AM, Jiajun Huang <ganst...@gmail.com> wrote:
> Hello, I'm reading golang source code, it's in version 1.8. some times, I
> got some functions like: (runtime/proc.go, function main):
>
>    107 func main() {
>    108     g := getg()
>    109
>    110     // Racectx of m0->g0 is used only as the parent of the main
> goroutine.
>    111     // It must not be used for anything else.
>    112     g.m.g0.racectx = 0
>
> I got the function, getg, and located it in(runtime/stubs.go):
>
>    18 // getg returns the pointer to the current g.
>    19 // The compiler rewrites calls to this function into instructions
>    20 // that fetch the g directly (from TLS or from the dedicated
> register).
>    21 func getg() *g
>    22
>
> I've search the golang source code library for it, but results doesn't
> contain the definition. and the comment say, The compiler rewrites calls to
> this function into instructions, so where can I find the rewritten Assembly
> code?

It's not easy.  The getg function is translated into the SSA operation
OpGetG.  That is rewritten by processor-specific rules listed in
cmd/compile/internal/ssa/gen.  On amd64 we see (in files in
cmd/compile/internal/ssa/gen)
    (GetG mem) -> (LoweredGetG mem)
and a pseudo-op
     {name: "LoweredGetG", argLength: 1, reg: gp01}, // arg0=mem
Then we can look over in cmd/compile/internal/amd64/ssa.go where we
can see the handling of OpAMD64LoweredGetG.  That is where getg gets
turned into actual machine instructions, although they aren't written
in assembler but rather in the internal format that cmd/asm parses
instructions into.  Basically, on amd64, it's a load from a TLS
pseudo-register.  The handling of REG_TLS is over in
cmd/internal/obj/x86/asm6.go where we can finally see the instruction
prefix being used, which generates %gs or %fs depending on the system
and whether this is 386 or amd64.

Really a much simpler way to see what the generated instructions are
is to disassemble a function that calls getg.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to