Skip to content

Commit 2236afc

Browse files
committed
GSoC 2025 blog on the ABI lowering library
1 parent 98af07b commit 2236afc

File tree

3 files changed

+246
-0
lines changed

3 files changed

+246
-0
lines changed
Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
---
2+
author: "Narayan Sreekumar (vortex73)"
3+
date: "2025-08-25"
4+
tags: ["GSoC", "abi", "codegen", "sysv"]
5+
title: "GSoC 2025: Introducing an ABI Lowering Library"
6+
---
7+
8+
# Introduction
9+
10+
In this post I'm going to outline details about a new ABI lowering library I've been developing for LLVM as part of GSoC 2025! The aim was to extract the ABI logic from Clang and create a reusable library that any LLVM frontend can use for correct C interoperability.
11+
12+
# The Problem We're Solving
13+
14+
At the start of the program, I wrote about the [fundamental gap in LLVM's target abstraction](https://vortex73.github.io/rendered/GSOC_BLOG1.html). The promise is simple: frontends emit LLVM IR, and LLVM handles everything else. But this promise completely breaks down when it comes to Application Binary Interface (ABI) lowering. Every LLVM frontend that wants C interoperability has to reimplement thousands of lines of target-specific ABI logic.
15+
16+
Here's what that looks like in practice:
17+
```cpp
18+
struct Point { float x, y; };
19+
struct Point add_points(struct Point a, struct Point b);
20+
```
21+
22+
Seems innocent enough, right? But generating correct LLVM IR for this requires knowing:
23+
- Are the struct arguments passed in registers or memory?
24+
- If in registers, what register class is used?
25+
- Are multiple values packed into a single register?
26+
- Is the struct returned in registers or using a hidden return parameter?
27+
28+
The answer depends on subtle ABI rules that are target-specific, constantly evolving, and absolutely critical to get right. Miss one detail and you get silent memory corruption.
29+
30+
[This godbolt link](https://clang.godbolt.org/z/P4fMj7hjY) shows the same simple struct using six different calling conventions across six different targets. And crucially: a frontend generating IR needs to know ALL of this before it can emit the right function signature.
31+
32+
As I outlined in my earlier blog post, LLVM's type system simply can't express all the information needed for correct ABI decisions. Two otherwise identical structs with different explicit alignment attributes have different ABIs. `__int128` and `_BitInt(128)` look similar but follow completely different rules.
33+
34+
# The Design
35+
36+
<div style="margin:0 auto;">
37+
<img src="/img/abi_flow.png"><br/>
38+
</div>
39+
40+
41+
42+
## Independent ABI Type System
43+
44+
At the heart of the library is `llvm::abi::Type`, a type system designed specifically for ABI decisions:
45+
46+
```cpp
47+
class Type {
48+
protected:
49+
TypeKind Kind;
50+
TypeSize SizeInBits;
51+
Align ABIAlignment;
52+
53+
public:
54+
TypeKind getKind() const { return Kind; }
55+
TypeSize getSizeInBits() const { return SizeInBits; }
56+
Align getAlignment() const { return ABIAlignment; }
57+
58+
bool isInteger() const { return Kind == TypeKind::Integer; }
59+
bool isStruct() const { return Kind == TypeKind::Struct; }
60+
// ... other predicates that matter for ABI
61+
};
62+
```
63+
64+
It contains **more information than LLVM IR types** (which for instance doesn't distinguish between `__int128` and `_BitInt(128)`, both just `i128`), but **less information than frontend types** like Clang's QualType (which carry parsing context, sugar, and other frontend-specific concerns that don't matter for calling conventions).
65+
```cpp
66+
class IntegerType : public Type {
67+
private:
68+
bool IsSigned;
69+
bool IsBitInt; // Crucially different from __int128!
70+
71+
public:
72+
IntegerType(uint64_t BitWidth, Align Align, bool Signed,
73+
bool BitInt = false);
74+
};
75+
```
76+
77+
## Frontend-to-ABI Mapping
78+
79+
The `QualTypeMapper` class handles the job of converting Clang frontend types to ABI types.
80+
81+
**The ABI library is primarily intended to handle the C ABI.** The C type system is relatively simple, and as such the type mapping from frontend types to ABI types is straightforward : integers map to `IntegerType`, pointers map to `PointerType`, and structs map to `StructType` with their fields and offsets preserved.
82+
83+
However, Clang also needs support for the C++ ABI, and the type mapping for this case is significantly more complicated. C++ object layout involves vtables, base class subobjects, virtual inheritance, and all sorts of edge cases that need to be preserved for correct ABI decisions. Here's an excerpt showing how `QualTypeMapper` tackles C++ inheritance:
84+
```cpp
85+
const llvm::abi::StructType *
86+
QualTypeMapper::convertCXXRecordType(const CXXRecordDecl *RD,
87+
bool canPassInRegs) {
88+
const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(RD);
89+
SmallVector<llvm::abi::FieldInfo, 16> Fields;
90+
SmallVector<llvm::abi::FieldInfo, 8> BaseClasses;
91+
SmallVector<llvm::abi::FieldInfo, 8> VirtualBaseClasses;
92+
93+
// Handle vtable pointer for polymorphic classes
94+
if (RD->isPolymorphic()) {
95+
const llvm::abi::Type *VtablePointer =
96+
createPointerTypeForPointee(ASTCtx.VoidPtrTy);
97+
Fields.emplace_back(VtablePointer, 0);
98+
}
99+
100+
// Process base classes with proper offset calculation
101+
for (const auto &Base : RD->bases()) {
102+
const llvm::abi::Type *BaseType = convertType(Base.getType());
103+
uint64_t BaseOffset = Layout.getBaseClassOffset(
104+
Base.getType()->castAs<RecordType>()->getAsCXXRecordDecl()
105+
).getQuantity() * 8;
106+
107+
if (Base.isVirtual())
108+
VirtualBaseClasses.emplace_back(BaseType, BaseOffset);
109+
else
110+
BaseClasses.emplace_back(BaseType, BaseOffset);
111+
}
112+
113+
// ... field processing and final struct creation
114+
}
115+
```
116+
Other frontends that only need C interoperability will have a much simpler mapping task.
117+
118+
## Target-Specific Classification
119+
120+
Each target implements the ABIInfo interface. I'll show the BPF implementation here since it's one of the simplest ABIs in LLVM, the classification logic fits in about 50 lines of code with straightforward rules: small aggregates go in registers, larger ones are passed indirectly.
121+
122+
Its worth noting that most real-world ABIs are not *this* simple - for instance targets like X86-64 are significantly more complex.
123+
```cpp
124+
class BPFABIInfo : public ABIInfo {
125+
private:
126+
TypeBuilder &TB;
127+
128+
public:
129+
BPFABIInfo(TypeBuilder &TypeBuilder) : TB(TypeBuilder) {}
130+
131+
ABIArgInfo classifyArgumentType(const Type *ArgTy) const {
132+
if (isAggregateTypeForABI(ArgTy)) {
133+
auto SizeInBits = ArgTy->getSizeInBits().getFixedValue();
134+
if (SizeInBits == 0)
135+
return ABIArgInfo::getIgnore();
136+
137+
if (SizeInBits <= 128) {
138+
const Type *CoerceTy;
139+
if (SizeInBits <= 64) {
140+
auto AlignedBits = alignTo(SizeInBits, 8);
141+
CoerceTy = TB.getIntegerType(AlignedBits, Align(8), false);
142+
} else {
143+
const Type *RegTy = TB.getIntegerType(64, Align(8), false);
144+
CoerceTy = TB.getArrayType(RegTy, 2, 128);
145+
}
146+
return ABIArgInfo::getDirect(CoerceTy);
147+
}
148+
149+
return ABIArgInfo::getIndirect(ArgTy->getAlignment().value());
150+
}
151+
152+
if (const auto *IntTy = dyn_cast<IntegerType>(ArgTy)) {
153+
auto BitWidth = IntTy->getSizeInBits().getFixedValue();
154+
if (IntTy->isBitInt() && BitWidth > 128)
155+
return ABIArgInfo::getIndirect(ArgTy->getAlignment().value());
156+
157+
if (isPromotableInteger(IntTy))
158+
return ABIArgInfo::getExtend(ArgTy);
159+
}
160+
return ABIArgInfo::getDirect();
161+
}
162+
};
163+
```
164+
165+
The key difference is that the ABI classification logic itself is **completely independent of Clang**. Any LLVM frontend can use it by implementing a mapper from their types to `llvm::abi::Type`. The library then performs ABI classification and outputs `llvm::abi::ABIFunctionInfo` with all the lowering decisions.
166+
167+
For Clang specifically, the `ABITypeMapper` converts those `llvm::abi::Type` results back into `llvm::Type` and populates `clang::CGFunctionInfo`, which then continues through the normal IR generation pipeline.
168+
# Results
169+
The library and the new type system are implemented and working in the [PR #140112](https://github.com/llvm/llvm-project/pull/140112), currently enabled for BPF and X86-64 Linux targets. You can find the implementation under `llvm/lib/ABI/` with Clang integration in `clang/lib/CodeGen/CGCall.cpp`. Here's what we've achieved so far:
170+
171+
## Clean Architecture
172+
173+
The three-layer separation is working beautifully. Frontend concerns, ABI classification, and IR generation are now properly separated:
174+
175+
```cpp
176+
// Integration point in Clang
177+
if (CGM.shouldUseLLVMABI()) {
178+
SmallVector<const llvm::abi::Type *, 8> MappedArgTypes;
179+
for (CanQualType ArgType : argTypes)
180+
MappedArgTypes.push_back(getMapper().convertType(ArgType));
181+
182+
tempFI.reset(llvm::abi::ABIFunctionInfo::create(
183+
CC, getMapper().convertType(resultType), MappedArgTypes));
184+
185+
CGM.fetchABIInfo(getTypeBuilder()).computeInfo(*tempFI);
186+
} else {
187+
CGM.getABIInfo().computeInfo(*FI); // Legacy path
188+
}
189+
```
190+
191+
## Performance Considerations Addressed
192+
193+
My earlier blog post worried about the overhead of "an additional type system." The caching strategy handles this elegantly:
194+
195+
```cpp
196+
const llvm::abi::Type *QualTypeMapper::convertType(QualType QT) {
197+
QT = QT.getCanonicalType().getUnqualifiedType();
198+
199+
auto It = TypeCache.find(QT);
200+
if (It != TypeCache.end())
201+
return It->second; // Cache hit - no recomputation
202+
203+
const llvm::abi::Type *Result = /* conversion logic */;
204+
205+
if (Result)
206+
TypeCache[QT] = Result;
207+
return Result;
208+
}
209+
```
210+
211+
Combined with `BumpPtrAllocator` for type storage, the performance impact is minimal in practice.
212+
213+
<div style="margin:0 auto;">
214+
<img src="/img/abi_library_benchmarks.png"><br/>
215+
</div>
216+
217+
The results are encouraging. Most compilation stages show essentially no performance difference (well within measurement noise). The 0.20% regression in the final Clang build times is expected - we've added new code to the codebase. But the actual compilation performance impact is negligible.
218+
219+
# Future Work
220+
221+
There's still plenty to explore:
222+
223+
## Upstreaming the progress so far...
224+
225+
The work is being upstreamed to LLVM in stages, starting with [PR #158329](https://github.com/llvm/llvm-project/pull/158329). This involves addressing reviewer feedback, ensuring compatibility with existing code, and validating that the new system produces identical results to the current implementation for all supported targets.
226+
227+
## Extended Target Support
228+
229+
Currently the ABI library supports the BPF and X86-64 SysV ABIs, but the architecture makes adding ARM, Windows calling conventions, and other targets straightforward.
230+
231+
## Cross-Frontend Compatibility
232+
233+
The real test will be when other frontends start using the library. We need to ensure that all frontends generate identical calling conventions for the same C function signature.
234+
235+
236+
## Better Integration
237+
238+
There are still some rough edges in the Clang integration that could be smoothed out. And other LLVM projects could benefit from adopting the library.
239+
240+
# Acknowledgements
241+
242+
This work wouldn't have been possible without my amazing mentors, Nikita Popov and Maksim Levental, who provided invaluable guidance throughout the project. The LLVM community's feedback on the [original RFC](https://discourse.llvm.org/t/rfc-an-abi-lowering-library-for-llvm/84495) was instrumental in shaping the design.
243+
244+
Special thanks to everyone who reviewed the code, provided feedback, and helped navigate all the ABI corner cases. The architecture only works because it's built on decades of accumulated ABI knowledge that was already present in LLVM and Clang.
245+
246+
Looking back at my precursor blog post from earlier this year, I'm amazed at how much the design evolved during implementation. What started as a relatively straightforward "extract Clang's ABI code" became a much more ambitious architectural rework. But the result is something that's genuinely useful for the entire LLVM ecosystem.

static/img/abi_flow.png

82.3 KB
Loading
53.6 KB
Loading

0 commit comments

Comments
 (0)