英特尔处理器上的未对齐访问商店

unaligned access store on intel processor

本文关键字:访问 对齐 处理器 英特尔      更新时间:2023-10-16

考虑以下样本。它在标记的线上用GCC 5.4划分时我用g++ -O3 -std=c++11编译。它在movaps上失败了,我怀疑它执行了不一致的内存访问。可能是GCC生成如此简单的样本的非法代码,或者我缺少某些内容?我正在Intel i5-5200U上运行它。

#include <vector>
#include <memory>
#include <cstdint>
using namespace std;
__attribute__ ((noinline))
void SerializeTo(const vector<uint64_t>& v, uint8_t* dest) {
  for (size_t i = 0; i < v.size(); ++i) {
    *reinterpret_cast<uint64_t*>(dest) = v[i];  // Segfaults here.
    dest += sizeof(uint64_t);
  }
}
int main() {
 std::vector<uint64_t> d(64);
 unique_ptr<uint8_t[]> tmp(new uint8_t[1024]);
 SerializeTo(d, tmp.get() + 6);
 return 0;
}

您被6个字节踏入数组,因此现在不结盟。编译器不知道它必须避免需要对齐的说明;这就是为什么PUNNING是不确定的行为。

在C 中合法执行键入的方法很少。

魔术功能std::memcpy是这里选择的工具:

__attribute__ ((noinline))
void SerializeTo(const vector<uint64_t>& v, uint8_t* dest) {
  for (size_t i = 0; i < v.size(); ++i) {
      std::memcpy(dest, std::addressof(v[i]), sizeof(v[i]));
    dest += sizeof(uint64_t);
  }
}

-std=c++11 -O3 -march=native -Wall -pedantic

产生的输出
SerializeTo(std::vector<unsigned long, std::allocator<unsigned long> > const&, unsigned char*):   # @SerializeTo(std::vector<unsigned long, std::allocator<unsigned long> > const&, unsigned char*)
        mov     rax, qword ptr [rdi]
        cmp     qword ptr [rdi + 8], rax
        je      .LBB0_3
        xor     ecx, ecx
.LBB0_2:                                # =>This Inner Loop Header: Depth=1
        mov     rax, qword ptr [rax + 8*rcx]
        mov     qword ptr [rsi + 8*rcx], rax
        add     rcx, 1
        mov     rax, qword ptr [rdi]
        mov     rdx, qword ptr [rdi + 8]
        sub     rdx, rax
        sar     rdx, 3
        cmp     rcx, rdx
        jb      .LBB0_2
.LBB0_3:
        ret

https://godbolt.org/g/rega9n