clang 24.0.0git
CIRABIRewriteContextAArch64.cpp
Go to the documentation of this file.
1//===- CIRABIRewriteContextAArch64.cpp - AArch64 ABI rewrite context -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// The AArch64 rewrite context, which expands cir.va_arg through the AAPCS64
10// __stack / __gr_top / __vr_top / __gr_offs / __vr_offs va_list.
11//
12//===----------------------------------------------------------------------===//
13
18#include "llvm/Support/Alignment.h"
19#include "llvm/Support/MathExtras.h"
20#include <algorithm>
21
22using namespace cir;
23using namespace mlir;
24using namespace mlir::abi;
25
26namespace {
27
28class AArch64ABIRewriteContext final : public CIRABIRewriteContext {
29public:
30 AArch64ABIRewriteContext(mlir::ModuleOp module, const mlir::DataLayout &dl,
31 bool enableNoundefAttrs, bool softFloat)
32 : CIRABIRewriteContext(module, dl, enableNoundefAttrs),
33 softFloat(softFloat) {}
34
35protected:
36 mlir::LogicalResult expandVAArg(cir::VAArgOp op, const ArgClassification &ac,
37 mlir::OpBuilder &opBuilder) override;
38
39private:
40 /// Whether the module uses the soft-float ABI, which has no vector
41 /// registers, so floating-point and vector values are read from the general
42 /// register save area.
43 bool softFloat;
44};
45
46/// The alignment AAPCS64 places a variadic argument at. This is the
47/// unadjusted alignment, which an `aligned` attribute on a record does not
48/// raise.
49uint64_t unadjustedArgAlign(mlir::Type ty, mlir::ModuleOp modOp,
50 const mlir::DataLayout &dl) {
51 if (auto recTy = mlir::dyn_cast<cir::RecordType>(ty))
52 if (auto layout = cir::tryGetRecordLayout(modOp, recTy.getName()))
53 return layout.getUnadjustedAlign();
54 return dl.getTypeABIAlignment(ty);
55}
56
57/// Whether AAPCS64 treats \p ty as an aggregate rather than a scalar.
58bool isAAPCS64Aggregate(mlir::Type ty) {
59 return mlir::isa<cir::RecordType, cir::ArrayType, cir::ComplexType>(ty);
60}
61
62} // namespace
63
64mlir::LogicalResult AArch64ABIRewriteContext::expandVAArg(
65 cir::VAArgOp op, const ArgClassification &ac, mlir::OpBuilder &opBuilder) {
66 CIRBaseBuilderTy builder(opBuilder);
67 mlir::Location loc = op.getLoc();
68 mlir::Type resultTy = op.getType();
69 mlir::Value valist = op.getArgList();
70
71 switch (ac.kind) {
72 case ArgKind::Direct:
73 case ArgKind::Extend:
74 if (ac.directOffset)
75 return reportVAArgNYI(op, "a type read at an offset into its register");
76 break;
77 case ArgKind::Indirect:
78 if (ac.byVal)
79 return reportVAArgNYI(op, "a type passed byval");
80 break;
81 case ArgKind::IndirectAliased:
82 return reportVAArgNYI(op, "a type passed byref");
83 case ArgKind::Expand:
84 return reportVAArgNYI(op, "a type expanded into its fields");
85 case ArgKind::Ignore:
86 llvm_unreachable("rewriteVAArg replaces an ignored va_arg");
87 }
88
89 auto vaListRecTy = mlir::dyn_cast<cir::RecordType>(
90 mlir::cast<cir::PointerType>(valist.getType()).getPointee());
91 if (!vaListRecTy || vaListRecTy.getNumElements() != 5) {
92 return reportVAArgNYI(op, "a va_list that is not the five-field __stack / "
93 "__gr_top / __vr_top / __gr_offs / __vr_offs "
94 "cursor");
95 }
96 llvm::ArrayRef<mlir::Type> vaFields = vaListRecTy.getMembers();
97
98 cir::IntType byteTy = builder.getUIntNTy(8);
99 bool isIndirect = ac.kind == ArgKind::Indirect;
100 bool isBigEndian = cirDataLayout.isBigEndian();
101 bool isAggregate = isAAPCS64Aggregate(resultTy);
102 uint64_t tySize = dl.getTypeAllocSize(resultTy).getFixedValue();
103 uint64_t tyAlign = unadjustedArgAlign(resultTy, module, dl);
104
105 // An indirect argument is passed as a pointer to a copy. Otherwise the
106 // coerced type says which registers carry the value, and an array coercion
107 // spreads it over one register per element.
108 mlir::Type baseTy = resultTy;
109 if (isIndirect)
110 baseTy = builder.getPointerTo(byteTy);
111 else if (ac.coercedType)
112 baseTy = ac.coercedType;
113 unsigned numRegs = 1;
114 if (auto arrTy = mlir::dyn_cast<cir::ArrayType>(baseTy)) {
115 baseTy = arrTy.getElementType();
116 numRegs = arrTy.getSize();
117 }
118 bool isFPR =
119 !softFloat && mlir::isa<cir::FPTypeInterface, cir::VectorType>(baseTy);
120 bool isHFA = isFPR && isAggregate;
121
122 // Each vector register save slot is 16 bytes, whatever part of it the value
123 // fills. General register slots are 8 bytes and packed.
124 unsigned offsIdx = isFPR ? 4 : 3;
125 unsigned topIdx = isFPR ? 2 : 1;
126 llvm::StringRef offsName = isFPR ? "__vr_offs" : "__gr_offs";
127 llvm::StringRef topName = isFPR ? "__vr_top" : "__gr_top";
128 uint64_t regSize =
129 isFPR ? 16 * numRegs : llvm::alignTo(isIndirect ? 8 : tySize, 8);
130 uint64_t regSlotSize = isFPR ? 16 : 8;
131
132 builder.setInsertionPoint(op);
133
134 // The offset is negative, counting up to zero, while registers remain.
135 // A value aligned to more than 8 bytes starts at an even general register.
136 mlir::Value offsP = builder.createGetMember(
137 loc, builder.getPointerTo(vaFields[offsIdx]), valist, offsName, offsIdx);
138 llvm::Align offsAlign =
139 llvm::commonAlignment(llvm::Align(dl.getTypeABIAlignment(vaListRecTy)),
140 vaListRecTy.getElementOffset(dl, offsIdx));
141 mlir::Value offs =
142 builder.createLoad(loc, offsP, /*isVolatile=*/false, offsAlign.value());
143 mlir::Type offsTy = offs.getType();
144 mlir::Value zero = builder.getConstantInt(loc, offsTy, 0);
145 mlir::Value usingStack =
146 builder.createCompare(loc, cir::CmpOpKind::ge, offs, zero);
147 mlir::Value regOffs = offs;
148 if (!isFPR && !isIndirect && tyAlign > 8) {
149 regOffs = builder.createAdd(
150 loc, offs, builder.getConstantInt(loc, offsTy, tyAlign - 1));
151 regOffs = builder.createAnd(
152 loc, regOffs,
153 builder.getConstantInt(loc, offsTy, -static_cast<int64_t>(tyAlign)));
154 }
155 mlir::Value newOffs = builder.createAdd(
156 loc, regOffs, builder.getConstantInt(loc, offsTy, regSize));
157
158 // Once the offset is non-negative it is left unchanged. Otherwise it is
159 // advanced past this value even when the value does not fit, since an
160 // argument passed on the stack also uses up the remaining registers.
161 mlir::Value inRegs =
162 cir::TernaryOp::create(
163 builder, loc, usingStack,
164 /*trueBuilder=*/
165 [&](mlir::OpBuilder &ob, mlir::Location l) {
166 CIRBaseBuilderTy b(ob);
167 cir::YieldOp::create(b, l, mlir::Value(b.getBool(false, l)));
168 },
169 /*falseBuilder=*/
170 [&](mlir::OpBuilder &ob, mlir::Location l) {
171 CIRBaseBuilderTy b(ob);
172 b.createStore(l, newOffs, offsP, /*isVolatile=*/false,
173 /*isNontemporal=*/false,
174 b.getAlignmentAttr(offsAlign));
175 mlir::Value fits =
176 b.createCompare(l, cir::CmpOpKind::le, newOffs, zero);
177 cir::YieldOp::create(b, l, fits);
178 })
179 .getResult();
180
181 // The members of an HFA in registers are 16 bytes apart, so they are copied
182 // into a temporary where they are contiguous.
183 bool copyHFA = isHFA && numRegs > 1;
184 mlir::Value hfaTemp;
185 uint64_t regAlign = regSlotSize;
186 if (copyHFA) {
187 regAlign = std::max<uint64_t>(tyAlign, dl.getTypeABIAlignment(baseTy));
188 hfaTemp = builder.createAlloca(
189 loc, builder.getPointerTo(cir::ArrayType::get(baseTy, numRegs)),
190 "vaarg.hfa", clang::CharUnits::fromQuantity(regAlign));
191 }
192
193 // On a big-endian target a value smaller than its slot is at the high end
194 // of the slot. In a register slot this applies to scalars and to the
195 // members of an HFA. In a stack slot it applies only to scalars.
196 uint64_t regBEOffset = 0;
197 if (isBigEndian && copyHFA) {
198 uint64_t baseSize = dl.getTypeAllocSize(baseTy).getFixedValue();
199 if (baseSize < 16)
200 regBEOffset = 16 - baseSize;
201 } else if (isBigEndian && !isIndirect && (isHFA || !isAggregate) &&
202 tySize < regSlotSize) {
203 regBEOffset = regSlotSize - tySize;
204 regAlign =
205 llvm::commonAlignment(llvm::Align(regAlign), regBEOffset).value();
206 }
207 uint64_t stackSlotSize = 8;
208 uint64_t stackAlign = std::max<uint64_t>(stackSlotSize, tyAlign);
209 uint64_t stackBEOffset = 0;
210 if (isBigEndian && !isAggregate && tySize < stackSlotSize) {
211 stackBEOffset = stackSlotSize - tySize;
212 stackAlign =
213 llvm::commonAlignment(llvm::Align(stackAlign), stackBEOffset).value();
214 }
215
216 mlir::Value addr =
217 cir::TernaryOp::create(
218 builder, loc, inRegs,
219 /*trueBuilder=*/
220 [&](mlir::OpBuilder &ob, mlir::Location l) {
221 CIRBaseBuilderTy b(ob);
222 mlir::Value regTop = b.createLoad(
223 l, b.createGetMember(l, b.getPointerTo(vaFields[topIdx]),
224 valist, topName, topIdx));
225 mlir::Value regAddr = b.createPtrStride(
226 l, b.createPtrBitcast(regTop, byteTy), regOffs);
227 if (copyHFA) {
228 mlir::Value elems =
229 b.createCast(l, cir::CastKind::array_to_ptrdecay, hfaTemp,
230 b.getPointerTo(baseTy));
231 uint64_t baseSize = dl.getTypeAllocSize(baseTy).getFixedValue();
232 for (unsigned i = 0; i < numRegs; ++i) {
233 uint64_t srcOffset = 16 * i + regBEOffset;
234 mlir::Value src = b.createPtrStride(
235 l, regAddr, b.getSignedInt(l, srcOffset, 64));
236 mlir::Value elem = b.createAlignedLoad(
237 l, b.createPtrBitcast(src, baseTy),
238 llvm::commonAlignment(llvm::Align(16), srcOffset).value());
239 mlir::Value dst =
240 b.createPtrStride(l, elems, b.getSignedInt(l, i, 64));
241 b.createStore(l, elem, dst, /*isVolatile=*/false,
242 /*isNontemporal=*/false,
243 b.getAlignmentAttr(llvm::commonAlignment(
244 llvm::Align(regAlign), i * baseSize)));
245 }
246 regAddr = b.createPtrBitcast(hfaTemp, byteTy);
247 } else if (regBEOffset) {
248 regAddr = b.createPtrStride(l, regAddr,
249 b.getSignedInt(l, regBEOffset, 64));
250 }
251 cir::YieldOp::create(b, l, regAddr);
252 },
253 /*falseBuilder=*/
254 [&](mlir::OpBuilder &ob, mlir::Location l) {
255 CIRBaseBuilderTy b(ob);
256 mlir::Value stackP = b.createGetMember(
257 l, b.getPointerTo(vaFields[0]), valist, "__stack", 0);
258 mlir::Value stack =
259 b.createPtrBitcast(b.createLoad(l, stackP), byteTy);
260 if (!isIndirect && tyAlign > 8)
261 stack = roundPointerUpToAlignment(b, l, stack, tyAlign);
262 uint64_t stackSize = isIndirect
263 ? stackSlotSize
264 : llvm::alignTo(tySize, stackSlotSize);
265 b.createStore(
266 l,
267 b.createPtrStride(l, stack, b.getSignedInt(l, stackSize, 64)),
268 stackP);
269 if (stackBEOffset)
270 stack = b.createPtrStride(l, stack,
271 b.getSignedInt(l, stackBEOffset, 64));
272 cir::YieldOp::create(b, l, stack);
273 })
274 .getResult();
275
276 uint64_t addrAlign = std::min(regAlign, stackAlign);
277 mlir::Value resultAddr;
278 uint64_t resultAlign;
279 if (isIndirect) {
280 mlir::Value ptrAddr =
281 builder.createPtrBitcast(addr, builder.getPointerTo(resultTy));
282 resultAddr = builder.createAlignedLoad(loc, ptrAddr, addrAlign);
283 resultAlign = tyAlign;
284 } else {
285 resultAddr = builder.createPtrBitcast(addr, resultTy);
286 resultAlign = addrAlign;
287 }
288
289 if (mlir::isa<cir::RecordType>(resultTy)) {
290 SmallPtrSet<mlir::Operation *, 1> noExceptions;
291 if (failed(rewireRecordUses(builder, loc, op.getResult(), resultAddr,
292 resultAlign, noExceptions)))
293 return mlir::failure();
294 } else {
295 op.getResult().replaceAllUsesWith(
296 builder.createAlignedLoad(loc, resultAddr, resultAlign));
297 }
298 op->erase();
299 return mlir::success();
300}
301
302std::unique_ptr<CIRABIRewriteContext>
304 const mlir::DataLayout &dl,
305 bool enableNoundefAttrs, bool softFloat) {
306 return std::make_unique<AArch64ABIRewriteContext>(
307 module, dl, enableNoundefAttrs, softFloat);
308}
CIR-specific implementation of mlir::abi::ABIRewriteContext.
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
RecordLayoutAttr tryGetRecordLayout(mlir::ModuleOp mod, mlir::StringAttr name)
Same lookup as getRecordLayout, but returns a null attribute instead of asserting when the record has...
std::unique_ptr< CIRABIRewriteContext > createAArch64ABIRewriteContext(mlir::ModuleOp module, const mlir::DataLayout &dl, bool enableNoundefAttrs, bool softFloat)
A rewrite context that expands cir.va_arg through the AAPCS64 va_list.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t