13.1 对齐分配器
卷四第 13 章开始进入「规模化」主题:当场景里有成千上万个网格、材质与实例时,内存布局就成了性能分水岭。这一节先看最底层的构件——对齐分配器。SIMD 指令(SSE/NEON)要求 16 字节对齐的内存地址,越界未对齐的指针在 movaps 这类指令上会直接触发异常;即使不走 SIMD,跨缓存行(cache line)的数据也会多浪费一次载入。OGRE 因此提供 AlignedMemory 与 STL 兼容的 AlignedAllocator,让内部容器(如顶点数据、变换矩阵)天然对齐。
本章与站内既有内容的分工
《游戏引擎实现原理》(helio 四卷)从零实现引擎时直接用标准 new/delete 管理对象内存;这里解析真实 OGRE 的 AlignedMemory:它不是一个「更聪明的 new」,而是一个对齐搬运工——分配时多要一点字节、把起点藏在一个偏移字节里,释放时靠那一个字节找回真正的起点。
内存布局与 allocate 算法
OgreAlignedAllocator.cpp 开头画了一张内存布局图,把这次「额外分配」解释得很清楚:
// OgreMain/src/OgreAlignedAllocator.cpp:AlignedMemory::allocate / deallocate(v14.6.3 源码摘录,已删减)
/**
*
* |___2___|3|_________5__________|__6__|
* ^ ^
* 1 4
*
* 1 -> Pointer to start of the block allocated by new.
* 2 -> Gap used to get 4 aligned on given alignment
* 3 -> Byte offset between 1 and 4
* 4 -> Pointer to the start of data block.
* 5 -> Data block.
* 6 -> Wasted memory at rear of data block.
*/
void* AlignedMemory::allocate(size_t size, size_t alignment)
{
assert(0 < alignment && alignment <= 128 && Bitwise::isPO2(alignment));
unsigned char* p = new unsigned char[size + alignment];
size_t offset = alignment - (size_t(p) & (alignment-1));
unsigned char* result = p + offset;
result[-1] = (unsigned char)offset;
return result;
}
...
void AlignedMemory::deallocate(void* p)
{
if (p)
{
unsigned char* mem = (unsigned char*)p;
mem = mem - mem[-1];
delete [] mem;
}
}
算法只有三行,却同时解决了两个问题:
| 步骤 | 做什么 | 为什么 |
|---|---|---|
new unsigned char[size + alignment] | 多分配 alignment 个字节 | 保证在 [p, p+alignment) 内必然存在一个对齐地址 |
offset = alignment - (size_t(p) & (alignment-1)) | 计算从 p 到最近对齐地址的距离 | alignment 是 2 的幂,p & (alignment-1) 就是 p 的低位偏移 |
result[-1] = (unsigned char)offset | 把偏移存在数据区前一个字节 | deallocate 只拿到 result,靠它找回 p |
关键点在于:对齐要求 alignment 必须是 2 的幂(源码里用 Bitwise::isPO2 断言)。OgreBitwise.h 的判定是一个掩码技巧:
// OgreMain/include/OgreBitwise.h:Bitwise::isPO2(v14.6.3 源码摘录,已删减)
/** Determines whether the number is power-of-two or not.
@note 0 and 1 are treat as power of two.
*/
template<typename T>
static OGRE_FORCE_INLINE bool isPO2(T n)
{
return (n & (n-1)) == 0;
}
n & (n-1) == 0 对 0、1、2、4、8、16…都成立——这就是为什么 alignment 必须落在 [1, 128] 且为 2 的幂:offset 的计算完全建立在「alignment-1 的低位全 1」这一性质上。分配失败时 new 抛 std::bad_alloc,符合「On failure, exception will be throw」的契约。
deallocate 找回起点
deallocate 的神奇之处在于零额外信息:它不知道 size、不知道 alignment,只靠 result[-1] 里存的那个偏移字节:
mem = (unsigned char*)p; // p 是数据区起点(result)
mem = mem - mem[-1]; // 回退 offset 字节,回到 new 的起点
delete [] mem; // 按原始指针释放
为什么偏移能安全地存在 result[-1]?因为 result 与 p 之间至少隔着 1 个字节(当 p 恰已对齐时 offset 为 0,此时 result == p,result[-1] 落在 p-1,仍属于 new 分配的 size+alignment 范围)。整个数据区 result[0..size) 完全不受影响。这个「1 字节偏移头」的设计让 AlignedMemory::deallocate(NULL) 是安全空操作——源码第一行就判了 if (p)。
AlignedAllocator:STL 兼容包装
AlignedAllocator.h 把上面的过程包装成 STL 分配器,让 std::vector 这类容器也能走对齐路径:
// OgreMain/include/OgreAlignedAllocator.h:class AlignedAllocator(v14.6.3 源码摘录,已删减)
class _OgreExport AlignedMemory
{
public:
/** Allocate memory with given alignment. ... */
static DECL_MALLOC void* allocate(size_t size, size_t alignment);
/** Allocate memory with default platform dependent alignment. ... */
static DECL_MALLOC void* allocate(size_t size);
...
static void deallocate(void* p);
};
/// STL compatible wrapper for @ref AlignedMemory
template<typename T, size_t Alignment>
struct AlignedAllocator : public std::allocator<T>
{
AlignedAllocator() : std::allocator<T>() {}
template <class U>
AlignedAllocator(const AlignedAllocator<U, Alignment>& other) {};
template<class Other>
struct rebind { using other = AlignedAllocator<Other, Alignment>; };
T* allocate(size_t n) {
return static_cast<T*>(AlignedMemory::allocate(n * sizeof(T), Alignment));
}
T* allocate(size_t n, const void* hint) { // deprecated in C++17
return static_cast<T*>(AlignedMemory::allocate(n * sizeof(T), Alignment));
}
void deallocate(T* p, size_t /*n*/) {
AlignedMemory::deallocate(p);
}
};
注意两处设计取舍:
allocate(n)把n * sizeof(T)交给AlignedMemory,并固定用模板参数Alignment——容器级别的对齐在类型层面确定,编译器能看到每次分配的语义。deallocate(T* p, size_t /*n*/)忽略元素个数,因为AlignedMemory::deallocate只靠偏移字节即可回收——n参数只是 STL 分配器接口的形式要求。
无参的 AlignedMemory::allocate(size_t size) 会走默认平台对齐。OgrePlatform.h 给出定义:
// OgreMain/include/OgrePlatform.h:OGRE_SIMD_ALIGNMENT(v14.6.3 源码摘录,已删减)
/** Find perfect alignment (should supports SIMD alignment if SIMD available) */
#define OGRE_SIMD_ALIGNMENT 16
/* Declare variable aligned to SIMD alignment. */
#define OGRE_SIMD_ALIGNED_DECL(type, var) OGRE_ALIGNED_DECL(type, var, OGRE_SIMD_ALIGNMENT)
OGRE_SIMD_ALIGNMENT 16 是跨平台 SIMD 对齐底线(SSE/NEON 都是 16 字节),OGRE_SIMD_ALIGNED_DECL 再把「对齐声明」下沉到编译器语法(MSVC 的 __declspec(align())、GCC/Clang 的 __attribute__((__aligned__())))。
源码定位
OgreMain/src/OgreAlignedAllocator.cpp:AlignedMemory::allocate(size_t, size_t)(58-69)、AlignedMemory::allocate(size_t)(71-74)、AlignedMemory::deallocate(void*)(76-84)OgreMain/include/OgreAlignedAllocator.h:class _OgreExport AlignedMemory(62)、struct AlignedAllocator : public std::allocator<T>(102-103)、T* allocate(size_t n)(113-115)、void deallocate(T* p, size_t /*n*/)(120-122)OgreMain/include/OgreBitwise.h:static OGRE_FORCE_INLINE bool isPO2(T n)(161-164)OgreMain/include/OgrePlatform.h:#define OGRE_SIMD_ALIGNMENT 16(193)、#define OGRE_SIMD_ALIGNED_DECL(type, var)(196)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面用纯 C++ 复现 AlignedMemory 的对齐分配与回收配对。它与 src/ogre-ext-13-1-aligned-allocator.cpp 逐字节一致:
// file: src/ogre-ext-13-1-aligned-allocator.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/ogre-ext-13-1-aligned-allocator.cpp -o bin/ogre-ext-13-1-aligned-allocator && ./bin/ogre-ext-13-1-aligned-allocator
//
// 复现 AlignedMemory::allocate/deallocate(对应 OgreAlignedAllocator.cpp 58-84):
// over-allocate size+alignment,用 (alignment - (p & (alignment-1))) 计算偏移,
// 把偏移字节存在 result[-1],deallocate 时用 mem[-1] 找回 new 的起点。
// 另用全局计数验证 new/delete 严格配对(回收不泄漏)。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cstdint>
#include <cstdlib>
namespace ogre_repro {
// 统计存活分配块数,验证 deallocate 正确找回起点并回收
static int g_allocCount = 0;
void* alignedAllocate(std::size_t size, std::size_t alignment) {
// 对应源码的 assert:alignment 必须是 2 的幂
if ((alignment & (alignment - 1)) != 0) return nullptr;
unsigned char* p = new unsigned char[size + alignment];
++g_allocCount;
std::size_t offset = alignment - (reinterpret_cast<std::size_t>(p) & (alignment - 1));
unsigned char* result = p + offset;
result[-1] = static_cast<unsigned char>(offset);
return result;
}
void alignedDeallocate(void* p) {
if (!p) return;
unsigned char* mem = static_cast<unsigned char*>(p);
mem = mem - mem[-1];
delete[] mem;
--g_allocCount;
}
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
// 16 字节 SIMD 对齐(对应 OGRE_SIMD_ALIGNMENT)
void* p16 = alignedAllocate(64, 16);
CHECK(reinterpret_cast<std::size_t>(p16) % 16 == 0);
// 偏移字节记录在 result[-1],deallocate 用其找回 new 起点
unsigned char* base16 = static_cast<unsigned char*>(p16);
CHECK(base16[-1] >= 1 && base16[-1] <= 16);
CHECK(g_allocCount == 1);
alignedDeallocate(p16);
CHECK(g_allocCount == 0);
// 128 字节对齐(源码允许的最大 alignment)
void* p128 = alignedAllocate(16, 128);
CHECK(reinterpret_cast<std::size_t>(p128) % 128 == 0);
unsigned char* base128 = static_cast<unsigned char*>(p128);
CHECK(base128[-1] >= 1 && base128[-1] <= 128);
alignedDeallocate(p128);
CHECK(g_allocCount == 0);
// 数据区确实可用:写入并求和读回
void* pData = alignedAllocate(40, 16);
unsigned char* bytes = static_cast<unsigned char*>(pData);
for (int i = 0; i < 40; ++i) bytes[i] = static_cast<uint8_t>(i);
uint32_t sum = 0;
for (int i = 0; i < 40; ++i) sum += bytes[i];
CHECK_EQ(sum, static_cast<uint32_t>(40 * 39 / 2));
alignedDeallocate(pData);
CHECK(g_allocCount == 0);
// alignment = 1:offset = 1 - (p & 0) 恒为 1,result 指向 p+1,仍可回收
void* p1 = alignedAllocate(8, 1);
unsigned char* base1 = static_cast<unsigned char*>(p1);
CHECK(base1[-1] == 1);
CHECK(reinterpret_cast<std::size_t>(p1) % 1 == 0);
alignedDeallocate(p1);
CHECK(g_allocCount == 0);
// 非 2 的幂对齐被拒绝(对应源码 assert 语义)
void* pBad = alignedAllocate(8, 3);
CHECK(pBad == nullptr);
return lab::report("13.1 对齐分配器");
}
本机实测(Apple clang,clang++ -std=c++20 -Wall):编译零警告,断言 13/13 通过。
小结
AlignedMemory::allocate用「多分配 + 偏移字节」在单次new内拿到任意 2 的幂对齐地址。- 偏移字节存在
result[-1],deallocate不需要 size/alignment 就能找回new的起点。 alignment必须是 2 的幂且在[1, 128],由Bitwise::isPO2在断言中把关。AlignedAllocator把对齐语义固化到 STL 容器类型层面,deallocate忽略n只因回收只靠偏移字节。OGRE_SIMD_ALIGNMENT(16)是全平台 SIMD 对齐底线,OGRE_SIMD_ALIGNED_DECL下沉到编译器语法。
阅读导航:上一节:12.3 引擎混合使用 · 下一节:13.2 共享指针 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。