| 1 |
// Package frontend implements the translation of WebAssembly to SSA IR using the ssa package. |
| 2 |
package frontend |
| 3 |
|
| 4 |
import ( |
| 5 |
"bytes" |
| 6 |
"math" |
| 7 |
"sync" |
| 8 |
|
| 9 |
"github.com/tetratelabs/wazero/internal/engine/wazevo/ssa" |
| 10 |
"github.com/tetratelabs/wazero/internal/engine/wazevo/wazevoapi" |
| 11 |
"github.com/tetratelabs/wazero/internal/wasm" |
| 12 |
) |
| 13 |
|
| 14 |
// Compiler is in charge of lowering Wasm to SSA IR, and does the optimization |
| 15 |
// on top of it in architecture-independent way. |
| 16 |
type Compiler struct { |
| 17 |
// Per-module data that is used across all functions. |
| 18 |
|
| 19 |
m *wasm.Module |
| 20 |
offset *wazevoapi.ModuleContextOffsetData |
| 21 |
// ssaBuilder is a ssa.Builder used by this frontend. |
| 22 |
ssaBuilder ssa.Builder |
| 23 |
signatures map[*wasm.FunctionType]*ssa.Signature |
| 24 |
listenerSignatures map[*wasm.FunctionType][2]*ssa.Signature |
| 25 |
memoryGrowSig ssa.Signature |
| 26 |
memoryWait32Sig ssa.Signature |
| 27 |
memoryWait64Sig ssa.Signature |
| 28 |
memoryNotifySig ssa.Signature |
| 29 |
checkModuleExitCodeSig ssa.Signature |
| 30 |
tableGrowSig ssa.Signature |
| 31 |
refFuncSig ssa.Signature |
| 32 |
memmoveSig ssa.Signature |
| 33 |
ensureTermination bool |
| 34 |
|
| 35 |
// Followings are reset by per function. |
| 36 |
|
| 37 |
// wasmLocalToVariable maps the index (considered as wasm.Index of locals) |
| 38 |
// to the corresponding ssa.Variable. |
| 39 |
wasmLocalToVariable [] /* local index to */ ssa.Variable |
| 40 |
wasmLocalFunctionIndex wasm.Index |
| 41 |
wasmFunctionTypeIndex wasm.Index |
| 42 |
wasmFunctionTyp *wasm.FunctionType |
| 43 |
wasmFunctionLocalTypes []wasm.ValueType |
| 44 |
wasmFunctionBody []byte |
| 45 |
wasmFunctionBodyOffsetInCodeSection uint64 |
| 46 |
memoryBaseVariable, memoryLenVariable ssa.Variable |
| 47 |
needMemory bool |
| 48 |
memoryShared bool |
| 49 |
globalVariables []ssa.Variable |
| 50 |
globalVariablesTypes []ssa.Type |
| 51 |
mutableGlobalVariablesIndexes []wasm.Index // index to ^. |
| 52 |
needListener bool |
| 53 |
needSourceOffsetInfo bool |
| 54 |
// br is reused during lowering. |
| 55 |
br *bytes.Reader |
| 56 |
loweringState loweringState |
| 57 |
|
| 58 |
knownSafeBounds [] /* ssa.ValueID to */ knownSafeBound |
| 59 |
knownSafeBoundsSet []ssa.ValueID |
| 60 |
|
| 61 |
knownSafeBoundsAtTheEndOfBlocks [] /* ssa.BlockID to */ knownSafeBoundsAtTheEndOfBlock |
| 62 |
varLengthKnownSafeBoundWithIDPool wazevoapi.VarLengthPool[knownSafeBoundWithID] |
| 63 |
|
| 64 |
execCtxPtrValue, moduleCtxPtrValue ssa.Value |
| 65 |
|
| 66 |
// throwAllocSig is the signature for the throw-alloc trampoline: |
| 67 |
// (execCtx, tagIndex) → (exnref). Allocates the Exception and returns |
| 68 |
// its pointer so compiled code can pass it to the throw trampoline. |
| 69 |
throwAllocSig ssa.Signature |
| 70 |
// throwSig is the signature for the throw/throw_ref trampoline: |
| 71 |
// (execCtx, exnref) → (). Searches for a matching handler and restores. |
| 72 |
throwSig ssa.Signature |
| 73 |
// tryTableEnterSig is the signature for the try_table enter trampoline. |
| 74 |
tryTableEnterSig ssa.Signature |
| 75 |
// tryTableLeaveSig is the signature for the try_table leave trampoline. |
| 76 |
tryTableLeaveSig ssa.Signature |
| 77 |
// catchClauseTable accumulates catch clause info for each try_table during compilation. |
| 78 |
catchClauseTable catchClauseTable |
| 79 |
|
| 80 |
// Following are reused for the known safe bounds analysis. |
| 81 |
|
| 82 |
pointers []int |
| 83 |
bounds [][]knownSafeBoundWithID |
| 84 |
} |
| 85 |
|
| 86 |
type ( |
| 87 |
// knownSafeBound represents a known safe bound for a value. |
| 88 |
knownSafeBound struct { |
| 89 |
// bound is a constant upper bound for the value. |
| 90 |
bound uint64 |
| 91 |
// absoluteAddr is the absolute address of the value. |
| 92 |
absoluteAddr ssa.Value |
| 93 |
} |
| 94 |
// knownSafeBoundWithID is a knownSafeBound with the ID of the value. |
| 95 |
knownSafeBoundWithID struct { |
| 96 |
knownSafeBound |
| 97 |
id ssa.ValueID |
| 98 |
} |
| 99 |
knownSafeBoundsAtTheEndOfBlock = wazevoapi.VarLength[knownSafeBoundWithID] |
| 100 |
) |
| 101 |
|
| 102 |
var knownSafeBoundsAtTheEndOfBlockNil = wazevoapi.NewNilVarLength[knownSafeBoundWithID]() |
| 103 |
|
| 104 |
// NewFrontendCompiler returns a frontend Compiler. |
| 105 |
func NewFrontendCompiler(m *wasm.Module, ssaBuilder ssa.Builder, offset *wazevoapi.ModuleContextOffsetData, ensureTermination bool, listenerOn bool, sourceInfo bool) *Compiler { |
| 106 |
c := &Compiler{ |
| 107 |
m: m, |
| 108 |
ssaBuilder: ssaBuilder, |
| 109 |
br: bytes.NewReader(nil), |
| 110 |
offset: offset, |
| 111 |
ensureTermination: ensureTermination, |
| 112 |
needSourceOffsetInfo: sourceInfo, |
| 113 |
catchClauseTable: &localCatchClauseTable{}, |
| 114 |
varLengthKnownSafeBoundWithIDPool: wazevoapi.NewVarLengthPool[knownSafeBoundWithID](), |
| 115 |
} |
| 116 |
c.declareSignatures(listenerOn) |
| 117 |
return c |
| 118 |
} |
| 119 |
|
| 120 |
// catchClauseTable accumulates catch clause entries during compilation. |
| 121 |
type catchClauseTable interface { |
| 122 |
Append(clauses []wazevoapi.CatchClauseInstance) int |
| 123 |
Table() [][]wazevoapi.CatchClauseInstance |
| 124 |
} |
| 125 |
|
| 126 |
// localCatchClauseTable is the single-threaded implementation. |
| 127 |
type localCatchClauseTable struct { |
| 128 |
table [][]wazevoapi.CatchClauseInstance |
| 129 |
} |
| 130 |
|
| 131 |
func (t *localCatchClauseTable) Append(clauses []wazevoapi.CatchClauseInstance) int { |
| 132 |
id := len(t.table) |
| 133 |
t.table = append(t.table, clauses) |
| 134 |
return id |
| 135 |
} |
| 136 |
|
| 137 |
func (t *localCatchClauseTable) Table() [][]wazevoapi.CatchClauseInstance { |
| 138 |
return t.table |
| 139 |
} |
| 140 |
|
| 141 |
// SharedCatchClauseTable is the thread-safe implementation for parallel compilation. |
| 142 |
type SharedCatchClauseTable struct { |
| 143 |
mu sync.Mutex |
| 144 |
table [][]wazevoapi.CatchClauseInstance |
| 145 |
finalized bool |
| 146 |
} |
| 147 |
|
| 148 |
// NewSharedCatchClauseTable creates a new SharedCatchClauseTable. |
| 149 |
func NewSharedCatchClauseTable() *SharedCatchClauseTable { |
| 150 |
return &SharedCatchClauseTable{} |
| 151 |
} |
| 152 |
|
| 153 |
func (s *SharedCatchClauseTable) Append(clauses []wazevoapi.CatchClauseInstance) int { |
| 154 |
if s.finalized { |
| 155 |
panic("already finalized") |
| 156 |
} |
| 157 |
s.mu.Lock() |
| 158 |
id := len(s.table) |
| 159 |
s.table = append(s.table, clauses) |
| 160 |
s.mu.Unlock() |
| 161 |
return id |
| 162 |
} |
| 163 |
|
| 164 |
func (s *SharedCatchClauseTable) Table() [][]wazevoapi.CatchClauseInstance { |
| 165 |
s.finalized = true |
| 166 |
return s.table |
| 167 |
} |
| 168 |
|
| 169 |
// WithCatchClauseTable replaces the catch clause table implementation. |
| 170 |
// Used by the parallel compilation path to share a single mutex-protected |
| 171 |
// table across workers. |
| 172 |
func (c *Compiler) WithCatchClauseTable(t catchClauseTable) *Compiler { |
| 173 |
c.catchClauseTable = t |
| 174 |
return c |
| 175 |
} |
| 176 |
|
| 177 |
// CatchClauseTable returns the accumulated catch clause table. |
| 178 |
func (c *Compiler) CatchClauseTable() [][]wazevoapi.CatchClauseInstance { |
| 179 |
return c.catchClauseTable.Table() |
| 180 |
} |
| 181 |
|
| 182 |
func (c *Compiler) declareSignatures(listenerOn bool) { |
| 183 |
m := c.m |
| 184 |
c.signatures = make(map[*wasm.FunctionType]*ssa.Signature, len(m.TypeSection)+2) |
| 185 |
if listenerOn { |
| 186 |
c.listenerSignatures = make(map[*wasm.FunctionType][2]*ssa.Signature, len(m.TypeSection)) |
| 187 |
} |
| 188 |
for i := range m.TypeSection { |
| 189 |
wasmSig := &m.TypeSection[i] |
| 190 |
sig := SignatureForWasmFunctionType(wasmSig) |
| 191 |
sig.ID = ssa.SignatureID(i) |
| 192 |
c.signatures[wasmSig] = &sig |
| 193 |
c.ssaBuilder.DeclareSignature(&sig) |
| 194 |
|
| 195 |
if listenerOn { |
| 196 |
beforeSig, afterSig := SignatureForListener(wasmSig) |
| 197 |
beforeSig.ID = ssa.SignatureID(i) + ssa.SignatureID(len(m.TypeSection)) |
| 198 |
afterSig.ID = ssa.SignatureID(i) + ssa.SignatureID(len(m.TypeSection))*2 |
| 199 |
c.listenerSignatures[wasmSig] = [2]*ssa.Signature{beforeSig, afterSig} |
| 200 |
c.ssaBuilder.DeclareSignature(beforeSig) |
| 201 |
c.ssaBuilder.DeclareSignature(afterSig) |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
begin := ssa.SignatureID(len(m.TypeSection)) |
| 206 |
if listenerOn { |
| 207 |
begin *= 3 |
| 208 |
} |
| 209 |
c.memoryGrowSig = ssa.Signature{ |
| 210 |
ID: begin, |
| 211 |
// Takes execution context and the page size to grow. |
| 212 |
Params: []ssa.Type{ssa.TypeI64, ssa.TypeI32}, |
| 213 |
// Returns the previous page size. |
| 214 |
Results: []ssa.Type{ssa.TypeI32}, |
| 215 |
} |
| 216 |
c.ssaBuilder.DeclareSignature(&c.memoryGrowSig) |
| 217 |
|
| 218 |
c.checkModuleExitCodeSig = ssa.Signature{ |
| 219 |
ID: c.memoryGrowSig.ID + 1, |
| 220 |
// Only takes execution context. |
| 221 |
Params: []ssa.Type{ssa.TypeI64}, |
| 222 |
} |
| 223 |
c.ssaBuilder.DeclareSignature(&c.checkModuleExitCodeSig) |
| 224 |
|
| 225 |
c.tableGrowSig = ssa.Signature{ |
| 226 |
ID: c.checkModuleExitCodeSig.ID + 1, |
| 227 |
Params: []ssa.Type{ssa.TypeI64 /* exec context */, ssa.TypeI32 /* table index */, ssa.TypeI32 /* num */, ssa.TypeI64 /* ref */}, |
| 228 |
// Returns the previous size. |
| 229 |
Results: []ssa.Type{ssa.TypeI32}, |
| 230 |
} |
| 231 |
c.ssaBuilder.DeclareSignature(&c.tableGrowSig) |
| 232 |
|
| 233 |
c.refFuncSig = ssa.Signature{ |
| 234 |
ID: c.tableGrowSig.ID + 1, |
| 235 |
Params: []ssa.Type{ssa.TypeI64 /* exec context */, ssa.TypeI32 /* func index */}, |
| 236 |
// Returns the function reference. |
| 237 |
Results: []ssa.Type{ssa.TypeI64}, |
| 238 |
} |
| 239 |
c.ssaBuilder.DeclareSignature(&c.refFuncSig) |
| 240 |
|
| 241 |
c.memmoveSig = ssa.Signature{ |
| 242 |
ID: c.refFuncSig.ID + 1, |
| 243 |
// dst, src, and the byte count. |
| 244 |
Params: []ssa.Type{ssa.TypeI64, ssa.TypeI64, ssa.TypeI64}, |
| 245 |
} |
| 246 |
|
| 247 |
c.ssaBuilder.DeclareSignature(&c.memmoveSig) |
| 248 |
|
| 249 |
c.memoryWait32Sig = ssa.Signature{ |
| 250 |
ID: c.memmoveSig.ID + 1, |
| 251 |
// exec context, timeout, expected, addr |
| 252 |
Params: []ssa.Type{ssa.TypeI64, ssa.TypeI64, ssa.TypeI32, ssa.TypeI64}, |
| 253 |
// Returns the status. |
| 254 |
Results: []ssa.Type{ssa.TypeI32}, |
| 255 |
} |
| 256 |
c.ssaBuilder.DeclareSignature(&c.memoryWait32Sig) |
| 257 |
|
| 258 |
c.memoryWait64Sig = ssa.Signature{ |
| 259 |
ID: c.memoryWait32Sig.ID + 1, |
| 260 |
// exec context, timeout, expected, addr |
| 261 |
Params: []ssa.Type{ssa.TypeI64, ssa.TypeI64, ssa.TypeI64, ssa.TypeI64}, |
| 262 |
// Returns the status. |
| 263 |
Results: []ssa.Type{ssa.TypeI32}, |
| 264 |
} |
| 265 |
c.ssaBuilder.DeclareSignature(&c.memoryWait64Sig) |
| 266 |
|
| 267 |
c.memoryNotifySig = ssa.Signature{ |
| 268 |
ID: c.memoryWait64Sig.ID + 1, |
| 269 |
// exec context, count, addr |
| 270 |
Params: []ssa.Type{ssa.TypeI64, ssa.TypeI32, ssa.TypeI64}, |
| 271 |
// Returns the number notified. |
| 272 |
Results: []ssa.Type{ssa.TypeI32}, |
| 273 |
} |
| 274 |
c.ssaBuilder.DeclareSignature(&c.memoryNotifySig) |
| 275 |
|
| 276 |
c.throwAllocSig = ssa.Signature{ |
| 277 |
ID: c.memoryNotifySig.ID + 1, |
| 278 |
Params: []ssa.Type{ssa.TypeI64 /* exec context */, ssa.TypeI64 /* tag index */}, |
| 279 |
Results: []ssa.Type{ssa.TypeI64 /* exnref */}, |
| 280 |
} |
| 281 |
c.ssaBuilder.DeclareSignature(&c.throwAllocSig) |
| 282 |
|
| 283 |
c.throwSig = ssa.Signature{ |
| 284 |
ID: c.throwAllocSig.ID + 1, |
| 285 |
Params: []ssa.Type{ssa.TypeI64 /* exec context */, ssa.TypeI64 /* exnref */}, |
| 286 |
Results: []ssa.Type{}, |
| 287 |
} |
| 288 |
c.ssaBuilder.DeclareSignature(&c.throwSig) |
| 289 |
|
| 290 |
c.tryTableEnterSig = ssa.Signature{ |
| 291 |
ID: c.throwSig.ID + 1, |
| 292 |
Params: []ssa.Type{ssa.TypeI64 /* exec context */, ssa.TypeI64 /* encoded exit code */}, |
| 293 |
Results: []ssa.Type{}, |
| 294 |
} |
| 295 |
c.ssaBuilder.DeclareSignature(&c.tryTableEnterSig) |
| 296 |
|
| 297 |
c.tryTableLeaveSig = ssa.Signature{ |
| 298 |
ID: c.tryTableEnterSig.ID + 1, |
| 299 |
Params: []ssa.Type{ssa.TypeI64 /* exec context */}, |
| 300 |
Results: []ssa.Type{}, |
| 301 |
} |
| 302 |
c.ssaBuilder.DeclareSignature(&c.tryTableLeaveSig) |
| 303 |
} |
| 304 |
|
| 305 |
// SignatureForWasmFunctionType returns the ssa.Signature for the given wasm.FunctionType. |
| 306 |
func SignatureForWasmFunctionType(typ *wasm.FunctionType) ssa.Signature { |
| 307 |
sig := ssa.Signature{ |
| 308 |
// +2 to pass moduleContextPtr and executionContextPtr. See the inline comment LowerToSSA. |
| 309 |
Params: make([]ssa.Type, len(typ.Params)+2), |
| 310 |
Results: make([]ssa.Type, len(typ.Results)), |
| 311 |
} |
| 312 |
sig.Params[0] = executionContextPtrTyp |
| 313 |
sig.Params[1] = moduleContextPtrTyp |
| 314 |
for j, typ := range typ.Params { |
| 315 |
sig.Params[j+2] = WasmTypeToSSAType(typ) |
| 316 |
} |
| 317 |
for j, typ := range typ.Results { |
| 318 |
sig.Results[j] = WasmTypeToSSAType(typ) |
| 319 |
} |
| 320 |
return sig |
| 321 |
} |
| 322 |
|
| 323 |
// Init initializes the state of frontendCompiler and make it ready for a next function. |
| 324 |
func (c *Compiler) Init(idx, typIndex wasm.Index, typ *wasm.FunctionType, localTypes []wasm.ValueType, body []byte, needListener bool, bodyOffsetInCodeSection uint64) { |
| 325 |
c.ssaBuilder.Init(c.signatures[typ]) |
| 326 |
c.loweringState.reset() |
| 327 |
|
| 328 |
c.wasmFunctionTypeIndex = typIndex |
| 329 |
c.wasmLocalFunctionIndex = idx |
| 330 |
c.wasmFunctionTyp = typ |
| 331 |
c.wasmFunctionLocalTypes = localTypes |
| 332 |
c.wasmFunctionBody = body |
| 333 |
c.wasmFunctionBodyOffsetInCodeSection = bodyOffsetInCodeSection |
| 334 |
c.needListener = needListener |
| 335 |
c.clearSafeBounds() |
| 336 |
c.varLengthKnownSafeBoundWithIDPool.Reset() |
| 337 |
c.knownSafeBoundsAtTheEndOfBlocks = c.knownSafeBoundsAtTheEndOfBlocks[:0] |
| 338 |
} |
| 339 |
|
| 340 |
// Note: this assumes 64-bit platform (I believe we won't have 32-bit backend ;)). |
| 341 |
const executionContextPtrTyp, moduleContextPtrTyp = ssa.TypeI64, ssa.TypeI64 |
| 342 |
|
| 343 |
// LowerToSSA lowers the current function to SSA IR which will be held by ssaBuilder. |
| 344 |
// |
| 345 |
// After calling this, the caller will be able to access the SSA info in *Compiler.ssaBuilder. |
| 346 |
// |
| 347 |
// Note that this only does the naive lowering, and do not do any optimization, instead the caller is expected to do so. |
| 348 |
func (c *Compiler) LowerToSSA() { |
| 349 |
builder := c.ssaBuilder |
| 350 |
|
| 351 |
// Set up the entry block. |
| 352 |
entryBlock := builder.AllocateBasicBlock() |
| 353 |
builder.SetCurrentBlock(entryBlock) |
| 354 |
|
| 355 |
// Functions always take two parameters in addition to Wasm-level parameters: |
| 356 |
// |
| 357 |
// 1. executionContextPtr: pointer to the *executionContext in wazevo package. |
| 358 |
// This will be used to exit the execution in the face of trap, plus used for host function calls. |
| 359 |
// |
| 360 |
// 2. moduleContextPtr: pointer to the *moduleContextOpaque in wazevo package. |
| 361 |
// This will be used to access memory, etc. Also, this will be used during host function calls. |
| 362 |
// |
| 363 |
// Note: it's clear that sometimes a function won't need them. For example, |
| 364 |
// if the function doesn't trap and doesn't make function call, then |
| 365 |
// we might be able to eliminate the parameter. However, if that function |
| 366 |
// can be called via call_indirect, then we cannot eliminate because the |
| 367 |
// signature won't match with the expected one. |
| 368 |
// TODO: maybe there's some way to do this optimization without glitches, but so far I have no clue about the feasibility. |
| 369 |
// |
| 370 |
// Note: In Wasmtime or many other runtimes, moduleContextPtr is called "vmContext". Also note that `moduleContextPtr` |
| 371 |
// is wazero-specific since other runtimes can naturally use the OS-level signal to do this job thanks to the fact that |
| 372 |
// they can use native stack vs wazero cannot use Go-routine stack and have to use Go-runtime allocated []byte as a stack. |
| 373 |
c.execCtxPtrValue = entryBlock.AddParam(builder, executionContextPtrTyp) |
| 374 |
c.moduleCtxPtrValue = entryBlock.AddParam(builder, moduleContextPtrTyp) |
| 375 |
builder.AnnotateValue(c.execCtxPtrValue, "exec_ctx") |
| 376 |
builder.AnnotateValue(c.moduleCtxPtrValue, "module_ctx") |
| 377 |
|
| 378 |
for i, typ := range c.wasmFunctionTyp.Params { |
| 379 |
st := WasmTypeToSSAType(typ) |
| 380 |
variable := builder.DeclareVariable(st) |
| 381 |
value := entryBlock.AddParam(builder, st) |
| 382 |
builder.DefineVariable(variable, value, entryBlock) |
| 383 |
c.setWasmLocalVariable(wasm.Index(i), variable) |
| 384 |
} |
| 385 |
c.declareWasmLocals() |
| 386 |
c.declareNecessaryVariables() |
| 387 |
|
| 388 |
c.lowerBody(entryBlock) |
| 389 |
} |
| 390 |
|
| 391 |
// localVariable returns the SSA variable for the given Wasm local index. |
| 392 |
func (c *Compiler) localVariable(index wasm.Index) ssa.Variable { |
| 393 |
return c.wasmLocalToVariable[index] |
| 394 |
} |
| 395 |
|
| 396 |
func (c *Compiler) setWasmLocalVariable(index wasm.Index, variable ssa.Variable) { |
| 397 |
idx := int(index) |
| 398 |
if idx >= len(c.wasmLocalToVariable) { |
| 399 |
c.wasmLocalToVariable = append(c.wasmLocalToVariable, make([]ssa.Variable, idx+1-len(c.wasmLocalToVariable))...) |
| 400 |
} |
| 401 |
c.wasmLocalToVariable[idx] = variable |
| 402 |
} |
| 403 |
|
| 404 |
// declareWasmLocals declares the SSA variables for the Wasm locals. |
| 405 |
func (c *Compiler) declareWasmLocals() { |
| 406 |
localCount := wasm.Index(len(c.wasmFunctionTyp.Params)) |
| 407 |
for i, typ := range c.wasmFunctionLocalTypes { |
| 408 |
st := WasmTypeToSSAType(typ) |
| 409 |
variable := c.ssaBuilder.DeclareVariable(st) |
| 410 |
c.setWasmLocalVariable(wasm.Index(i)+localCount, variable) |
| 411 |
c.ssaBuilder.InsertZeroValue(st) |
| 412 |
} |
| 413 |
} |
| 414 |
|
| 415 |
func (c *Compiler) declareNecessaryVariables() { |
| 416 |
if c.needMemory = c.m.MemorySection != nil; c.needMemory { |
| 417 |
c.memoryShared = c.m.MemorySection.IsShared |
| 418 |
} else if c.needMemory = c.m.ImportMemoryCount > 0; c.needMemory { |
| 419 |
for _, imp := range c.m.ImportSection { |
| 420 |
if imp.Type == wasm.ExternTypeMemory { |
| 421 |
c.memoryShared = imp.DescMem.IsShared |
| 422 |
break |
| 423 |
} |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
if c.needMemory { |
| 428 |
c.memoryBaseVariable = c.ssaBuilder.DeclareVariable(ssa.TypeI64) |
| 429 |
c.memoryLenVariable = c.ssaBuilder.DeclareVariable(ssa.TypeI64) |
| 430 |
} |
| 431 |
|
| 432 |
c.globalVariables = c.globalVariables[:0] |
| 433 |
c.mutableGlobalVariablesIndexes = c.mutableGlobalVariablesIndexes[:0] |
| 434 |
c.globalVariablesTypes = c.globalVariablesTypes[:0] |
| 435 |
for _, imp := range c.m.ImportSection { |
| 436 |
if imp.Type == wasm.ExternTypeGlobal { |
| 437 |
desc := imp.DescGlobal |
| 438 |
c.declareWasmGlobal(desc.ValType, desc.Mutable) |
| 439 |
} |
| 440 |
} |
| 441 |
for _, g := range c.m.GlobalSection { |
| 442 |
desc := g.Type |
| 443 |
c.declareWasmGlobal(desc.ValType, desc.Mutable) |
| 444 |
} |
| 445 |
|
| 446 |
// TODO: add tables. |
| 447 |
} |
| 448 |
|
| 449 |
func (c *Compiler) declareWasmGlobal(typ wasm.ValueType, mutable bool) { |
| 450 |
st := WasmTypeToSSAType(typ) |
| 451 |
v := c.ssaBuilder.DeclareVariable(st) |
| 452 |
index := wasm.Index(len(c.globalVariables)) |
| 453 |
c.globalVariables = append(c.globalVariables, v) |
| 454 |
c.globalVariablesTypes = append(c.globalVariablesTypes, st) |
| 455 |
if mutable { |
| 456 |
c.mutableGlobalVariablesIndexes = append(c.mutableGlobalVariablesIndexes, index) |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
// WasmTypeToSSAType converts wasm.ValueType to ssa.Type. |
| 461 |
func WasmTypeToSSAType(vt wasm.ValueType) ssa.Type { |
| 462 |
switch vt { |
| 463 |
case wasm.ValueTypeI32: |
| 464 |
return ssa.TypeI32 |
| 465 |
case wasm.ValueTypeI64, |
| 466 |
// externref, funcref, and exnref are represented as I64 since we only support 64-bit platforms. |
| 467 |
wasm.ValueTypeExternref, wasm.ValueTypeFuncref, |
| 468 |
wasm.ValueTypeExnref: |
| 469 |
return ssa.TypeI64 |
| 470 |
case wasm.ValueTypeF32: |
| 471 |
return ssa.TypeF32 |
| 472 |
case wasm.ValueTypeF64: |
| 473 |
return ssa.TypeF64 |
| 474 |
case wasm.ValueTypeV128: |
| 475 |
return ssa.TypeV128 |
| 476 |
default: |
| 477 |
// Concrete ref types (ref $t) have variable bit patterns. |
| 478 |
if vt.IsRef() { |
| 479 |
return ssa.TypeI64 |
| 480 |
} |
| 481 |
panic("TODO: " + wasm.ValueTypeName(vt)) |
| 482 |
} |
| 483 |
} |
| 484 |
|
| 485 |
// addBlockParamsFromWasmTypes adds the block parameters to the given block. |
| 486 |
func (c *Compiler) addBlockParamsFromWasmTypes(tps []wasm.ValueType, blk ssa.BasicBlock) { |
| 487 |
for _, typ := range tps { |
| 488 |
st := WasmTypeToSSAType(typ) |
| 489 |
blk.AddParam(c.ssaBuilder, st) |
| 490 |
} |
| 491 |
} |
| 492 |
|
| 493 |
// formatBuilder outputs the constructed SSA function as a string with a source information. |
| 494 |
func (c *Compiler) formatBuilder() string { |
| 495 |
return c.ssaBuilder.Format() |
| 496 |
} |
| 497 |
|
| 498 |
// SignatureForListener returns the signatures for the listener functions. |
| 499 |
func SignatureForListener(wasmSig *wasm.FunctionType) (*ssa.Signature, *ssa.Signature) { |
| 500 |
beforeSig := &ssa.Signature{} |
| 501 |
beforeSig.Params = make([]ssa.Type, len(wasmSig.Params)+2) |
| 502 |
beforeSig.Params[0] = ssa.TypeI64 // Execution context. |
| 503 |
beforeSig.Params[1] = ssa.TypeI32 // Function index. |
| 504 |
for i, p := range wasmSig.Params { |
| 505 |
beforeSig.Params[i+2] = WasmTypeToSSAType(p) |
| 506 |
} |
| 507 |
afterSig := &ssa.Signature{} |
| 508 |
afterSig.Params = make([]ssa.Type, len(wasmSig.Results)+2) |
| 509 |
afterSig.Params[0] = ssa.TypeI64 // Execution context. |
| 510 |
afterSig.Params[1] = ssa.TypeI32 // Function index. |
| 511 |
for i, p := range wasmSig.Results { |
| 512 |
afterSig.Params[i+2] = WasmTypeToSSAType(p) |
| 513 |
} |
| 514 |
return beforeSig, afterSig |
| 515 |
} |
| 516 |
|
| 517 |
// isBoundSafe returns true if the given value is known to be safe to access up to the given bound. |
| 518 |
func (c *Compiler) getKnownSafeBound(v ssa.ValueID) *knownSafeBound { |
| 519 |
if int(v) >= len(c.knownSafeBounds) { |
| 520 |
return nil |
| 521 |
} |
| 522 |
return &c.knownSafeBounds[v] |
| 523 |
} |
| 524 |
|
| 525 |
// recordKnownSafeBound records the given safe bound for the given value. |
| 526 |
func (c *Compiler) recordKnownSafeBound(v ssa.ValueID, safeBound uint64, absoluteAddr ssa.Value) { |
| 527 |
if int(v) >= len(c.knownSafeBounds) { |
| 528 |
c.knownSafeBounds = append(c.knownSafeBounds, make([]knownSafeBound, v+1)...) |
| 529 |
} |
| 530 |
|
| 531 |
if exiting := c.knownSafeBounds[v]; exiting.bound == 0 { |
| 532 |
c.knownSafeBounds[v] = knownSafeBound{ |
| 533 |
bound: safeBound, |
| 534 |
absoluteAddr: absoluteAddr, |
| 535 |
} |
| 536 |
c.knownSafeBoundsSet = append(c.knownSafeBoundsSet, v) |
| 537 |
} else if safeBound > exiting.bound { |
| 538 |
c.knownSafeBounds[v].bound = safeBound |
| 539 |
} |
| 540 |
} |
| 541 |
|
| 542 |
// clearSafeBounds clears the known safe bounds. |
| 543 |
func (c *Compiler) clearSafeBounds() { |
| 544 |
for _, v := range c.knownSafeBoundsSet { |
| 545 |
ptr := &c.knownSafeBounds[v] |
| 546 |
ptr.bound = 0 |
| 547 |
ptr.absoluteAddr = ssa.ValueInvalid |
| 548 |
} |
| 549 |
c.knownSafeBoundsSet = c.knownSafeBoundsSet[:0] |
| 550 |
} |
| 551 |
|
| 552 |
// resetAbsoluteAddressInSafeBounds resets the absolute addresses recorded in the known safe bounds. |
| 553 |
func (c *Compiler) resetAbsoluteAddressInSafeBounds() { |
| 554 |
for _, v := range c.knownSafeBoundsSet { |
| 555 |
ptr := &c.knownSafeBounds[v] |
| 556 |
ptr.absoluteAddr = ssa.ValueInvalid |
| 557 |
} |
| 558 |
} |
| 559 |
|
| 560 |
func (k *knownSafeBound) valid() bool { |
| 561 |
return k != nil && k.bound > 0 |
| 562 |
} |
| 563 |
|
| 564 |
func (c *Compiler) allocateVarLengthValues(_cap int, vs ...ssa.Value) ssa.Values { |
| 565 |
builder := c.ssaBuilder |
| 566 |
pool := builder.VarLengthPool() |
| 567 |
args := pool.Allocate(_cap) |
| 568 |
args = args.Append(pool, vs...) |
| 569 |
return args |
| 570 |
} |
| 571 |
|
| 572 |
func (c *Compiler) finalizeKnownSafeBoundsAtTheEndOfBlock(bID ssa.BasicBlockID) { |
| 573 |
_bID := int(bID) |
| 574 |
if l := len(c.knownSafeBoundsAtTheEndOfBlocks); _bID >= l { |
| 575 |
c.knownSafeBoundsAtTheEndOfBlocks = append(c.knownSafeBoundsAtTheEndOfBlocks, |
| 576 |
make([]knownSafeBoundsAtTheEndOfBlock, _bID+1-len(c.knownSafeBoundsAtTheEndOfBlocks))...) |
| 577 |
for i := l; i < len(c.knownSafeBoundsAtTheEndOfBlocks); i++ { |
| 578 |
c.knownSafeBoundsAtTheEndOfBlocks[i] = knownSafeBoundsAtTheEndOfBlockNil |
| 579 |
} |
| 580 |
} |
| 581 |
p := &c.varLengthKnownSafeBoundWithIDPool |
| 582 |
size := len(c.knownSafeBoundsSet) |
| 583 |
allocated := c.varLengthKnownSafeBoundWithIDPool.Allocate(size) |
| 584 |
// Sort the known safe bounds by the value ID so that we can use the intersection algorithm in initializeCurrentBlockKnownBounds. |
| 585 |
sortSSAValueIDs(c.knownSafeBoundsSet) |
| 586 |
for _, vID := range c.knownSafeBoundsSet { |
| 587 |
kb := c.knownSafeBounds[vID] |
| 588 |
allocated = allocated.Append(p, knownSafeBoundWithID{ |
| 589 |
knownSafeBound: kb, |
| 590 |
id: vID, |
| 591 |
}) |
| 592 |
} |
| 593 |
c.knownSafeBoundsAtTheEndOfBlocks[bID] = allocated |
| 594 |
c.clearSafeBounds() |
| 595 |
} |
| 596 |
|
| 597 |
func (c *Compiler) initializeCurrentBlockKnownBounds() { |
| 598 |
currentBlk := c.ssaBuilder.CurrentBlock() |
| 599 |
switch preds := currentBlk.Preds(); preds { |
| 600 |
case 0: |
| 601 |
case 1: |
| 602 |
pred := currentBlk.Pred(0).ID() |
| 603 |
for _, kb := range c.getKnownSafeBoundsAtTheEndOfBlocks(pred).View() { |
| 604 |
// Unless the block is sealed, we cannot assume the absolute address is valid: |
| 605 |
// later we might add another predecessor that has no visibility of that value. |
| 606 |
addr := ssa.ValueInvalid |
| 607 |
if currentBlk.Sealed() { |
| 608 |
addr = kb.absoluteAddr |
| 609 |
} |
| 610 |
c.recordKnownSafeBound(kb.id, kb.bound, addr) |
| 611 |
} |
| 612 |
default: |
| 613 |
c.pointers = c.pointers[:0] |
| 614 |
c.bounds = c.bounds[:0] |
| 615 |
for i := 0; i < preds; i++ { |
| 616 |
c.bounds = append(c.bounds, c.getKnownSafeBoundsAtTheEndOfBlocks(currentBlk.Pred(i).ID()).View()) |
| 617 |
c.pointers = append(c.pointers, 0) |
| 618 |
} |
| 619 |
|
| 620 |
// If there are multiple predecessors, we need to find the intersection of the known safe bounds. |
| 621 |
|
| 622 |
outer: |
| 623 |
for { |
| 624 |
smallestID := ssa.ValueID(math.MaxUint32) |
| 625 |
for i, ptr := range c.pointers { |
| 626 |
if ptr >= len(c.bounds[i]) { |
| 627 |
break outer |
| 628 |
} |
| 629 |
cb := &c.bounds[i][ptr] |
| 630 |
if id := cb.id; id < smallestID { |
| 631 |
smallestID = cb.id |
| 632 |
} |
| 633 |
} |
| 634 |
|
| 635 |
// Check if current elements are the same across all lists. |
| 636 |
same := true |
| 637 |
minBound := uint64(math.MaxUint64) |
| 638 |
for i := 0; i < preds; i++ { |
| 639 |
cb := &c.bounds[i][c.pointers[i]] |
| 640 |
if cb.id != smallestID { |
| 641 |
same = false |
| 642 |
} else { |
| 643 |
if cb.bound < minBound { |
| 644 |
minBound = cb.bound |
| 645 |
} |
| 646 |
c.pointers[i]++ |
| 647 |
} |
| 648 |
} |
| 649 |
|
| 650 |
if same { // All elements are the same. |
| 651 |
// Absolute address cannot be used in the intersection since the value might be only defined in one of the predecessors. |
| 652 |
c.recordKnownSafeBound(smallestID, minBound, ssa.ValueInvalid) |
| 653 |
} |
| 654 |
} |
| 655 |
} |
| 656 |
} |
| 657 |
|
| 658 |
func (c *Compiler) getKnownSafeBoundsAtTheEndOfBlocks(id ssa.BasicBlockID) knownSafeBoundsAtTheEndOfBlock { |
| 659 |
if int(id) >= len(c.knownSafeBoundsAtTheEndOfBlocks) { |
| 660 |
return knownSafeBoundsAtTheEndOfBlockNil |
| 661 |
} |
| 662 |
return c.knownSafeBoundsAtTheEndOfBlocks[id] |
| 663 |
} |