[Bug other/97417] RISC-V Unnecessary andi instruction when loading volatile bool

jiawei at iscas dot ac.cn gcc-bugzilla@gcc.gnu.org
Tue Oct 27 11:18:28 GMT 2020


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97417

--- Comment #4 from jiawei <jiawei at iscas dot ac.cn> ---
I had did some tests with this problem and find:

foo.c

#include <stdbool.h>

extern volatile bool active;

int foo(void)
{
  if (!active) {
    return 42;
  } else {
    return -42;
  }
}

code generated in foo.s

foo:
        lui     a5,%hi(active)
        lbu     a5,%lo(active)(a5)
        li      a0,42
        andi    a5,a5,0xff
        beq     a5,zero,.L2
        li      a0,-42

When we remove the keyword `volatile`

foo_without_volatile.c

#include <stdbool.h>

extern bool active;

int foo(void)
{
  if (!active) {
    return 42;
  } else {
    return -42;
  }
}

code generated in foo_without_volatile.s

foo:
        lui     a5,%hi(active)
        lbu     a5,%lo(active)(a5)
        li      a0,42
        beq     a5,zero,.L2
        li      a0,-42

and then we change the type from `bool` to `int`

foo_int.c

#include <stdbool.h>

extern volatile int active;

int foo(void)
{
  if (!active) {
    return 42;
  } else {
    return -42;
  }
}

code generated in foo_int.s

foo:
        lui     a5,%hi(active)
        lw      a5,%lo(active)(a5)
        li      a0,42
        sext.w  a5,a5
        beq     a5,zero,.L2
        li      a0,-42

the `sext.w` instruction replace the `andi`

We also remove the keyword `volatile` in foo_int_without_volatile.c

#include <stdbool.h>

extern int active;

int foo(void)
{
  if (!active) {
    return 42;
  } else {
    return -42;
  }
}

code generated in foo_int_without_volatile.s also look like optimized

foo:
        lui     a5,%hi(active)
        lw      a5,%lo(active)(a5)
        li      a0,42
        beq     a5,zero,.L2
        li      a0,-42

Maybe this problem is due to the keyword `volatile`.


More information about the Gcc-bugs mailing list