x86位移UB

博客目录

2019-09-30 10:18 +0800

2019-09-30 10:44 +0800

What happened?

在写PA2的时候,写出了如下指令:

// s0 <- 4
rtl_shli(&s0, &s0, 0x3); // s0 <- 32
rtl_shl(&t0, &id_dest->val, &s0);
rtl_shr(&t0, &t0, &s0);

结果运行之后t0中保存的值是id_dest->val,而不是0。(这个bug找了我大半天)

接着写了一个简单的测试

#include <stdio.h>
#include <stdint.h>
int main() {
  uint32_t x = 0x123;
  printf("%x << 32 = %x\n", x, x << 32);
  return 0;
}

本地编译(gcc 9.1.0)后运行得到

123 << 32 = 123

但是网上随便找了个在线IDE运行之后得到

123 << 32 = 0

meme

为什么我去年写PA的时候就没遇到这个问题呢?

怎么想都是新版gcc的锅 把这个问题发到扣扣群里被老师骂去RTFM

meme

RTFM

AMD:

AMD64

Intel:

Intel64

How to solve it

// s0 <- 4
rtl_shli(&s0, &s0, 0x2); // s0 <- 16
rtl_shl(&t0, &id_dest->val, &s0);
rtl_shl(&t0, &t0, &s0);
rtl_shr(&t0, &t0, &s0);
rtl_shr(&t0, &t0, &s0);

meme

Problem solved with only RTL instructions!

评论功能因技术问题暂时关闭
Comments are disabled due to technical issues.
Alternative: mail to blog.doowzs[at]outlook.com