Skip to content

CSE does not handle side effect of [array.copy] correctly #6690

@Guest0x0

Description

@Guest0x0
> wasm-opt --version
wasm-opt version 117 (version_117)

The input code is:

(import "module" "fn" (func $use_array (param (ref $array_i32))))
(data $data
 "\01\00\00\00\02\00\00\00\03\00\00\00\04\00\00\00\05\00\00\00 ")
(type $array_i32 (array (mut i32)))
(memory $memory 1)
(func $*init*
 (local $x (ref $array_i32))

 (array.copy $array_i32 $array_i32
  (local.tee $x
   (array.new_data $array_i32 $data (i32.const 0) (i32.const 5)))
  (i32.const 1)
  (local.get $x)
  (i32.const 0)
  (i32.const 4)
 )
 (call $use_array (local.get $x))

 (call $use_array
  (array.new_data $array_i32 $data (i32.const 0) (i32.const 5)))
)
(export "_start" (func $*init*))

The code creates a wasm-gc array with array.new_data, and performs a self copy on that array. Then it allocates another array with the same initial value via array.new_data. The import $use_array is used for preventing DCE.

After optimizing the above file with the following command line:

wasm-opt \
  --enable-gc --enable-bulk-memory --enable-reference-types\
  -O array_copy.wat -o array_copy.opt.wat\
  -S --new-wat-parser

the generated code is:

(module
 (type $array_i32 (array (mut i32)))
 (type $1 (func (param (ref $array_i32))))
 (type $2 (func))
 (import "module" "fn" (func $use_array (type $1) (param (ref $array_i32))))
 (data $data "\01\00\00\00\02\00\00\00\03\00\00\00\04\00\00\00\05\00\00\00 ")
 (export "_start" (func $*init*))
 (func $*init* (type $2) (; has Stack IR ;)
  (local $0 (ref $array_i32))
  (array.copy $array_i32 $array_i32
   (local.tee $0
    (array.new_data $array_i32 $data
     (i32.const 0)
     (i32.const 5)
    )
   )
   (i32.const 1)
   (local.get $0)
   (i32.const 0)
   (i32.const 4)
  )
  (call $use_array
   (local.get $0)
  )
  (call $use_array
   (local.get $0)
  )
 )
)

Note that the second array is replaced with local.get $0, i.e. the first array. But this is incorrect because the first array is already modified by array.copy.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions