一句话:提出 LLVM 链接时优化,用短指令序列替换 C++ 向下转型库调用,并通过修改 vtable 消除冗余 RTTI 数据。
这篇论文关注 C++ 中 dynamic_cast 和 RTTI 带来的性能与代码体积开销。为支持向下转型、异常和运行时类型内省,编译器为含虚函数的类生成 RTTI 数据,其中包含类型名字符串;在复杂继承层次中,这些数据体积可观,且向下转型算法随层次规模线性增长。常见规避手段 -fno-rtti 会禁用多态异常和动态转换,并因 ABI 变化需全程序应用。作者提出一种链接时优化:将昂贵的向下转型库调用替换为短指令序列,并通过修改 vtable 删除不必要的 RTTI 槽以消除冗余数据。该优化在 LLVM 中实现,平均加速 1.4%,二进制体积平均减少 1.7%。
A core design principle of C++ is that users should only incur costs for features they actually use, both in terms of performance and code size. A notable exception to this rule is the run-time type information (RTTI) data, used for dynamic downcasts, exceptions, and run-time type introspection. For classes that define at least one virtual method, compilers generate RTTI data that uniquely identifies the type, including a string for the type name. In large programs with complex type inheritance hierarchies, this RTTI data can grow substantially in size. Moreover, dynamic casting algorithms are linear in the type hierarchy size, causing some programs to spend considerable time on these casts. The common workaround is to use the -fno-rtti compiler flag, which disables RTTI data generation. However, this approach has significant drawbacks, such as disabling polymorphic exceptions and dynamic casts, and requiring the flag to be applied across the entire program due to ABI changes. In this paper, we propose a new link-time optimization to mitigate both the performance and size overhead associated with dynamic casts and RTTI data. Our optimization replaces costly library calls for downcasts with short instruction sequences and eliminates unnecessary RTTI data by modifying vtables to remove RTTI slots. Our prototype, implemented in the LLVM compiler, demonstrates an average speedup of 1.4%, as well as an average binary size reduction of 1.7%.