這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
Go in Go
隨著 Go 1.5 版本的開發,現在整個系統都是使用 Go 編寫的(有一小部分彙編)
C 已經成為過去時了。
註: gccgo 仍然很強大
這篇文章主要探討原始編譯器 gcc
為什麼之前用 C 編寫?
啟動
(而且 Go 的主要目的不是作為一個編譯器實現語言)
為什麼編譯器使用 Go 重寫?
不單單是驗證,我們還有更多實際的原因:
雖然看起來很多優勢,但是還是誇的太早了:)
設計文檔: golang.org/s/go13compiler
為什麼運行時也是用 Go 重寫?
我們有自己的 C 編譯器來編譯運行時
我們需要一個帶有跟 Go ABI 一樣編譯器,比如 segmented stacks。
使用 Go 編寫可以擺脫 C 編譯器的劣勢。
這是比使用 Go 重寫編譯器還重要。
(所有使用 Go 重寫編譯器的理由都可以作為使用 Go 重寫運行時的理由)
限制運行時只用一種語言編寫,更容易進行整合,管理 stack 等等操作。
跟往常一樣,簡化是首要的考慮因素。
曆史
為什麼我們要有完全屬於自己的工具鏈?
我們的 ABI?
我們自身的檔案格式?
History, familiarity, and ease of moving forward. And speed.
Go 的大部分重大改進要比 GCC 或者 LLVM 要更困難。
news.ycombinator.com/item?id=8817990
重大改進
由於使用自身工具簡化的功能和使用 Go 重寫後的一些改進:
-
linker 重構
-
新垃圾收集器
-
堆疊圖
-
連續棧
-
寫屏障
最後三個都不可能用 C 實現:
(Gccgo 很快會有 segmented stacks 和 imprecise (stack) collection )
Goroutine 棧
-
Until 1.2: Stacks were segmented.
-
1.3: Stacks were contiguous unless executing C code (runtime).
-
1.4: Stacks made contiguous by restricting C to system stack.
-
1.5: Stacks made contiguous by eliminating C.
These were each huge steps, made quickly (led by khr@).
Converting the runtime
Mostly done by hand with machine assistance.
Challenge to implement the runtime in a safe language.
Some use of unsafe to deal with pointers as raw bits in the GC, for instance.
But less than you might think.
The translator (next sections) helped for some of the translation.
Converting the compiler
Why translate it, not write it from scratch? Correctness, testing.
Steps:
-
Write a custom translator from C to Go.
-
Run the translator, iterate until success.
-
Measure success by bit-identical output.
-
Clean up the code by hand and by machine.
-
Turn it from C-in-Go to idiomatic Go (still happening).
Translator
First output was C line-by-line translated to (bad!) Go.
Tool to do this written by rsc@ (talked about at GopherCon 2014).
Custom written for this job, not a general C-to-Go translator.
Steps:
-
Parse C code using new simple C parser (yacc)
-
Remove or rewrite C-isms such as *p++ as an expression
-
Walk the C parse tree, print the C code in Go syntax
-
Compile the output
-
Run, compare generated code
-
Repeat
The Yacc grammar was translated by sam-powered hands.
Translator configuration
Aided by hand-written rewrite rules, such as:
Also diff-like rewrites for things such as using the standard library:
diff {- g.Rpo = obj.Calloc(g.Num*sizeof(g.Rpo[0]), 1).([]*Flow)- idom = obj.Calloc(g.Num*sizeof(idom[0]), 1).([]int32)- if g.Rpo == nil || idom == nil {- Fatal("out of memory")- }+ g.Rpo = make([]*Flow, g.Num)+ idom = make([]int32, g.Num)}
Another example
This one due to semantic difference between the languages.
diff {- if nreg == 64 {- mask = ^0 // can't rely on C to shift by 64- } else {- mask = (1 << uint(nreg)) - 1- }+ mask = (1 << uint(nreg)) - 1}
Grind
Once in Go, new tool grind deployed (by rsc@):
-
parses Go, type checks
-
records a list of edits to perform: "insert this text at this position"
-
at end, applies edits to source (hard to edit AST).
Changes guided by profiling and other analysis:
-
removes dead code
-
removes gotos
-
removes unused labels, needless indirections, etc.
-
moves var declarations nearer to first use
rsc.io/grind
Performance problems
Output from translator was poor Go, and ran about 10X slower.
Most of that slowdown has been recovered.
Problems with C to Go:
-
C patterns can be poor Go; e.g.: complex for loops
-
C stack variables never escape; Go compiler isn't as sure
-
interfaces such as fmt.Stringer vs. C's varargs
-
no unions in Go, so use structs instead: bloat
-
variable declarations in wrong place
C compiler didn't free much memory, but Go has a GC.
Adds CPU and memory overhead.
Performance fixes
Profile! (Never done before!)
-
move vars closer to first use
-
split vars into multiple
-
replace code in the compiler with code in the library: e.g. math/big
-
use interface or other tricks to combine struct fields
-
better escape analysis (drchase@).
-
hand tuning code and data layout
Use tools like grind, gofmt -r and eg for much of this.
Removing interface argument from a debugging print library got 15% overall!
More remains to be done.
Technical benefits
Other benefits of the conversion:
Garbage collection means no more worry about introducing a dangling pointer.
Chance to clean up the back ends.
Unified 386 and amd64 architectures throughout the tool chain.
New architectures are easier to add.
Unified the tools: now one compiler, one assembler, one linker.
Compiler
GOOS=YYY GOARCH=XXX go tool compile
One compiler; no more 6g, 8g etc.
About 50K lines of portable code.
Even the registerizer is portable now; architectures well characterized.
Non-portable: Peepholing, details like registers bound to instructions.
Typically around 10% of the portable LOC.
Assembler
GOOS=YYY GOARCH=XXX go tool asm
New assembler, all in Go, written from scratch by r@.
Clean, idiomatic Go code.
Less than 4000 lines, <10% machine-dependent.
Almost completely compatible with previous yacc and C assemblers.
How is this possible?
-
shared syntax originating in the Plan 9 assemblers
-
unified back-end logic (old liblink, now internal/obj)
Linker
GOOS=YYY GOARCH=XXX go tool link
Mostly hand- and machine- translated from C code.
New library, internal/obj, part of original linker, captures details about machines, writes object files.
27000 lines summed across 4 architectures, mostly tables (plus some ugliness).
Example benefit: one print routine to print any instruction for any architecture.
啟動
不需要 C 編譯器,只需要一個 Go 編譯器
因此需要從 1.5 的原始碼去下載安裝構建 Go
我們使用 Go 1.4+ 作為基礎庫來構建 1.5+ 的工具鏈
詳情: golang.org/s/go15bootstrap
未來
未來仍然有很多任務要完成,但是 1.5 已經完成的差不多了。
未來的計劃:
更好的轉義分析
新編譯器後端使用 SSA(使用 Go 會比 C 簡單很多)。
更多最佳化
從 PDFs (或者是 XML)產生機器描述
將會有一個純機器產生指令定義
“從 PDF 讀入,寫出一個彙編配置”
已經部署反組譯工具
總結
擺脫 C 是 Go 項目的一個巨大改進,代碼更整潔,提升可測試性,可部署性,也更容易運行。
新的統一工具鏈減少了代碼數量,提升可維護性。
靈活的工具鏈對可移植性也很重要。
Thank you
Rob Pike
Google
r@golang.org
http://golang.org/
via talks.golang.org