source code:
//go:noinline
func testFor() int {
sum := 0
for i := 0; i < 200; i++ {
for j := 0; j < 10000; j++ {
sum += j
}
}
return sum
}
compile command:
GOOS=wasip1 GOARCH=wasm go build -o test.wasm test.go
Got wasm:
(func $main.testFor (type 0) (param i32) (result i32)
(local i32 i64 i64 i64 i64)
global.get 0
local.set 1
loop ;; label = @1
block ;; label = @2
block ;; label = @3
block ;; label = @4
block ;; label = @5
block ;; label = @6
block ;; label = @7
block ;; label = @8
block ;; label = @9
local.get 0
br_table 0 (;@9;) 1 (;@8;) 2 (;@7;) 3 (;@6;) 4 (;@5;) 5 (;@4;) 6 (;@3;) 7 (;@2;)
end
i64.const 0
local.set 2 ;; i = 0
i64.const 0
local.set 3 ;; sum = 0
i32.const 2
local.set 0
br 7 (;@1;)
end
local.get 2
i64.const 1
i64.add ;; i++
local.set 2
end
local.get 2
.......
......
......
Go is compiled into wasm, and the for
is expressed using the br_table
operation. As a result, the compiler backend cannot perform optimization pass related to the for
loop during optimization because the compiler backend cannot identify this as a for
loop.