天天看點

TeaVM編譯JAVA為Wasm的原理

 分兩步:

  • 先把JAVA class翻譯為Wasm C的文本格式。
  • 再對Wasm C進行編譯,産生正式的wasm檔案。

舉例說明。

源碼:

@Export(name = "layoutJs2Java")
    public static int[] layoutJs2Java() {
        int[] intarray = new int[]{5, 8};
        return intarray;
    }      

中間代碼

int32_t layoutJs2Java() {
    int32_t _intarray;
    int32_t localVar1;
    int32_t ___stack__;
    ___stack__ = meth_otbw_WasmRuntime_allocStack(INT32_C(0));
    if (((*((int32_t *) &wasm_heap[INT32_C(468) + 0]) & INT32_C(1)) == INT32_C(0))) {
        *((int32_t *) &wasm_heap[___stack__ + 0]) = INT32_C(12);
        initclass_tw_WasmBenchmarkStarter();
        if ((*((int32_t *) &wasm_heap[___stack__ + 0]) != INT32_C(12))) {
            goto block_0;
        }
    }
    *((int32_t *) &wasm_heap[___stack__ + 0]) = INT32_C(11);
    _intarray = meth_otr_Allocator_allocateArray(INT32_C(15040), INT32_C(2));
    if ((*((int32_t *) &wasm_heap[___stack__ + 0]) == INT32_C(11))) {
        localVar1 = _intarray;
        if ((INT32_C(0) >= *((int32_t *) &wasm_heap[(localVar1 + INT32_C(8)) + 0]))) {
            *((int32_t *) &wasm_heap[___stack__ + 0]) = INT32_C(13);
            teavm_throwArrayIndexOutOfBoundsException();
        } else {
            *((int32_t *) &wasm_heap[((localVar1 + INT32_C(12)) + (INT32_C(0) << INT32_C(2))) + 0]) = INT32_C(5);
            if ((INT32_C(1) < *((int32_t *) &wasm_heap[(localVar1 + INT32_C(8)) + 0]))) {
                *((int32_t *) &wasm_heap[((localVar1 + INT32_C(12)) + (INT32_C(1) << INT32_C(2))) + 0]) = INT32_C(8);
                goto block_1;
            }
            *((int32_t *) &wasm_heap[___stack__ + 0]) = INT32_C(14);
            teavm_throwArrayIndexOutOfBoundsException();
        }
    }
    block_0: ;
    _intarray = INT32_C(0);
    block_1: ;
    *((int32_t *) &wasm_heap[INT32_C(724) + 0]) = (___stack__ - INT32_C(4));
    return _intarray;
}