Skip to content

clang emits invalid wasm code when compiling C #108770

@TerrorJack

Description

@TerrorJack

Minimal repro:

extern int a;
void* b();
void c(void *);
void f() {
  void *d = b();
e:
  switch (a)
  case 0: {
    b();
    c(d);
    c((void *)*(int *)(d + -sizeof(int)));
    d = d - sizeof(int);
    goto e;
  }
}

The above code, when compiled with --target=wasm32 -O1 using latest clang on main, will produce the following invalid assembly code:

f:                                      # @f
        .functype       f () -> ()
        .local          i32
# %bb.0:
        call    b
        local.set       0
        block
        i32.const       0
        i32.load        a
        br_if           0                               # 0: down to label0
# %bb.1:
        local.get       0
        local.set       0
.LBB0_2:                                # =>This Inner Loop Header: Depth=1
        loop                                            # label1:
        call    b
        drop
        local.get       0
        local.tee       0
        call    c
        local.get       0
        i32.load        -4
        call    c
        local.get       0
        i32.const       -4
        i32.add
        local.set       0
        i32.const       0
        i32.load        a
        i32.eqz
        br_if           0                               # 0: up to label1
.LBB0_3:
        end_loop
        end_block                               # label0:
                                        # fallthrough-return
        end_function

Note the i32.load -4 line. This is invalid per wasm spec, the memarg offset/align must all be non-negative u32 literals. And indeed this code will trigger a memory trap at runtime!

I bisected this bug on master and the first bad commit is 7eca38c. cc @hazzlim

Metadata

Metadata

Assignees

No one assigned

    Labels

    backend:WebAssemblyquestionA question, not bug report. Check out https://llvm.org/docs/GettingInvolved.html instead!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions