blob: e45195dd261d3bffa43c3b2b3ad5b8ed9068be68 [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000018#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000021#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000022#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000025#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall943fae92010-05-27 06:19:26 +000029static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
30 llvm::Value *Array,
31 llvm::Value *Value,
32 unsigned FirstIndex,
33 unsigned LastIndex) {
34 // Alternatively, we could emit this as a loop in the source.
35 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
36 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
37 Builder.CreateStore(Value, Cell);
38 }
39}
40
John McCalla1dee5302010-08-22 10:59:02 +000041static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000042 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000043 T->isMemberFunctionPointerType();
44}
45
Anton Korobeynikov244360d2009-06-05 22:08:42 +000046ABIInfo::~ABIInfo() {}
47
Mark Lacey3825e832013-10-06 01:33:34 +000048static bool isRecordReturnIndirect(const RecordType *RT,
49 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000050 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
51 if (!RD)
52 return false;
Mark Lacey3825e832013-10-06 01:33:34 +000053 return CXXABI.isReturnTypeIndirect(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000054}
55
56
Mark Lacey3825e832013-10-06 01:33:34 +000057static bool isRecordReturnIndirect(QualType T, CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000058 const RecordType *RT = T->getAs<RecordType>();
59 if (!RT)
60 return false;
Mark Lacey3825e832013-10-06 01:33:34 +000061 return isRecordReturnIndirect(RT, CXXABI);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000062}
63
64static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000065 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000066 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
67 if (!RD)
68 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000069 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000070}
71
72static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000073 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000074 const RecordType *RT = T->getAs<RecordType>();
75 if (!RT)
76 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000077 return getRecordArgABI(RT, CXXABI);
78}
79
80CGCXXABI &ABIInfo::getCXXABI() const {
81 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000082}
83
Chris Lattner2b037972010-07-29 02:01:43 +000084ASTContext &ABIInfo::getContext() const {
85 return CGT.getContext();
86}
87
88llvm::LLVMContext &ABIInfo::getVMContext() const {
89 return CGT.getLLVMContext();
90}
91
Micah Villmowdd31ca12012-10-08 16:25:52 +000092const llvm::DataLayout &ABIInfo::getDataLayout() const {
93 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000094}
95
John McCallc8e01702013-04-16 22:48:15 +000096const TargetInfo &ABIInfo::getTarget() const {
97 return CGT.getTarget();
98}
Chris Lattner2b037972010-07-29 02:01:43 +000099
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000100void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000101 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000102 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000103 switch (TheKind) {
104 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000105 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000106 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000107 Ty->print(OS);
108 else
109 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000110 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000111 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000112 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000113 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000114 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000115 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000116 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000117 case InAlloca:
118 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
119 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000120 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000121 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000122 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000123 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000124 break;
125 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000126 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000127 break;
128 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000129 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000130}
131
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000132TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
133
John McCall3480ef22011-08-30 01:42:09 +0000134// If someone can figure out a general rule for this, that would be great.
135// It's probably just doomed to be platform-dependent, though.
136unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
137 // Verified for:
138 // x86-64 FreeBSD, Linux, Darwin
139 // x86-32 FreeBSD, Linux, Darwin
140 // PowerPC Linux, Darwin
141 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000142 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000143 return 32;
144}
145
John McCalla729c622012-02-17 03:33:10 +0000146bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
147 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000148 // The following conventions are known to require this to be false:
149 // x86_stdcall
150 // MIPS
151 // For everything else, we just prefer false unless we opt out.
152 return false;
153}
154
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000155void
156TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
157 llvm::SmallString<24> &Opt) const {
158 // This assumes the user is passing a library name like "rt" instead of a
159 // filename like "librt.a/so", and that they don't care whether it's static or
160 // dynamic.
161 Opt = "-l";
162 Opt += Lib;
163}
164
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000165static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000166
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000167/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000168/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000169static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
170 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000171 if (FD->isUnnamedBitfield())
172 return true;
173
174 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000175
Eli Friedman0b3f2012011-11-18 03:47:20 +0000176 // Constant arrays of empty records count as empty, strip them off.
177 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000178 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000179 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
180 if (AT->getSize() == 0)
181 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000182 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000183 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000184
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000185 const RecordType *RT = FT->getAs<RecordType>();
186 if (!RT)
187 return false;
188
189 // C++ record fields are never empty, at least in the Itanium ABI.
190 //
191 // FIXME: We should use a predicate for whether this behavior is true in the
192 // current ABI.
193 if (isa<CXXRecordDecl>(RT->getDecl()))
194 return false;
195
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000196 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000197}
198
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000199/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000200/// fields. Note that a structure with a flexible array member is not
201/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000202static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000203 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000204 if (!RT)
205 return 0;
206 const RecordDecl *RD = RT->getDecl();
207 if (RD->hasFlexibleArrayMember())
208 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000209
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000210 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000211 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000212 for (const auto &I : CXXRD->bases())
213 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000214 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000215
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000216 for (const auto *I : RD->fields())
217 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000218 return false;
219 return true;
220}
221
222/// isSingleElementStruct - Determine if a structure is a "single
223/// element struct", i.e. it has exactly one non-empty field or
224/// exactly one field which is itself a single element
225/// struct. Structures with flexible array members are never
226/// considered single element structs.
227///
228/// \return The field declaration for the single non-empty field, if
229/// it exists.
230static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
231 const RecordType *RT = T->getAsStructureType();
232 if (!RT)
233 return 0;
234
235 const RecordDecl *RD = RT->getDecl();
236 if (RD->hasFlexibleArrayMember())
237 return 0;
238
239 const Type *Found = 0;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000240
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000241 // If this is a C++ record, check the bases first.
242 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000243 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000244 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000245 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000246 continue;
247
248 // If we already found an element then this isn't a single-element struct.
249 if (Found)
250 return 0;
251
252 // If this is non-empty and not a single element struct, the composite
253 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000254 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000255 if (!Found)
256 return 0;
257 }
258 }
259
260 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000261 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000262 QualType FT = FD->getType();
263
264 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000265 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000266 continue;
267
268 // If we already found an element then this isn't a single-element
269 // struct.
270 if (Found)
271 return 0;
272
273 // Treat single element arrays as the element.
274 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
275 if (AT->getSize().getZExtValue() != 1)
276 break;
277 FT = AT->getElementType();
278 }
279
John McCalla1dee5302010-08-22 10:59:02 +0000280 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000281 Found = FT.getTypePtr();
282 } else {
283 Found = isSingleElementStruct(FT, Context);
284 if (!Found)
285 return 0;
286 }
287 }
288
Eli Friedmanee945342011-11-18 01:25:50 +0000289 // We don't consider a struct a single-element struct if it has
290 // padding beyond the element type.
291 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
292 return 0;
293
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000294 return Found;
295}
296
297static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000298 // Treat complex types as the element type.
299 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
300 Ty = CTy->getElementType();
301
302 // Check for a type which we know has a simple scalar argument-passing
303 // convention without any padding. (We're specifically looking for 32
304 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000305 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000306 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000307 return false;
308
309 uint64_t Size = Context.getTypeSize(Ty);
310 return Size == 32 || Size == 64;
311}
312
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000313/// canExpandIndirectArgument - Test whether an argument type which is to be
314/// passed indirectly (on the stack) would have the equivalent layout if it was
315/// expanded into separate arguments. If so, we prefer to do the latter to avoid
316/// inhibiting optimizations.
317///
318// FIXME: This predicate is missing many cases, currently it just follows
319// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
320// should probably make this smarter, or better yet make the LLVM backend
321// capable of handling it.
322static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
323 // We can only expand structure types.
324 const RecordType *RT = Ty->getAs<RecordType>();
325 if (!RT)
326 return false;
327
328 // We can only expand (C) structures.
329 //
330 // FIXME: This needs to be generalized to handle classes as well.
331 const RecordDecl *RD = RT->getDecl();
332 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
333 return false;
334
Eli Friedmane5c85622011-11-18 01:32:26 +0000335 uint64_t Size = 0;
336
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000337 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000338 if (!is32Or64BitBasicType(FD->getType(), Context))
339 return false;
340
341 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
342 // how to expand them yet, and the predicate for telling if a bitfield still
343 // counts as "basic" is more complicated than what we were doing previously.
344 if (FD->isBitField())
345 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000346
347 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000348 }
349
Eli Friedmane5c85622011-11-18 01:32:26 +0000350 // Make sure there are not any holes in the struct.
351 if (Size != Context.getTypeSize(Ty))
352 return false;
353
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000354 return true;
355}
356
357namespace {
358/// DefaultABIInfo - The default implementation for ABI specific
359/// details. This implementation provides information which results in
360/// self-consistent and sensible LLVM IR generation, but does not
361/// conform to any particular ABI.
362class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000363public:
364 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000365
Chris Lattner458b2aa2010-07-29 02:16:43 +0000366 ABIArgInfo classifyReturnType(QualType RetTy) const;
367 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000368
Craig Topper4f12f102014-03-12 06:41:41 +0000369 void computeInfo(CGFunctionInfo &FI) const override {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000370 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000371 for (auto &I : FI.arguments())
372 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000373 }
374
Craig Topper4f12f102014-03-12 06:41:41 +0000375 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
376 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000377};
378
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000379class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
380public:
Chris Lattner2b037972010-07-29 02:01:43 +0000381 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
382 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000383};
384
385llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
386 CodeGenFunction &CGF) const {
387 return 0;
388}
389
Chris Lattner458b2aa2010-07-29 02:16:43 +0000390ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Jan Wen Voung180319f2011-11-03 00:59:44 +0000391 if (isAggregateTypeForABI(Ty)) {
Alp Tokerd4733632013-12-05 04:47:09 +0000392 // Records with non-trivial destructors/constructors should not be passed
Jan Wen Voung180319f2011-11-03 00:59:44 +0000393 // by value.
Mark Lacey3825e832013-10-06 01:33:34 +0000394 if (isRecordReturnIndirect(Ty, getCXXABI()))
Jan Wen Voung180319f2011-11-03 00:59:44 +0000395 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
396
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000397 return ABIArgInfo::getIndirect(0);
Jan Wen Voung180319f2011-11-03 00:59:44 +0000398 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000399
Chris Lattner9723d6c2010-03-11 18:19:55 +0000400 // Treat an enum type as its underlying type.
401 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
402 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000403
Chris Lattner9723d6c2010-03-11 18:19:55 +0000404 return (Ty->isPromotableIntegerType() ?
405 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000406}
407
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000408ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
409 if (RetTy->isVoidType())
410 return ABIArgInfo::getIgnore();
411
412 if (isAggregateTypeForABI(RetTy))
413 return ABIArgInfo::getIndirect(0);
414
415 // Treat an enum type as its underlying type.
416 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
417 RetTy = EnumTy->getDecl()->getIntegerType();
418
419 return (RetTy->isPromotableIntegerType() ?
420 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
421}
422
Derek Schuff09338a22012-09-06 17:37:28 +0000423//===----------------------------------------------------------------------===//
424// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000425//
426// This is a simplified version of the x86_32 ABI. Arguments and return values
427// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000428//===----------------------------------------------------------------------===//
429
430class PNaClABIInfo : public ABIInfo {
431 public:
432 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
433
434 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000435 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000436
Craig Topper4f12f102014-03-12 06:41:41 +0000437 void computeInfo(CGFunctionInfo &FI) const override;
438 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
439 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000440};
441
442class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
443 public:
444 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
445 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
446};
447
448void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
449 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
450
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000451 for (auto &I : FI.arguments())
452 I.info = classifyArgumentType(I.type);
Derek Schuff09338a22012-09-06 17:37:28 +0000453 }
454
455llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
456 CodeGenFunction &CGF) const {
457 return 0;
458}
459
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000460/// \brief Classify argument of given type \p Ty.
461ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000462 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000463 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000464 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000465 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000466 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
467 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000468 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000469 } else if (Ty->isFloatingType()) {
470 // Floating-point types don't go inreg.
471 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000472 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000473
474 return (Ty->isPromotableIntegerType() ?
475 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000476}
477
478ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
479 if (RetTy->isVoidType())
480 return ABIArgInfo::getIgnore();
481
Eli Benderskye20dad62013-04-04 22:49:35 +0000482 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000483 if (isAggregateTypeForABI(RetTy))
484 return ABIArgInfo::getIndirect(0);
485
486 // Treat an enum type as its underlying type.
487 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
488 RetTy = EnumTy->getDecl()->getIntegerType();
489
490 return (RetTy->isPromotableIntegerType() ?
491 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
492}
493
Chad Rosier651c1832013-03-25 21:00:27 +0000494/// IsX86_MMXType - Return true if this is an MMX type.
495bool IsX86_MMXType(llvm::Type *IRType) {
496 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendling5cd41c42010-10-18 03:41:31 +0000497 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
498 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
499 IRType->getScalarSizeInBits() != 64;
500}
501
Jay Foad7c57be32011-07-11 09:56:20 +0000502static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000503 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000504 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000505 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
506 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
507 // Invalid MMX constraint
508 return 0;
509 }
510
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000511 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000512 }
513
514 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000515 return Ty;
516}
517
Chris Lattner0cf24192010-06-28 20:05:43 +0000518//===----------------------------------------------------------------------===//
519// X86-32 ABI Implementation
520//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000521
Reid Kleckner661f35b2014-01-18 01:12:41 +0000522/// \brief Similar to llvm::CCState, but for Clang.
523struct CCState {
524 CCState(unsigned CC) : CC(CC), FreeRegs(0) {}
525
526 unsigned CC;
527 unsigned FreeRegs;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000528 unsigned StackOffset;
529 bool UseInAlloca;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000530};
531
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000532/// X86_32ABIInfo - The X86-32 ABI information.
533class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000534 enum Class {
535 Integer,
536 Float
537 };
538
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000539 static const unsigned MinABIStackAlignInBytes = 4;
540
David Chisnallde3a0692009-08-17 23:08:21 +0000541 bool IsDarwinVectorABI;
542 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000543 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000544 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000545
546 static bool isRegisterSize(unsigned Size) {
547 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
548 }
549
Reid Kleckner4982b822014-01-31 22:54:50 +0000550 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
551 bool IsInstanceMethod) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000552
Daniel Dunbar557893d2010-04-21 19:10:51 +0000553 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
554 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000555 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
556
557 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000558
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000559 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000560 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000561
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000562 Class classify(QualType Ty) const;
Reid Kleckner4982b822014-01-31 22:54:50 +0000563 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State,
564 bool IsInstanceMethod) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000565 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
566 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000567
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000568 /// \brief Rewrite the function info so that all memory arguments use
569 /// inalloca.
570 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
571
572 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
573 unsigned &StackOffset, ABIArgInfo &Info,
574 QualType Type) const;
575
Rafael Espindola75419dc2012-07-23 23:30:29 +0000576public:
577
Craig Topper4f12f102014-03-12 06:41:41 +0000578 void computeInfo(CGFunctionInfo &FI) const override;
579 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
580 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000581
Chad Rosier651c1832013-03-25 21:00:27 +0000582 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000583 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000584 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000585 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000586};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000587
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000588class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
589public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000590 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000591 bool d, bool p, bool w, unsigned r)
592 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000593
John McCall1fe2a8c2013-06-18 02:46:29 +0000594 static bool isStructReturnInRegABI(
595 const llvm::Triple &Triple, const CodeGenOptions &Opts);
596
Charles Davis4ea31ab2010-02-13 15:54:06 +0000597 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000598 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000599
Craig Topper4f12f102014-03-12 06:41:41 +0000600 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000601 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000602 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000603 return 4;
604 }
605
606 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000607 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000608
Jay Foad7c57be32011-07-11 09:56:20 +0000609 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000610 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000611 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000612 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
613 }
614
Craig Topper4f12f102014-03-12 06:41:41 +0000615 llvm::Constant *
616 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000617 unsigned Sig = (0xeb << 0) | // jmp rel8
618 (0x06 << 8) | // .+0x08
619 ('F' << 16) |
620 ('T' << 24);
621 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
622 }
623
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000624};
625
626}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000627
628/// shouldReturnTypeInRegister - Determine if the given type should be
629/// passed in a register (for the Darwin ABI).
Reid Kleckner4982b822014-01-31 22:54:50 +0000630bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
631 bool IsInstanceMethod) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000632 uint64_t Size = Context.getTypeSize(Ty);
633
634 // Type must be register sized.
635 if (!isRegisterSize(Size))
636 return false;
637
638 if (Ty->isVectorType()) {
639 // 64- and 128- bit vectors inside structures are not returned in
640 // registers.
641 if (Size == 64 || Size == 128)
642 return false;
643
644 return true;
645 }
646
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000647 // If this is a builtin, pointer, enum, complex type, member pointer, or
648 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000649 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000650 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000651 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000652 return true;
653
654 // Arrays are treated like records.
655 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman3c424412012-02-22 03:04:13 +0000656 return shouldReturnTypeInRegister(AT->getElementType(), Context,
Reid Kleckner4982b822014-01-31 22:54:50 +0000657 IsInstanceMethod);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000658
659 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000660 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000661 if (!RT) return false;
662
Anders Carlsson40446e82010-01-27 03:25:19 +0000663 // FIXME: Traverse bases here too.
664
Aaron Ballman3c424412012-02-22 03:04:13 +0000665 // For thiscall conventions, structures will never be returned in
666 // a register. This is for compatibility with the MSVC ABI
Reid Kleckner4982b822014-01-31 22:54:50 +0000667 if (IsWin32StructABI && IsInstanceMethod && RT->isStructureType())
Aaron Ballman3c424412012-02-22 03:04:13 +0000668 return false;
Aaron Ballman3c424412012-02-22 03:04:13 +0000669
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000670 // Structure types are passed in register if all fields would be
671 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000672 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000673 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000674 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000675 continue;
676
677 // Check fields recursively.
Reid Kleckner4982b822014-01-31 22:54:50 +0000678 if (!shouldReturnTypeInRegister(FD->getType(), Context, IsInstanceMethod))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000679 return false;
680 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000681 return true;
682}
683
Reid Kleckner661f35b2014-01-18 01:12:41 +0000684ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
685 // If the return value is indirect, then the hidden argument is consuming one
686 // integer register.
687 if (State.FreeRegs) {
688 --State.FreeRegs;
689 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
690 }
691 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
692}
693
Reid Kleckner4982b822014-01-31 22:54:50 +0000694ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State,
695 bool IsInstanceMethod) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000696 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000697 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000698
Chris Lattner458b2aa2010-07-29 02:16:43 +0000699 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000700 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000701 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000702 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000703
704 // 128-bit vectors are a special case; they are returned in
705 // registers and we need to make sure to pick a type the LLVM
706 // backend will like.
707 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000708 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000709 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000710
711 // Always return in register if it fits in a general purpose
712 // register, or if it is 64 bits and has a single element.
713 if ((Size == 8 || Size == 16 || Size == 32) ||
714 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000715 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000716 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000717
Reid Kleckner661f35b2014-01-18 01:12:41 +0000718 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000719 }
720
721 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000722 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000723
John McCalla1dee5302010-08-22 10:59:02 +0000724 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000725 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Mark Lacey3825e832013-10-06 01:33:34 +0000726 if (isRecordReturnIndirect(RT, getCXXABI()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000727 return getIndirectReturnResult(State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000728
Anders Carlsson5789c492009-10-20 22:07:59 +0000729 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000730 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000731 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000732 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000733
David Chisnallde3a0692009-08-17 23:08:21 +0000734 // If specified, structs and unions are always indirect.
735 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000736 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000737
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000738 // Small structures which are register sized are generally returned
739 // in a register.
Reid Kleckner4982b822014-01-31 22:54:50 +0000740 if (shouldReturnTypeInRegister(RetTy, getContext(), IsInstanceMethod)) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000741 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000742
743 // As a special-case, if the struct is a "single-element" struct, and
744 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000745 // floating-point register. (MSVC does not apply this special case.)
746 // We apply a similar transformation for pointer types to improve the
747 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000748 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000749 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000750 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000751 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
752
753 // FIXME: We should be able to narrow this integer in cases with dead
754 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000755 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000756 }
757
Reid Kleckner661f35b2014-01-18 01:12:41 +0000758 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000759 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000760
Chris Lattner458b2aa2010-07-29 02:16:43 +0000761 // Treat an enum type as its underlying type.
762 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
763 RetTy = EnumTy->getDecl()->getIntegerType();
764
765 return (RetTy->isPromotableIntegerType() ?
766 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000767}
768
Eli Friedman7919bea2012-06-05 19:40:46 +0000769static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
770 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
771}
772
Daniel Dunbared23de32010-09-16 20:42:00 +0000773static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
774 const RecordType *RT = Ty->getAs<RecordType>();
775 if (!RT)
776 return 0;
777 const RecordDecl *RD = RT->getDecl();
778
779 // If this is a C++ record, check the bases first.
780 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000781 for (const auto &I : CXXRD->bases())
782 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000783 return false;
784
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000785 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000786 QualType FT = i->getType();
787
Eli Friedman7919bea2012-06-05 19:40:46 +0000788 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000789 return true;
790
791 if (isRecordWithSSEVectorType(Context, FT))
792 return true;
793 }
794
795 return false;
796}
797
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000798unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
799 unsigned Align) const {
800 // Otherwise, if the alignment is less than or equal to the minimum ABI
801 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000802 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000803 return 0; // Use default alignment.
804
805 // On non-Darwin, the stack type alignment is always 4.
806 if (!IsDarwinVectorABI) {
807 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000808 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000809 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000810
Daniel Dunbared23de32010-09-16 20:42:00 +0000811 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000812 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
813 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000814 return 16;
815
816 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000817}
818
Rafael Espindola703c47f2012-10-19 05:04:37 +0000819ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000820 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000821 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000822 if (State.FreeRegs) {
823 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000824 return ABIArgInfo::getIndirectInReg(0, false);
825 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000826 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000827 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000828
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000829 // Compute the byval alignment.
830 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
831 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
832 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000833 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000834
835 // If the stack alignment is less than the type alignment, realign the
836 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000837 bool Realign = TypeAlign > StackAlign;
838 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000839}
840
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000841X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
842 const Type *T = isSingleElementStruct(Ty, getContext());
843 if (!T)
844 T = Ty.getTypePtr();
845
846 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
847 BuiltinType::Kind K = BT->getKind();
848 if (K == BuiltinType::Float || K == BuiltinType::Double)
849 return Float;
850 }
851 return Integer;
852}
853
Reid Kleckner661f35b2014-01-18 01:12:41 +0000854bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
855 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000856 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000857 Class C = classify(Ty);
858 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000859 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000860
Rafael Espindola077dd592012-10-24 01:58:58 +0000861 unsigned Size = getContext().getTypeSize(Ty);
862 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000863
864 if (SizeInRegs == 0)
865 return false;
866
Reid Kleckner661f35b2014-01-18 01:12:41 +0000867 if (SizeInRegs > State.FreeRegs) {
868 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000869 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000870 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000871
Reid Kleckner661f35b2014-01-18 01:12:41 +0000872 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000873
Reid Kleckner661f35b2014-01-18 01:12:41 +0000874 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000875 if (Size > 32)
876 return false;
877
878 if (Ty->isIntegralOrEnumerationType())
879 return true;
880
881 if (Ty->isPointerType())
882 return true;
883
884 if (Ty->isReferenceType())
885 return true;
886
Reid Kleckner661f35b2014-01-18 01:12:41 +0000887 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000888 NeedsPadding = true;
889
Rafael Espindola077dd592012-10-24 01:58:58 +0000890 return false;
891 }
892
Rafael Espindola703c47f2012-10-19 05:04:37 +0000893 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000894}
895
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000896ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
897 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000898 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000899 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000900 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000901 // Check with the C++ ABI first.
902 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
903 if (RAA == CGCXXABI::RAA_Indirect) {
904 return getIndirectResult(Ty, false, State);
905 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
906 // The field index doesn't matter, we'll fix it up later.
907 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
908 }
909
910 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000911 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000912 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000913
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000914 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000915 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000916 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +0000917 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000918
Eli Friedman9f061a32011-11-18 00:28:11 +0000919 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000920 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000921 return ABIArgInfo::getIgnore();
922
Rafael Espindolafad28de2012-10-24 01:59:00 +0000923 llvm::LLVMContext &LLVMContext = getVMContext();
924 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
925 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000926 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000927 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000928 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000929 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
930 return ABIArgInfo::getDirectInReg(Result);
931 }
Rafael Espindolafad28de2012-10-24 01:59:00 +0000932 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000933
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000934 // Expand small (<= 128-bit) record types when we know that the stack layout
935 // of those arguments will match the struct. This is important because the
936 // LLVM backend isn't smart enough to remove byval, which inhibits many
937 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +0000938 if (getContext().getTypeSize(Ty) <= 4*32 &&
939 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000940 return ABIArgInfo::getExpandWithPadding(
941 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000942
Reid Kleckner661f35b2014-01-18 01:12:41 +0000943 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000944 }
945
Chris Lattnerd774ae92010-08-26 20:05:13 +0000946 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +0000947 // On Darwin, some vectors are passed in memory, we handle this by passing
948 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +0000949 if (IsDarwinVectorABI) {
950 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +0000951 if ((Size == 8 || Size == 16 || Size == 32) ||
952 (Size == 64 && VT->getNumElements() == 1))
953 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
954 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +0000955 }
Bill Wendling5cd41c42010-10-18 03:41:31 +0000956
Chad Rosier651c1832013-03-25 21:00:27 +0000957 if (IsX86_MMXType(CGT.ConvertType(Ty)))
958 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000959
Chris Lattnerd774ae92010-08-26 20:05:13 +0000960 return ABIArgInfo::getDirect();
961 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000962
963
Chris Lattner458b2aa2010-07-29 02:16:43 +0000964 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
965 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000966
Rafael Espindolafad28de2012-10-24 01:59:00 +0000967 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000968 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000969
970 if (Ty->isPromotableIntegerType()) {
971 if (InReg)
972 return ABIArgInfo::getExtendInReg();
973 return ABIArgInfo::getExtend();
974 }
975 if (InReg)
976 return ABIArgInfo::getDirectInReg();
977 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000978}
979
Rafael Espindolaa6472962012-07-24 00:01:07 +0000980void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000981 CCState State(FI.getCallingConvention());
982 if (State.CC == llvm::CallingConv::X86_FastCall)
983 State.FreeRegs = 2;
Rafael Espindola077dd592012-10-24 01:58:58 +0000984 else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000985 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +0000986 else
Reid Kleckner661f35b2014-01-18 01:12:41 +0000987 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000988
Reid Kleckner4982b822014-01-31 22:54:50 +0000989 FI.getReturnInfo() =
990 classifyReturnType(FI.getReturnType(), State, FI.isInstanceMethod());
991
992 // On win32, use the x86_cdeclmethodcc convention for cdecl methods that use
993 // sret. This convention swaps the order of the first two parameters behind
994 // the scenes to match MSVC.
995 if (IsWin32StructABI && FI.isInstanceMethod() &&
996 FI.getCallingConvention() == llvm::CallingConv::C &&
997 FI.getReturnInfo().isIndirect())
998 FI.setEffectiveCallingConvention(llvm::CallingConv::X86_CDeclMethod);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000999
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001000 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001001 for (auto &I : FI.arguments()) {
1002 I.info = classifyArgumentType(I.type, State);
1003 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001004 }
1005
1006 // If we needed to use inalloca for any argument, do a second pass and rewrite
1007 // all the memory arguments to use inalloca.
1008 if (UsedInAlloca)
1009 rewriteWithInAlloca(FI);
1010}
1011
1012void
1013X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1014 unsigned &StackOffset,
1015 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001016 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1017 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1018 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1019 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1020
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001021 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1022 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001023 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001024 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001025 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001026 unsigned NumBytes = StackOffset - OldOffset;
1027 assert(NumBytes);
1028 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1029 Ty = llvm::ArrayType::get(Ty, NumBytes);
1030 FrameFields.push_back(Ty);
1031 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001032}
1033
1034void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1035 assert(IsWin32StructABI && "inalloca only supported on win32");
1036
1037 // Build a packed struct type for all of the arguments in memory.
1038 SmallVector<llvm::Type *, 6> FrameFields;
1039
1040 unsigned StackOffset = 0;
1041
1042 // Put the sret parameter into the inalloca struct if it's in memory.
1043 ABIArgInfo &Ret = FI.getReturnInfo();
1044 if (Ret.isIndirect() && !Ret.getInReg()) {
1045 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1046 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001047 // On Windows, the hidden sret parameter is always returned in eax.
1048 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001049 }
1050
1051 // Skip the 'this' parameter in ecx.
1052 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1053 if (FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall)
1054 ++I;
1055
1056 // Put arguments passed in memory into the struct.
1057 for (; I != E; ++I) {
1058
1059 // Leave ignored and inreg arguments alone.
1060 switch (I->info.getKind()) {
1061 case ABIArgInfo::Indirect:
1062 assert(I->info.getIndirectByVal());
1063 break;
1064 case ABIArgInfo::Ignore:
1065 continue;
1066 case ABIArgInfo::Direct:
1067 case ABIArgInfo::Extend:
1068 if (I->info.getInReg())
1069 continue;
1070 break;
1071 default:
1072 break;
1073 }
1074
1075 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1076 }
1077
1078 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1079 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001080}
1081
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001082llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1083 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001084 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001085
1086 CGBuilderTy &Builder = CGF.Builder;
1087 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1088 "ap");
1089 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001090
1091 // Compute if the address needs to be aligned
1092 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1093 Align = getTypeStackAlignInBytes(Ty, Align);
1094 Align = std::max(Align, 4U);
1095 if (Align > 4) {
1096 // addr = (addr + align - 1) & -align;
1097 llvm::Value *Offset =
1098 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1099 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1100 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1101 CGF.Int32Ty);
1102 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1103 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1104 Addr->getType(),
1105 "ap.cur.aligned");
1106 }
1107
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001108 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001109 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001110 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1111
1112 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001113 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001114 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001115 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001116 "ap.next");
1117 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1118
1119 return AddrTyped;
1120}
1121
Charles Davis4ea31ab2010-02-13 15:54:06 +00001122void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1123 llvm::GlobalValue *GV,
1124 CodeGen::CodeGenModule &CGM) const {
1125 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1126 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1127 // Get the LLVM function.
1128 llvm::Function *Fn = cast<llvm::Function>(GV);
1129
1130 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001131 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001132 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001133 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1134 llvm::AttributeSet::get(CGM.getLLVMContext(),
1135 llvm::AttributeSet::FunctionIndex,
1136 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001137 }
1138 }
1139}
1140
John McCallbeec5a02010-03-06 00:35:14 +00001141bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1142 CodeGen::CodeGenFunction &CGF,
1143 llvm::Value *Address) const {
1144 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001145
Chris Lattnerece04092012-02-07 00:39:47 +00001146 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001147
John McCallbeec5a02010-03-06 00:35:14 +00001148 // 0-7 are the eight integer registers; the order is different
1149 // on Darwin (for EH), but the range is the same.
1150 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001151 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001152
John McCallc8e01702013-04-16 22:48:15 +00001153 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001154 // 12-16 are st(0..4). Not sure why we stop at 4.
1155 // These have size 16, which is sizeof(long double) on
1156 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001157 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001158 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001159
John McCallbeec5a02010-03-06 00:35:14 +00001160 } else {
1161 // 9 is %eflags, which doesn't get a size on Darwin for some
1162 // reason.
1163 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1164
1165 // 11-16 are st(0..5). Not sure why we stop at 5.
1166 // These have size 12, which is sizeof(long double) on
1167 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001168 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001169 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1170 }
John McCallbeec5a02010-03-06 00:35:14 +00001171
1172 return false;
1173}
1174
Chris Lattner0cf24192010-06-28 20:05:43 +00001175//===----------------------------------------------------------------------===//
1176// X86-64 ABI Implementation
1177//===----------------------------------------------------------------------===//
1178
1179
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001180namespace {
1181/// X86_64ABIInfo - The X86_64 ABI information.
1182class X86_64ABIInfo : public ABIInfo {
1183 enum Class {
1184 Integer = 0,
1185 SSE,
1186 SSEUp,
1187 X87,
1188 X87Up,
1189 ComplexX87,
1190 NoClass,
1191 Memory
1192 };
1193
1194 /// merge - Implement the X86_64 ABI merging algorithm.
1195 ///
1196 /// Merge an accumulating classification \arg Accum with a field
1197 /// classification \arg Field.
1198 ///
1199 /// \param Accum - The accumulating classification. This should
1200 /// always be either NoClass or the result of a previous merge
1201 /// call. In addition, this should never be Memory (the caller
1202 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001203 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001204
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001205 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1206 ///
1207 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1208 /// final MEMORY or SSE classes when necessary.
1209 ///
1210 /// \param AggregateSize - The size of the current aggregate in
1211 /// the classification process.
1212 ///
1213 /// \param Lo - The classification for the parts of the type
1214 /// residing in the low word of the containing object.
1215 ///
1216 /// \param Hi - The classification for the parts of the type
1217 /// residing in the higher words of the containing object.
1218 ///
1219 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1220
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001221 /// classify - Determine the x86_64 register classes in which the
1222 /// given type T should be passed.
1223 ///
1224 /// \param Lo - The classification for the parts of the type
1225 /// residing in the low word of the containing object.
1226 ///
1227 /// \param Hi - The classification for the parts of the type
1228 /// residing in the high word of the containing object.
1229 ///
1230 /// \param OffsetBase - The bit offset of this type in the
1231 /// containing object. Some parameters are classified different
1232 /// depending on whether they straddle an eightbyte boundary.
1233 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001234 /// \param isNamedArg - Whether the argument in question is a "named"
1235 /// argument, as used in AMD64-ABI 3.5.7.
1236 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001237 /// If a word is unused its result will be NoClass; if a type should
1238 /// be passed in Memory then at least the classification of \arg Lo
1239 /// will be Memory.
1240 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001241 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001242 ///
1243 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1244 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001245 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1246 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001247
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001248 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001249 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1250 unsigned IROffset, QualType SourceTy,
1251 unsigned SourceOffset) const;
1252 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1253 unsigned IROffset, QualType SourceTy,
1254 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001255
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001256 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001257 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001258 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001259
1260 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001261 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001262 ///
1263 /// \param freeIntRegs - The number of free integer registers remaining
1264 /// available.
1265 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001266
Chris Lattner458b2aa2010-07-29 02:16:43 +00001267 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001268
Bill Wendling5cd41c42010-10-18 03:41:31 +00001269 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001270 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001271 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001272 unsigned &neededSSE,
1273 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001274
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001275 bool IsIllegalVectorType(QualType Ty) const;
1276
John McCalle0fda732011-04-21 01:20:55 +00001277 /// The 0.98 ABI revision clarified a lot of ambiguities,
1278 /// unfortunately in ways that were not always consistent with
1279 /// certain previous compilers. In particular, platforms which
1280 /// required strict binary compatibility with older versions of GCC
1281 /// may need to exempt themselves.
1282 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001283 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001284 }
1285
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001286 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001287 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1288 // 64-bit hardware.
1289 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001290
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001291public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001292 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001293 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001294 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001295 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001296
John McCalla729c622012-02-17 03:33:10 +00001297 bool isPassedUsingAVXType(QualType type) const {
1298 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001299 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001300 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1301 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001302 if (info.isDirect()) {
1303 llvm::Type *ty = info.getCoerceToType();
1304 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1305 return (vectorTy->getBitWidth() > 128);
1306 }
1307 return false;
1308 }
1309
Craig Topper4f12f102014-03-12 06:41:41 +00001310 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001311
Craig Topper4f12f102014-03-12 06:41:41 +00001312 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1313 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001314};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001315
Chris Lattner04dc9572010-08-31 16:44:54 +00001316/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001317class WinX86_64ABIInfo : public ABIInfo {
1318
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001319 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001320
Chris Lattner04dc9572010-08-31 16:44:54 +00001321public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001322 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1323
Craig Topper4f12f102014-03-12 06:41:41 +00001324 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001325
Craig Topper4f12f102014-03-12 06:41:41 +00001326 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1327 CodeGenFunction &CGF) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001328};
1329
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001330class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1331public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001332 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffc7dd7222012-10-11 15:52:22 +00001333 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001334
John McCalla729c622012-02-17 03:33:10 +00001335 const X86_64ABIInfo &getABIInfo() const {
1336 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1337 }
1338
Craig Topper4f12f102014-03-12 06:41:41 +00001339 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001340 return 7;
1341 }
1342
1343 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001344 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001345 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001346
John McCall943fae92010-05-27 06:19:26 +00001347 // 0-15 are the 16 integer registers.
1348 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001349 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001350 return false;
1351 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001352
Jay Foad7c57be32011-07-11 09:56:20 +00001353 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001354 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001355 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001356 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1357 }
1358
John McCalla729c622012-02-17 03:33:10 +00001359 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001360 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001361 // The default CC on x86-64 sets %al to the number of SSA
1362 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001363 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001364 // that when AVX types are involved: the ABI explicitly states it is
1365 // undefined, and it doesn't work in practice because of how the ABI
1366 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001367 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001368 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001369 for (CallArgList::const_iterator
1370 it = args.begin(), ie = args.end(); it != ie; ++it) {
1371 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1372 HasAVXType = true;
1373 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001374 }
1375 }
John McCalla729c622012-02-17 03:33:10 +00001376
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001377 if (!HasAVXType)
1378 return true;
1379 }
John McCallcbc038a2011-09-21 08:08:30 +00001380
John McCalla729c622012-02-17 03:33:10 +00001381 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001382 }
1383
Craig Topper4f12f102014-03-12 06:41:41 +00001384 llvm::Constant *
1385 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001386 unsigned Sig = (0xeb << 0) | // jmp rel8
1387 (0x0a << 8) | // .+0x0c
1388 ('F' << 16) |
1389 ('T' << 24);
1390 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1391 }
1392
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001393};
1394
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001395static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1396 // If the argument does not end in .lib, automatically add the suffix. This
1397 // matches the behavior of MSVC.
1398 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001399 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001400 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001401 return ArgStr;
1402}
1403
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001404class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1405public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001406 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1407 bool d, bool p, bool w, unsigned RegParms)
1408 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001409
1410 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001411 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001412 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001413 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001414 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001415
1416 void getDetectMismatchOption(llvm::StringRef Name,
1417 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001418 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001419 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001420 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001421};
1422
Chris Lattner04dc9572010-08-31 16:44:54 +00001423class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1424public:
1425 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1426 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1427
Craig Topper4f12f102014-03-12 06:41:41 +00001428 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001429 return 7;
1430 }
1431
1432 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001433 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001434 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001435
Chris Lattner04dc9572010-08-31 16:44:54 +00001436 // 0-15 are the 16 integer registers.
1437 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001438 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001439 return false;
1440 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001441
1442 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001443 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001444 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001445 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001446 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001447
1448 void getDetectMismatchOption(llvm::StringRef Name,
1449 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001450 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001451 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001452 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001453};
1454
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001455}
1456
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001457void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1458 Class &Hi) const {
1459 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1460 //
1461 // (a) If one of the classes is Memory, the whole argument is passed in
1462 // memory.
1463 //
1464 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1465 // memory.
1466 //
1467 // (c) If the size of the aggregate exceeds two eightbytes and the first
1468 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1469 // argument is passed in memory. NOTE: This is necessary to keep the
1470 // ABI working for processors that don't support the __m256 type.
1471 //
1472 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1473 //
1474 // Some of these are enforced by the merging logic. Others can arise
1475 // only with unions; for example:
1476 // union { _Complex double; unsigned; }
1477 //
1478 // Note that clauses (b) and (c) were added in 0.98.
1479 //
1480 if (Hi == Memory)
1481 Lo = Memory;
1482 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1483 Lo = Memory;
1484 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1485 Lo = Memory;
1486 if (Hi == SSEUp && Lo != SSE)
1487 Hi = SSE;
1488}
1489
Chris Lattnerd776fb12010-06-28 21:43:59 +00001490X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001491 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1492 // classified recursively so that always two fields are
1493 // considered. The resulting class is calculated according to
1494 // the classes of the fields in the eightbyte:
1495 //
1496 // (a) If both classes are equal, this is the resulting class.
1497 //
1498 // (b) If one of the classes is NO_CLASS, the resulting class is
1499 // the other class.
1500 //
1501 // (c) If one of the classes is MEMORY, the result is the MEMORY
1502 // class.
1503 //
1504 // (d) If one of the classes is INTEGER, the result is the
1505 // INTEGER.
1506 //
1507 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1508 // MEMORY is used as class.
1509 //
1510 // (f) Otherwise class SSE is used.
1511
1512 // Accum should never be memory (we should have returned) or
1513 // ComplexX87 (because this cannot be passed in a structure).
1514 assert((Accum != Memory && Accum != ComplexX87) &&
1515 "Invalid accumulated classification during merge.");
1516 if (Accum == Field || Field == NoClass)
1517 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001518 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001519 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001520 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001521 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001522 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001523 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001524 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1525 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001526 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001527 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001528}
1529
Chris Lattner5c740f12010-06-30 19:14:05 +00001530void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001531 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001532 // FIXME: This code can be simplified by introducing a simple value class for
1533 // Class pairs with appropriate constructor methods for the various
1534 // situations.
1535
1536 // FIXME: Some of the split computations are wrong; unaligned vectors
1537 // shouldn't be passed in registers for example, so there is no chance they
1538 // can straddle an eightbyte. Verify & simplify.
1539
1540 Lo = Hi = NoClass;
1541
1542 Class &Current = OffsetBase < 64 ? Lo : Hi;
1543 Current = Memory;
1544
John McCall9dd450b2009-09-21 23:43:11 +00001545 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001546 BuiltinType::Kind k = BT->getKind();
1547
1548 if (k == BuiltinType::Void) {
1549 Current = NoClass;
1550 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1551 Lo = Integer;
1552 Hi = Integer;
1553 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1554 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001555 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1556 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001557 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001558 Current = SSE;
1559 } else if (k == BuiltinType::LongDouble) {
1560 Lo = X87;
1561 Hi = X87Up;
1562 }
1563 // FIXME: _Decimal32 and _Decimal64 are SSE.
1564 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001565 return;
1566 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001567
Chris Lattnerd776fb12010-06-28 21:43:59 +00001568 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001569 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001570 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001571 return;
1572 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001573
Chris Lattnerd776fb12010-06-28 21:43:59 +00001574 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001575 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001576 return;
1577 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001578
Chris Lattnerd776fb12010-06-28 21:43:59 +00001579 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001580 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001581 Lo = Hi = Integer;
1582 else
1583 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001584 return;
1585 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001586
Chris Lattnerd776fb12010-06-28 21:43:59 +00001587 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001588 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001589 if (Size == 32) {
1590 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1591 // float> as integer.
1592 Current = Integer;
1593
1594 // If this type crosses an eightbyte boundary, it should be
1595 // split.
1596 uint64_t EB_Real = (OffsetBase) / 64;
1597 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1598 if (EB_Real != EB_Imag)
1599 Hi = Lo;
1600 } else if (Size == 64) {
1601 // gcc passes <1 x double> in memory. :(
1602 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1603 return;
1604
1605 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001606 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001607 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1608 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1609 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001610 Current = Integer;
1611 else
1612 Current = SSE;
1613
1614 // If this type crosses an eightbyte boundary, it should be
1615 // split.
1616 if (OffsetBase && OffsetBase != 64)
1617 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001618 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001619 // Arguments of 256-bits are split into four eightbyte chunks. The
1620 // least significant one belongs to class SSE and all the others to class
1621 // SSEUP. The original Lo and Hi design considers that types can't be
1622 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1623 // This design isn't correct for 256-bits, but since there're no cases
1624 // where the upper parts would need to be inspected, avoid adding
1625 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001626 //
1627 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1628 // registers if they are "named", i.e. not part of the "..." of a
1629 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001630 Lo = SSE;
1631 Hi = SSEUp;
1632 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001633 return;
1634 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001635
Chris Lattnerd776fb12010-06-28 21:43:59 +00001636 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001637 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001638
Chris Lattner2b037972010-07-29 02:01:43 +00001639 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001640 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001641 if (Size <= 64)
1642 Current = Integer;
1643 else if (Size <= 128)
1644 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001645 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001646 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001647 else if (ET == getContext().DoubleTy ||
1648 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001649 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001650 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001651 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001652 Current = ComplexX87;
1653
1654 // If this complex type crosses an eightbyte boundary then it
1655 // should be split.
1656 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001657 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001658 if (Hi == NoClass && EB_Real != EB_Imag)
1659 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001660
Chris Lattnerd776fb12010-06-28 21:43:59 +00001661 return;
1662 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001663
Chris Lattner2b037972010-07-29 02:01:43 +00001664 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001665 // Arrays are treated like structures.
1666
Chris Lattner2b037972010-07-29 02:01:43 +00001667 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001668
1669 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001670 // than four eightbytes, ..., it has class MEMORY.
1671 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001672 return;
1673
1674 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1675 // fields, it has class MEMORY.
1676 //
1677 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001678 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001679 return;
1680
1681 // Otherwise implement simplified merge. We could be smarter about
1682 // this, but it isn't worth it and would be harder to verify.
1683 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001684 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001685 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001686
1687 // The only case a 256-bit wide vector could be used is when the array
1688 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1689 // to work for sizes wider than 128, early check and fallback to memory.
1690 if (Size > 128 && EltSize != 256)
1691 return;
1692
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001693 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1694 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001695 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001696 Lo = merge(Lo, FieldLo);
1697 Hi = merge(Hi, FieldHi);
1698 if (Lo == Memory || Hi == Memory)
1699 break;
1700 }
1701
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001702 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001703 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001704 return;
1705 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001706
Chris Lattnerd776fb12010-06-28 21:43:59 +00001707 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001708 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001709
1710 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001711 // than four eightbytes, ..., it has class MEMORY.
1712 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001713 return;
1714
Anders Carlsson20759ad2009-09-16 15:53:40 +00001715 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1716 // copy constructor or a non-trivial destructor, it is passed by invisible
1717 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001718 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001719 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001720
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001721 const RecordDecl *RD = RT->getDecl();
1722
1723 // Assume variable sized types are passed in memory.
1724 if (RD->hasFlexibleArrayMember())
1725 return;
1726
Chris Lattner2b037972010-07-29 02:01:43 +00001727 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001728
1729 // Reset Lo class, this will be recomputed.
1730 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001731
1732 // If this is a C++ record, classify the bases first.
1733 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001734 for (const auto &I : CXXRD->bases()) {
1735 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001736 "Unexpected base class!");
1737 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001738 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001739
1740 // Classify this field.
1741 //
1742 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1743 // single eightbyte, each is classified separately. Each eightbyte gets
1744 // initialized to class NO_CLASS.
1745 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001746 uint64_t Offset =
1747 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001748 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001749 Lo = merge(Lo, FieldLo);
1750 Hi = merge(Hi, FieldHi);
1751 if (Lo == Memory || Hi == Memory)
1752 break;
1753 }
1754 }
1755
1756 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001757 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001758 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001759 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001760 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1761 bool BitField = i->isBitField();
1762
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001763 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1764 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001765 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001766 // The only case a 256-bit wide vector could be used is when the struct
1767 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1768 // to work for sizes wider than 128, early check and fallback to memory.
1769 //
1770 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1771 Lo = Memory;
1772 return;
1773 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001774 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001775 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001776 Lo = Memory;
1777 return;
1778 }
1779
1780 // Classify this field.
1781 //
1782 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1783 // exceeds a single eightbyte, each is classified
1784 // separately. Each eightbyte gets initialized to class
1785 // NO_CLASS.
1786 Class FieldLo, FieldHi;
1787
1788 // Bit-fields require special handling, they do not force the
1789 // structure to be passed in memory even if unaligned, and
1790 // therefore they can straddle an eightbyte.
1791 if (BitField) {
1792 // Ignore padding bit-fields.
1793 if (i->isUnnamedBitfield())
1794 continue;
1795
1796 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001797 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001798
1799 uint64_t EB_Lo = Offset / 64;
1800 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001801
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001802 if (EB_Lo) {
1803 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1804 FieldLo = NoClass;
1805 FieldHi = Integer;
1806 } else {
1807 FieldLo = Integer;
1808 FieldHi = EB_Hi ? Integer : NoClass;
1809 }
1810 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001811 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001812 Lo = merge(Lo, FieldLo);
1813 Hi = merge(Hi, FieldHi);
1814 if (Lo == Memory || Hi == Memory)
1815 break;
1816 }
1817
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001818 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001819 }
1820}
1821
Chris Lattner22a931e2010-06-29 06:01:59 +00001822ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001823 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1824 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001825 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001826 // Treat an enum type as its underlying type.
1827 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1828 Ty = EnumTy->getDecl()->getIntegerType();
1829
1830 return (Ty->isPromotableIntegerType() ?
1831 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1832 }
1833
1834 return ABIArgInfo::getIndirect(0);
1835}
1836
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001837bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1838 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1839 uint64_t Size = getContext().getTypeSize(VecTy);
1840 unsigned LargestVector = HasAVX ? 256 : 128;
1841 if (Size <= 64 || Size > LargestVector)
1842 return true;
1843 }
1844
1845 return false;
1846}
1847
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001848ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1849 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001850 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1851 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001852 //
1853 // This assumption is optimistic, as there could be free registers available
1854 // when we need to pass this argument in memory, and LLVM could try to pass
1855 // the argument in the free register. This does not seem to happen currently,
1856 // but this code would be much safer if we could mark the argument with
1857 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001858 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001859 // Treat an enum type as its underlying type.
1860 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1861 Ty = EnumTy->getDecl()->getIntegerType();
1862
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001863 return (Ty->isPromotableIntegerType() ?
1864 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001865 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001866
Mark Lacey3825e832013-10-06 01:33:34 +00001867 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001868 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001869
Chris Lattner44c2b902011-05-22 23:21:23 +00001870 // Compute the byval alignment. We specify the alignment of the byval in all
1871 // cases so that the mid-level optimizer knows the alignment of the byval.
1872 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001873
1874 // Attempt to avoid passing indirect results using byval when possible. This
1875 // is important for good codegen.
1876 //
1877 // We do this by coercing the value into a scalar type which the backend can
1878 // handle naturally (i.e., without using byval).
1879 //
1880 // For simplicity, we currently only do this when we have exhausted all of the
1881 // free integer registers. Doing this when there are free integer registers
1882 // would require more care, as we would have to ensure that the coerced value
1883 // did not claim the unused register. That would require either reording the
1884 // arguments to the function (so that any subsequent inreg values came first),
1885 // or only doing this optimization when there were no following arguments that
1886 // might be inreg.
1887 //
1888 // We currently expect it to be rare (particularly in well written code) for
1889 // arguments to be passed on the stack when there are still free integer
1890 // registers available (this would typically imply large structs being passed
1891 // by value), so this seems like a fair tradeoff for now.
1892 //
1893 // We can revisit this if the backend grows support for 'onstack' parameter
1894 // attributes. See PR12193.
1895 if (freeIntRegs == 0) {
1896 uint64_t Size = getContext().getTypeSize(Ty);
1897
1898 // If this type fits in an eightbyte, coerce it into the matching integral
1899 // type, which will end up on the stack (with alignment 8).
1900 if (Align == 8 && Size <= 64)
1901 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1902 Size));
1903 }
1904
Chris Lattner44c2b902011-05-22 23:21:23 +00001905 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001906}
1907
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001908/// GetByteVectorType - The ABI specifies that a value should be passed in an
1909/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00001910/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001911llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001912 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001913
Chris Lattner9fa15c32010-07-29 05:02:29 +00001914 // Wrapper structs that just contain vectors are passed just like vectors,
1915 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001916 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00001917 while (STy && STy->getNumElements() == 1) {
1918 IRType = STy->getElementType(0);
1919 STy = dyn_cast<llvm::StructType>(IRType);
1920 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001921
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00001922 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001923 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1924 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001925 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00001926 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00001927 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1928 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1929 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1930 EltTy->isIntegerTy(128)))
1931 return VT;
1932 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001933
Chris Lattner4200fe42010-07-29 04:56:46 +00001934 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1935}
1936
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001937/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1938/// is known to either be off the end of the specified type or being in
1939/// alignment padding. The user type specified is known to be at most 128 bits
1940/// in size, and have passed through X86_64ABIInfo::classify with a successful
1941/// classification that put one of the two halves in the INTEGER class.
1942///
1943/// It is conservatively correct to return false.
1944static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1945 unsigned EndBit, ASTContext &Context) {
1946 // If the bytes being queried are off the end of the type, there is no user
1947 // data hiding here. This handles analysis of builtins, vectors and other
1948 // types that don't contain interesting padding.
1949 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1950 if (TySize <= StartBit)
1951 return true;
1952
Chris Lattner98076a22010-07-29 07:43:55 +00001953 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1954 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1955 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1956
1957 // Check each element to see if the element overlaps with the queried range.
1958 for (unsigned i = 0; i != NumElts; ++i) {
1959 // If the element is after the span we care about, then we're done..
1960 unsigned EltOffset = i*EltSize;
1961 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001962
Chris Lattner98076a22010-07-29 07:43:55 +00001963 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1964 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1965 EndBit-EltOffset, Context))
1966 return false;
1967 }
1968 // If it overlaps no elements, then it is safe to process as padding.
1969 return true;
1970 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001971
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001972 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1973 const RecordDecl *RD = RT->getDecl();
1974 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001975
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001976 // If this is a C++ record, check the bases first.
1977 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001978 for (const auto &I : CXXRD->bases()) {
1979 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001980 "Unexpected base class!");
1981 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001982 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001983
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001984 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001985 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001986 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001987
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001988 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00001989 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001990 EndBit-BaseOffset, Context))
1991 return false;
1992 }
1993 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001994
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001995 // Verify that no field has data that overlaps the region of interest. Yes
1996 // this could be sped up a lot by being smarter about queried fields,
1997 // however we're only looking at structs up to 16 bytes, so we don't care
1998 // much.
1999 unsigned idx = 0;
2000 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2001 i != e; ++i, ++idx) {
2002 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002003
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002004 // If we found a field after the region we care about, then we're done.
2005 if (FieldOffset >= EndBit) break;
2006
2007 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2008 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2009 Context))
2010 return false;
2011 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002012
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002013 // If nothing in this record overlapped the area of interest, then we're
2014 // clean.
2015 return true;
2016 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002017
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002018 return false;
2019}
2020
Chris Lattnere556a712010-07-29 18:39:32 +00002021/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2022/// float member at the specified offset. For example, {int,{float}} has a
2023/// float at offset 4. It is conservatively correct for this routine to return
2024/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002025static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002026 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002027 // Base case if we find a float.
2028 if (IROffset == 0 && IRType->isFloatTy())
2029 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002030
Chris Lattnere556a712010-07-29 18:39:32 +00002031 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002032 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002033 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2034 unsigned Elt = SL->getElementContainingOffset(IROffset);
2035 IROffset -= SL->getElementOffset(Elt);
2036 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2037 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002038
Chris Lattnere556a712010-07-29 18:39:32 +00002039 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002040 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2041 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002042 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2043 IROffset -= IROffset/EltSize*EltSize;
2044 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2045 }
2046
2047 return false;
2048}
2049
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002050
2051/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2052/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002053llvm::Type *X86_64ABIInfo::
2054GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002055 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002056 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002057 // pass as float if the last 4 bytes is just padding. This happens for
2058 // structs that contain 3 floats.
2059 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2060 SourceOffset*8+64, getContext()))
2061 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002062
Chris Lattnere556a712010-07-29 18:39:32 +00002063 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2064 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2065 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002066 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2067 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002068 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002069
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002070 return llvm::Type::getDoubleTy(getVMContext());
2071}
2072
2073
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002074/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2075/// an 8-byte GPR. This means that we either have a scalar or we are talking
2076/// about the high or low part of an up-to-16-byte struct. This routine picks
2077/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002078/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2079/// etc).
2080///
2081/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2082/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2083/// the 8-byte value references. PrefType may be null.
2084///
2085/// SourceTy is the source level type for the entire argument. SourceOffset is
2086/// an offset into this that we're processing (which is always either 0 or 8).
2087///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002088llvm::Type *X86_64ABIInfo::
2089GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002090 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002091 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2092 // returning an 8-byte unit starting with it. See if we can safely use it.
2093 if (IROffset == 0) {
2094 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002095 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2096 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002097 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002098
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002099 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2100 // goodness in the source type is just tail padding. This is allowed to
2101 // kick in for struct {double,int} on the int, but not on
2102 // struct{double,int,int} because we wouldn't return the second int. We
2103 // have to do this analysis on the source type because we can't depend on
2104 // unions being lowered a specific way etc.
2105 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002106 IRType->isIntegerTy(32) ||
2107 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2108 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2109 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002110
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002111 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2112 SourceOffset*8+64, getContext()))
2113 return IRType;
2114 }
2115 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002116
Chris Lattner2192fe52011-07-18 04:24:23 +00002117 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002118 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002119 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002120 if (IROffset < SL->getSizeInBytes()) {
2121 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2122 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002123
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002124 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2125 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002126 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002127 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002128
Chris Lattner2192fe52011-07-18 04:24:23 +00002129 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002130 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002131 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002132 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002133 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2134 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002135 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002136
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002137 // Okay, we don't have any better idea of what to pass, so we pass this in an
2138 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002139 unsigned TySizeInBytes =
2140 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002141
Chris Lattner3f763422010-07-29 17:34:39 +00002142 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002143
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002144 // It is always safe to classify this as an integer type up to i64 that
2145 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002146 return llvm::IntegerType::get(getVMContext(),
2147 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002148}
2149
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002150
2151/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2152/// be used as elements of a two register pair to pass or return, return a
2153/// first class aggregate to represent them. For example, if the low part of
2154/// a by-value argument should be passed as i32* and the high part as float,
2155/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002156static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002157GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002158 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002159 // In order to correctly satisfy the ABI, we need to the high part to start
2160 // at offset 8. If the high and low parts we inferred are both 4-byte types
2161 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2162 // the second element at offset 8. Check for this:
2163 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2164 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002165 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002166 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002167
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002168 // To handle this, we have to increase the size of the low part so that the
2169 // second element will start at an 8 byte offset. We can't increase the size
2170 // of the second element because it might make us access off the end of the
2171 // struct.
2172 if (HiStart != 8) {
2173 // There are only two sorts of types the ABI generation code can produce for
2174 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2175 // Promote these to a larger type.
2176 if (Lo->isFloatTy())
2177 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2178 else {
2179 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2180 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2181 }
2182 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002183
Chris Lattnera5f58b02011-07-09 17:41:47 +00002184 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002185
2186
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002187 // Verify that the second element is at an 8-byte offset.
2188 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2189 "Invalid x86-64 argument pair!");
2190 return Result;
2191}
2192
Chris Lattner31faff52010-07-28 23:06:14 +00002193ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002194classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002195 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2196 // classification algorithm.
2197 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002198 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002199
2200 // Check some invariants.
2201 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002202 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2203
Chris Lattnera5f58b02011-07-09 17:41:47 +00002204 llvm::Type *ResType = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002205 switch (Lo) {
2206 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002207 if (Hi == NoClass)
2208 return ABIArgInfo::getIgnore();
2209 // If the low part is just padding, it takes no register, leave ResType
2210 // null.
2211 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2212 "Unknown missing lo part");
2213 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002214
2215 case SSEUp:
2216 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002217 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002218
2219 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2220 // hidden argument.
2221 case Memory:
2222 return getIndirectReturnResult(RetTy);
2223
2224 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2225 // available register of the sequence %rax, %rdx is used.
2226 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002227 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002228
Chris Lattner1f3a0632010-07-29 21:42:50 +00002229 // If we have a sign or zero extended integer, make sure to return Extend
2230 // so that the parameter gets the right LLVM IR attributes.
2231 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2232 // Treat an enum type as its underlying type.
2233 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2234 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002235
Chris Lattner1f3a0632010-07-29 21:42:50 +00002236 if (RetTy->isIntegralOrEnumerationType() &&
2237 RetTy->isPromotableIntegerType())
2238 return ABIArgInfo::getExtend();
2239 }
Chris Lattner31faff52010-07-28 23:06:14 +00002240 break;
2241
2242 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2243 // available SSE register of the sequence %xmm0, %xmm1 is used.
2244 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002245 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002246 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002247
2248 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2249 // returned on the X87 stack in %st0 as 80-bit x87 number.
2250 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002251 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002252 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002253
2254 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2255 // part of the value is returned in %st0 and the imaginary part in
2256 // %st1.
2257 case ComplexX87:
2258 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002259 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002260 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002261 NULL);
2262 break;
2263 }
2264
Chris Lattnera5f58b02011-07-09 17:41:47 +00002265 llvm::Type *HighPart = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002266 switch (Hi) {
2267 // Memory was handled previously and X87 should
2268 // never occur as a hi class.
2269 case Memory:
2270 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002271 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002272
2273 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002274 case NoClass:
2275 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002276
Chris Lattner52b3c132010-09-01 00:20:33 +00002277 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002278 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002279 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2280 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002281 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002282 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002283 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002284 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2285 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002286 break;
2287
2288 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002289 // is passed in the next available eightbyte chunk if the last used
2290 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002291 //
Chris Lattner57540c52011-04-15 05:22:18 +00002292 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002293 case SSEUp:
2294 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002295 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002296 break;
2297
2298 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2299 // returned together with the previous X87 value in %st0.
2300 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002301 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002302 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002303 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002304 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002305 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002306 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002307 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2308 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002309 }
Chris Lattner31faff52010-07-28 23:06:14 +00002310 break;
2311 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002312
Chris Lattner52b3c132010-09-01 00:20:33 +00002313 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002314 // known to pass in the high eightbyte of the result. We do this by forming a
2315 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002316 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002317 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002318
Chris Lattner1f3a0632010-07-29 21:42:50 +00002319 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002320}
2321
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002322ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002323 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2324 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002325 const
2326{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002327 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002328 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002329
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002330 // Check some invariants.
2331 // FIXME: Enforce these by construction.
2332 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002333 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2334
2335 neededInt = 0;
2336 neededSSE = 0;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002337 llvm::Type *ResType = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002338 switch (Lo) {
2339 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002340 if (Hi == NoClass)
2341 return ABIArgInfo::getIgnore();
2342 // If the low part is just padding, it takes no register, leave ResType
2343 // null.
2344 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2345 "Unknown missing lo part");
2346 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002347
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002348 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2349 // on the stack.
2350 case Memory:
2351
2352 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2353 // COMPLEX_X87, it is passed in memory.
2354 case X87:
2355 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002356 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002357 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002358 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002359
2360 case SSEUp:
2361 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002362 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002363
2364 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2365 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2366 // and %r9 is used.
2367 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002368 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002369
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002370 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002371 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002372
2373 // If we have a sign or zero extended integer, make sure to return Extend
2374 // so that the parameter gets the right LLVM IR attributes.
2375 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2376 // Treat an enum type as its underlying type.
2377 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2378 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002379
Chris Lattner1f3a0632010-07-29 21:42:50 +00002380 if (Ty->isIntegralOrEnumerationType() &&
2381 Ty->isPromotableIntegerType())
2382 return ABIArgInfo::getExtend();
2383 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002384
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002385 break;
2386
2387 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2388 // available SSE register is used, the registers are taken in the
2389 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002390 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002391 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002392 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002393 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002394 break;
2395 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002396 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002397
Chris Lattnera5f58b02011-07-09 17:41:47 +00002398 llvm::Type *HighPart = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002399 switch (Hi) {
2400 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002401 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002402 // which is passed in memory.
2403 case Memory:
2404 case X87:
2405 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002406 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002407
2408 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002409
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002410 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002411 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002412 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002413 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002414
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002415 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2416 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002417 break;
2418
2419 // X87Up generally doesn't occur here (long double is passed in
2420 // memory), except in situations involving unions.
2421 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002422 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002423 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002424
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002425 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2426 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002427
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002428 ++neededSSE;
2429 break;
2430
2431 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2432 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002433 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002434 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002435 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002436 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002437 break;
2438 }
2439
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002440 // If a high part was specified, merge it together with the low part. It is
2441 // known to pass in the high eightbyte of the result. We do this by forming a
2442 // first class struct aggregate with the high and low part: {low, high}
2443 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002444 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002445
Chris Lattner1f3a0632010-07-29 21:42:50 +00002446 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002447}
2448
Chris Lattner22326a12010-07-29 02:31:05 +00002449void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002450
Chris Lattner458b2aa2010-07-29 02:16:43 +00002451 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002452
2453 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002454 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002455
2456 // If the return value is indirect, then the hidden argument is consuming one
2457 // integer register.
2458 if (FI.getReturnInfo().isIndirect())
2459 --freeIntRegs;
2460
Eli Friedman96fd2642013-06-12 00:13:45 +00002461 bool isVariadic = FI.isVariadic();
2462 unsigned numRequiredArgs = 0;
2463 if (isVariadic)
2464 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2465
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002466 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2467 // get assigned (in left-to-right order) for passing as follows...
2468 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2469 it != ie; ++it) {
Eli Friedman96fd2642013-06-12 00:13:45 +00002470 bool isNamedArg = true;
2471 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002472 isNamedArg = (it - FI.arg_begin()) <
2473 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002474
Bill Wendling9987c0e2010-10-18 23:51:38 +00002475 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002476 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002477 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002478
2479 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2480 // eightbyte of an argument, the whole argument is passed on the
2481 // stack. If registers have already been assigned for some
2482 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002483 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002484 freeIntRegs -= neededInt;
2485 freeSSERegs -= neededSSE;
2486 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002487 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002488 }
2489 }
2490}
2491
2492static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2493 QualType Ty,
2494 CodeGenFunction &CGF) {
2495 llvm::Value *overflow_arg_area_p =
2496 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2497 llvm::Value *overflow_arg_area =
2498 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2499
2500 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2501 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002502 // It isn't stated explicitly in the standard, but in practice we use
2503 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002504 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2505 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002506 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002507 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002508 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002509 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2510 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002511 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002512 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002513 overflow_arg_area =
2514 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2515 overflow_arg_area->getType(),
2516 "overflow_arg_area.align");
2517 }
2518
2519 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002520 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002521 llvm::Value *Res =
2522 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002523 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002524
2525 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2526 // l->overflow_arg_area + sizeof(type).
2527 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2528 // an 8 byte boundary.
2529
2530 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002531 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002532 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002533 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2534 "overflow_arg_area.next");
2535 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2536
2537 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2538 return Res;
2539}
2540
2541llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2542 CodeGenFunction &CGF) const {
2543 // Assume that va_list type is correct; should be pointer to LLVM type:
2544 // struct {
2545 // i32 gp_offset;
2546 // i32 fp_offset;
2547 // i8* overflow_arg_area;
2548 // i8* reg_save_area;
2549 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002550 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002551
Chris Lattner9723d6c2010-03-11 18:19:55 +00002552 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002553 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2554 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555
2556 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2557 // in the registers. If not go to step 7.
2558 if (!neededInt && !neededSSE)
2559 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2560
2561 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2562 // general purpose registers needed to pass type and num_fp to hold
2563 // the number of floating point registers needed.
2564
2565 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2566 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2567 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2568 //
2569 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2570 // register save space).
2571
2572 llvm::Value *InRegs = 0;
2573 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2574 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2575 if (neededInt) {
2576 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2577 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002578 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2579 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002580 }
2581
2582 if (neededSSE) {
2583 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2584 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2585 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002586 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2587 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002588 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2589 }
2590
2591 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2592 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2593 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2594 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2595
2596 // Emit code to load the value if it was passed in registers.
2597
2598 CGF.EmitBlock(InRegBlock);
2599
2600 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2601 // an offset of l->gp_offset and/or l->fp_offset. This may require
2602 // copying to a temporary location in case the parameter is passed
2603 // in different register classes or requires an alignment greater
2604 // than 8 for general purpose registers and 16 for XMM registers.
2605 //
2606 // FIXME: This really results in shameful code when we end up needing to
2607 // collect arguments from different places; often what should result in a
2608 // simple assembling of a structure from scattered addresses has many more
2609 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002610 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002611 llvm::Value *RegAddr =
2612 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2613 "reg_save_area");
2614 if (neededInt && neededSSE) {
2615 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002616 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002617 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002618 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2619 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002620 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002621 llvm::Type *TyLo = ST->getElementType(0);
2622 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002623 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002624 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002625 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2626 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002627 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2628 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sands998f9d92010-02-15 16:14:01 +00002629 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2630 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002631 llvm::Value *V =
2632 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2633 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2634 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2635 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2636
Owen Anderson170229f2009-07-14 23:10:40 +00002637 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002638 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002639 } else if (neededInt) {
2640 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2641 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002642 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002643
2644 // Copy to a temporary if necessary to ensure the appropriate alignment.
2645 std::pair<CharUnits, CharUnits> SizeAlign =
2646 CGF.getContext().getTypeInfoInChars(Ty);
2647 uint64_t TySize = SizeAlign.first.getQuantity();
2648 unsigned TyAlign = SizeAlign.second.getQuantity();
2649 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002650 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2651 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2652 RegAddr = Tmp;
2653 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002654 } else if (neededSSE == 1) {
2655 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2656 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2657 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002658 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002659 assert(neededSSE == 2 && "Invalid number of needed registers!");
2660 // SSE registers are spaced 16 bytes apart in the register save
2661 // area, we need to collect the two eightbytes together.
2662 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002663 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002664 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002665 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002666 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002667 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2668 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2669 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002670 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2671 DblPtrTy));
2672 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2673 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2674 DblPtrTy));
2675 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2676 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2677 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002678 }
2679
2680 // AMD64-ABI 3.5.7p5: Step 5. Set:
2681 // l->gp_offset = l->gp_offset + num_gp * 8
2682 // l->fp_offset = l->fp_offset + num_fp * 16.
2683 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002684 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2686 gp_offset_p);
2687 }
2688 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002689 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002690 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2691 fp_offset_p);
2692 }
2693 CGF.EmitBranch(ContBlock);
2694
2695 // Emit code to load the value if it was passed in memory.
2696
2697 CGF.EmitBlock(InMemBlock);
2698 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2699
2700 // Return the appropriate result.
2701
2702 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002703 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002704 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002705 ResAddr->addIncoming(RegAddr, InRegBlock);
2706 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707 return ResAddr;
2708}
2709
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002710ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002711
2712 if (Ty->isVoidType())
2713 return ABIArgInfo::getIgnore();
2714
2715 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2716 Ty = EnumTy->getDecl()->getIntegerType();
2717
2718 uint64_t Size = getContext().getTypeSize(Ty);
2719
Reid Kleckner9005f412014-05-02 00:51:20 +00002720 const RecordType *RT = Ty->getAs<RecordType>();
2721 if (RT) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002722 if (IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002723 if (isRecordReturnIndirect(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002724 return ABIArgInfo::getIndirect(0, false);
2725 } else {
Mark Lacey3825e832013-10-06 01:33:34 +00002726 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002727 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2728 }
2729
2730 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002731 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2732
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002733 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00002734 if (Size == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002735 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2736 Size));
Reid Kleckner9005f412014-05-02 00:51:20 +00002737 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002738
Reid Kleckner9005f412014-05-02 00:51:20 +00002739 if (const auto *MPT = Ty->getAs<MemberPointerType>()) {
2740 // If the member pointer is not an aggregate, pass it directly.
2741 if (getTarget().getCXXABI().isMicrosoft()) {
2742 // For Microsoft, check with the inheritance model.
2743 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
2744 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
2745 RD->getMSInheritanceModel()))
2746 return ABIArgInfo::getDirect();
2747 } else {
2748 // For Itanium, data pointers are simple and function pointers are big.
2749 if (MPT->isMemberDataPointer())
2750 return ABIArgInfo::getDirect();
2751 }
2752 }
2753
2754 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002755 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2756 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner9005f412014-05-02 00:51:20 +00002757 if (Size > 64 || !llvm::isPowerOf2_64(Size))
2758 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002759
Reid Kleckner9005f412014-05-02 00:51:20 +00002760 // Otherwise, coerce it to a small integer.
2761 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002762 }
2763
2764 if (Ty->isPromotableIntegerType())
2765 return ABIArgInfo::getExtend();
2766
2767 return ABIArgInfo::getDirect();
2768}
2769
2770void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2771
2772 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002773 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002774
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002775 for (auto &I : FI.arguments())
2776 I.info = classify(I.type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002777}
2778
Chris Lattner04dc9572010-08-31 16:44:54 +00002779llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2780 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002781 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002782
Chris Lattner04dc9572010-08-31 16:44:54 +00002783 CGBuilderTy &Builder = CGF.Builder;
2784 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2785 "ap");
2786 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2787 llvm::Type *PTy =
2788 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2789 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2790
2791 uint64_t Offset =
2792 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2793 llvm::Value *NextAddr =
2794 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2795 "ap.next");
2796 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2797
2798 return AddrTyped;
2799}
Chris Lattner0cf24192010-06-28 20:05:43 +00002800
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002801namespace {
2802
Derek Schuffa2020962012-10-16 22:30:41 +00002803class NaClX86_64ABIInfo : public ABIInfo {
2804 public:
2805 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2806 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Craig Topper4f12f102014-03-12 06:41:41 +00002807 void computeInfo(CGFunctionInfo &FI) const override;
2808 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2809 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00002810 private:
2811 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2812 X86_64ABIInfo NInfo; // Used for everything else.
2813};
2814
2815class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2816 public:
2817 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2818 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2819};
2820
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002821}
2822
Derek Schuffa2020962012-10-16 22:30:41 +00002823void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2824 if (FI.getASTCallingConvention() == CC_PnaclCall)
2825 PInfo.computeInfo(FI);
2826 else
2827 NInfo.computeInfo(FI);
2828}
2829
2830llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2831 CodeGenFunction &CGF) const {
2832 // Always use the native convention; calling pnacl-style varargs functions
2833 // is unuspported.
2834 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2835}
2836
2837
John McCallea8d8bb2010-03-11 00:10:12 +00002838// PowerPC-32
2839
2840namespace {
2841class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2842public:
Chris Lattner2b037972010-07-29 02:01:43 +00002843 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002844
Craig Topper4f12f102014-03-12 06:41:41 +00002845 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00002846 // This is recovered from gcc output.
2847 return 1; // r1 is the dedicated stack pointer
2848 }
2849
2850 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002851 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00002852};
2853
2854}
2855
2856bool
2857PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2858 llvm::Value *Address) const {
2859 // This is calculated from the LLVM and GCC tables and verified
2860 // against gcc output. AFAIK all ABIs use the same encoding.
2861
2862 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002863
Chris Lattnerece04092012-02-07 00:39:47 +00002864 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002865 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2866 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2867 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2868
2869 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002870 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002871
2872 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002873 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00002874
2875 // 64-76 are various 4-byte special-purpose registers:
2876 // 64: mq
2877 // 65: lr
2878 // 66: ctr
2879 // 67: ap
2880 // 68-75 cr0-7
2881 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00002882 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002883
2884 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002885 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002886
2887 // 109: vrsave
2888 // 110: vscr
2889 // 111: spe_acc
2890 // 112: spefscr
2891 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002892 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002893
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002894 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002895}
2896
Roman Divackyd966e722012-05-09 18:22:46 +00002897// PowerPC-64
2898
2899namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002900/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2901class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2902
2903public:
2904 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2905
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002906 bool isPromotableTypeForABI(QualType Ty) const;
2907
2908 ABIArgInfo classifyReturnType(QualType RetTy) const;
2909 ABIArgInfo classifyArgumentType(QualType Ty) const;
2910
Bill Schmidt84d37792012-10-12 19:26:17 +00002911 // TODO: We can add more logic to computeInfo to improve performance.
2912 // Example: For aggregate arguments that fit in a register, we could
2913 // use getDirectInReg (as is done below for structs containing a single
2914 // floating-point value) to avoid pushing them to memory on function
2915 // entry. This would require changing the logic in PPCISelLowering
2916 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00002917 void computeInfo(CGFunctionInfo &FI) const override {
Bill Schmidt84d37792012-10-12 19:26:17 +00002918 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002919 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002920 // We rely on the default argument classification for the most part.
2921 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00002922 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002923 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00002924 if (T) {
2925 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidt179afae2013-07-23 22:15:57 +00002926 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002927 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002928 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00002929 continue;
2930 }
2931 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002932 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00002933 }
2934 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00002935
Craig Topper4f12f102014-03-12 06:41:41 +00002936 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2937 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00002938};
2939
2940class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2941public:
2942 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2943 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2944
Craig Topper4f12f102014-03-12 06:41:41 +00002945 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002946 // This is recovered from gcc output.
2947 return 1; // r1 is the dedicated stack pointer
2948 }
2949
2950 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002951 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00002952};
2953
Roman Divackyd966e722012-05-09 18:22:46 +00002954class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2955public:
2956 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2957
Craig Topper4f12f102014-03-12 06:41:41 +00002958 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00002959 // This is recovered from gcc output.
2960 return 1; // r1 is the dedicated stack pointer
2961 }
2962
2963 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002964 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00002965};
2966
2967}
2968
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002969// Return true if the ABI requires Ty to be passed sign- or zero-
2970// extended to 64 bits.
2971bool
2972PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2973 // Treat an enum type as its underlying type.
2974 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2975 Ty = EnumTy->getDecl()->getIntegerType();
2976
2977 // Promotable integer types are required to be promoted by the ABI.
2978 if (Ty->isPromotableIntegerType())
2979 return true;
2980
2981 // In addition to the usual promotable integer types, we also need to
2982 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2983 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2984 switch (BT->getKind()) {
2985 case BuiltinType::Int:
2986 case BuiltinType::UInt:
2987 return true;
2988 default:
2989 break;
2990 }
2991
2992 return false;
2993}
2994
2995ABIArgInfo
2996PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00002997 if (Ty->isAnyComplexType())
2998 return ABIArgInfo::getDirect();
2999
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003000 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003001 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003002 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003003
3004 return ABIArgInfo::getIndirect(0);
3005 }
3006
3007 return (isPromotableTypeForABI(Ty) ?
3008 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3009}
3010
3011ABIArgInfo
3012PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3013 if (RetTy->isVoidType())
3014 return ABIArgInfo::getIgnore();
3015
Bill Schmidta3d121c2012-12-17 04:20:17 +00003016 if (RetTy->isAnyComplexType())
3017 return ABIArgInfo::getDirect();
3018
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003019 if (isAggregateTypeForABI(RetTy))
3020 return ABIArgInfo::getIndirect(0);
3021
3022 return (isPromotableTypeForABI(RetTy) ?
3023 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3024}
3025
Bill Schmidt25cb3492012-10-03 19:18:57 +00003026// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3027llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3028 QualType Ty,
3029 CodeGenFunction &CGF) const {
3030 llvm::Type *BP = CGF.Int8PtrTy;
3031 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3032
3033 CGBuilderTy &Builder = CGF.Builder;
3034 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3035 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3036
Bill Schmidt924c4782013-01-14 17:45:36 +00003037 // Update the va_list pointer. The pointer should be bumped by the
3038 // size of the object. We can trust getTypeSize() except for a complex
3039 // type whose base type is smaller than a doubleword. For these, the
3040 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003041 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003042 QualType BaseTy;
3043 unsigned CplxBaseSize = 0;
3044
3045 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3046 BaseTy = CTy->getElementType();
3047 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3048 if (CplxBaseSize < 8)
3049 SizeInBytes = 16;
3050 }
3051
Bill Schmidt25cb3492012-10-03 19:18:57 +00003052 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3053 llvm::Value *NextAddr =
3054 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3055 "ap.next");
3056 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3057
Bill Schmidt924c4782013-01-14 17:45:36 +00003058 // If we have a complex type and the base type is smaller than 8 bytes,
3059 // the ABI calls for the real and imaginary parts to be right-adjusted
3060 // in separate doublewords. However, Clang expects us to produce a
3061 // pointer to a structure with the two parts packed tightly. So generate
3062 // loads of the real and imaginary parts relative to the va_list pointer,
3063 // and store them to a temporary structure.
3064 if (CplxBaseSize && CplxBaseSize < 8) {
3065 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3066 llvm::Value *ImagAddr = RealAddr;
3067 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3068 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3069 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3070 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3071 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3072 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3073 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3074 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3075 "vacplx");
3076 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3077 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3078 Builder.CreateStore(Real, RealPtr, false);
3079 Builder.CreateStore(Imag, ImagPtr, false);
3080 return Ptr;
3081 }
3082
Bill Schmidt25cb3492012-10-03 19:18:57 +00003083 // If the argument is smaller than 8 bytes, it is right-adjusted in
3084 // its doubleword slot. Adjust the pointer to pick it up from the
3085 // correct offset.
3086 if (SizeInBytes < 8) {
3087 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3088 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3089 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3090 }
3091
3092 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3093 return Builder.CreateBitCast(Addr, PTy);
3094}
3095
3096static bool
3097PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3098 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003099 // This is calculated from the LLVM and GCC tables and verified
3100 // against gcc output. AFAIK all ABIs use the same encoding.
3101
3102 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3103
3104 llvm::IntegerType *i8 = CGF.Int8Ty;
3105 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3106 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3107 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3108
3109 // 0-31: r0-31, the 8-byte general-purpose registers
3110 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3111
3112 // 32-63: fp0-31, the 8-byte floating-point registers
3113 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3114
3115 // 64-76 are various 4-byte special-purpose registers:
3116 // 64: mq
3117 // 65: lr
3118 // 66: ctr
3119 // 67: ap
3120 // 68-75 cr0-7
3121 // 76: xer
3122 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3123
3124 // 77-108: v0-31, the 16-byte vector registers
3125 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3126
3127 // 109: vrsave
3128 // 110: vscr
3129 // 111: spe_acc
3130 // 112: spefscr
3131 // 113: sfp
3132 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3133
3134 return false;
3135}
John McCallea8d8bb2010-03-11 00:10:12 +00003136
Bill Schmidt25cb3492012-10-03 19:18:57 +00003137bool
3138PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3139 CodeGen::CodeGenFunction &CGF,
3140 llvm::Value *Address) const {
3141
3142 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3143}
3144
3145bool
3146PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3147 llvm::Value *Address) const {
3148
3149 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3150}
3151
Chris Lattner0cf24192010-06-28 20:05:43 +00003152//===----------------------------------------------------------------------===//
Tim Northovera2ee4332014-03-29 15:09:45 +00003153// ARM64 ABI Implementation
3154//===----------------------------------------------------------------------===//
3155
3156namespace {
3157
3158class ARM64ABIInfo : public ABIInfo {
3159public:
3160 enum ABIKind {
3161 AAPCS = 0,
3162 DarwinPCS
3163 };
3164
3165private:
3166 ABIKind Kind;
3167
3168public:
3169 ARM64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
3170
3171private:
3172 ABIKind getABIKind() const { return Kind; }
3173 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3174
3175 ABIArgInfo classifyReturnType(QualType RetTy) const;
3176 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3177 bool &IsHA, unsigned &AllocatedGPR,
Bob Wilson373af732014-04-21 01:23:39 +00003178 bool &IsSmallAggr, bool IsNamedArg) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00003179 bool isIllegalVectorType(QualType Ty) const;
3180
3181 virtual void computeInfo(CGFunctionInfo &FI) const {
3182 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3183 // number of SIMD and Floating-point registers allocated so far.
3184 // If the argument is an HFA or an HVA and there are sufficient unallocated
3185 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3186 // and Floating-point Registers (with one register per member of the HFA or
3187 // HVA). Otherwise, the NSRN is set to 8.
3188 unsigned AllocatedVFP = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003189
Tim Northovera2ee4332014-03-29 15:09:45 +00003190 // To correctly handle small aggregates, we need to keep track of the number
3191 // of GPRs allocated so far. If the small aggregate can't all fit into
3192 // registers, it will be on stack. We don't allow the aggregate to be
3193 // partially in registers.
3194 unsigned AllocatedGPR = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003195
3196 // Find the number of named arguments. Variadic arguments get special
3197 // treatment with the Darwin ABI.
3198 unsigned NumRequiredArgs = (FI.isVariadic() ?
3199 FI.getRequiredArgs().getNumRequiredArgs() :
3200 FI.arg_size());
3201
Tim Northovera2ee4332014-03-29 15:09:45 +00003202 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3203 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3204 it != ie; ++it) {
3205 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3206 bool IsHA = false, IsSmallAggr = false;
3207 const unsigned NumVFPs = 8;
3208 const unsigned NumGPRs = 8;
Bob Wilson373af732014-04-21 01:23:39 +00003209 bool IsNamedArg = ((it - FI.arg_begin()) <
3210 static_cast<signed>(NumRequiredArgs));
Tim Northovera2ee4332014-03-29 15:09:45 +00003211 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
Bob Wilson373af732014-04-21 01:23:39 +00003212 AllocatedGPR, IsSmallAggr, IsNamedArg);
Tim Northover5ffc0922014-04-17 10:20:38 +00003213
3214 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3215 // as sequences of floats since they'll get "holes" inserted as
3216 // padding by the back end.
Tim Northover07f16242014-04-18 10:47:44 +00003217 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3218 getContext().getTypeAlign(it->type) < 64) {
3219 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3220 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
Tim Northover5ffc0922014-04-17 10:20:38 +00003221
Tim Northover07f16242014-04-18 10:47:44 +00003222 llvm::Type *CoerceTy = llvm::ArrayType::get(
3223 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3224 it->info = ABIArgInfo::getDirect(CoerceTy);
Tim Northover5ffc0922014-04-17 10:20:38 +00003225 }
3226
Tim Northovera2ee4332014-03-29 15:09:45 +00003227 // If we do not have enough VFP registers for the HA, any VFP registers
3228 // that are unallocated are marked as unavailable. To achieve this, we add
3229 // padding of (NumVFPs - PreAllocation) floats.
3230 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3231 llvm::Type *PaddingTy = llvm::ArrayType::get(
3232 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
Tim Northover5ffc0922014-04-17 10:20:38 +00003233 it->info.setPaddingType(PaddingTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00003234 }
Tim Northover5ffc0922014-04-17 10:20:38 +00003235
Tim Northovera2ee4332014-03-29 15:09:45 +00003236 // If we do not have enough GPRs for the small aggregate, any GPR regs
3237 // that are unallocated are marked as unavailable.
3238 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3239 llvm::Type *PaddingTy = llvm::ArrayType::get(
3240 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3241 it->info =
3242 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3243 }
3244 }
3245 }
3246
3247 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3248 CodeGenFunction &CGF) const;
3249
3250 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3251 CodeGenFunction &CGF) const;
3252
3253 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3254 CodeGenFunction &CGF) const {
3255 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3256 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3257 }
3258};
3259
3260class ARM64TargetCodeGenInfo : public TargetCodeGenInfo {
3261public:
3262 ARM64TargetCodeGenInfo(CodeGenTypes &CGT, ARM64ABIInfo::ABIKind Kind)
3263 : TargetCodeGenInfo(new ARM64ABIInfo(CGT, Kind)) {}
3264
3265 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3266 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3267 }
3268
3269 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3270
3271 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3272};
3273}
3274
3275static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3276 ASTContext &Context,
3277 uint64_t *HAMembers = 0);
3278
3279ABIArgInfo ARM64ABIInfo::classifyArgumentType(QualType Ty,
3280 unsigned &AllocatedVFP,
3281 bool &IsHA,
3282 unsigned &AllocatedGPR,
Bob Wilson373af732014-04-21 01:23:39 +00003283 bool &IsSmallAggr,
3284 bool IsNamedArg) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003285 // Handle illegal vector types here.
3286 if (isIllegalVectorType(Ty)) {
3287 uint64_t Size = getContext().getTypeSize(Ty);
3288 if (Size <= 32) {
3289 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3290 AllocatedGPR++;
3291 return ABIArgInfo::getDirect(ResType);
3292 }
3293 if (Size == 64) {
3294 llvm::Type *ResType =
3295 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3296 AllocatedVFP++;
3297 return ABIArgInfo::getDirect(ResType);
3298 }
3299 if (Size == 128) {
3300 llvm::Type *ResType =
3301 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3302 AllocatedVFP++;
3303 return ABIArgInfo::getDirect(ResType);
3304 }
3305 AllocatedGPR++;
3306 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3307 }
3308 if (Ty->isVectorType())
3309 // Size of a legal vector should be either 64 or 128.
3310 AllocatedVFP++;
3311 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3312 if (BT->getKind() == BuiltinType::Half ||
3313 BT->getKind() == BuiltinType::Float ||
3314 BT->getKind() == BuiltinType::Double ||
3315 BT->getKind() == BuiltinType::LongDouble)
3316 AllocatedVFP++;
3317 }
3318
3319 if (!isAggregateTypeForABI(Ty)) {
3320 // Treat an enum type as its underlying type.
3321 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3322 Ty = EnumTy->getDecl()->getIntegerType();
3323
3324 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003325 unsigned Alignment = getContext().getTypeAlign(Ty);
3326 if (!isDarwinPCS() && Alignment > 64)
3327 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3328
Tim Northovera2ee4332014-03-29 15:09:45 +00003329 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3330 AllocatedGPR += RegsNeeded;
3331 }
3332 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3333 ? ABIArgInfo::getExtend()
3334 : ABIArgInfo::getDirect());
3335 }
3336
3337 // Structures with either a non-trivial destructor or a non-trivial
3338 // copy constructor are always indirect.
3339 if (isRecordReturnIndirect(Ty, getCXXABI())) {
3340 AllocatedGPR++;
3341 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3342 }
3343
3344 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3345 // elsewhere for GNU compatibility.
3346 if (isEmptyRecord(getContext(), Ty, true)) {
3347 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3348 return ABIArgInfo::getIgnore();
3349
3350 ++AllocatedGPR;
3351 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3352 }
3353
3354 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
3355 const Type *Base = 0;
3356 uint64_t Members = 0;
3357 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003358 IsHA = true;
Bob Wilson373af732014-04-21 01:23:39 +00003359 if (!IsNamedArg && isDarwinPCS()) {
3360 // With the Darwin ABI, variadic arguments are always passed on the stack
3361 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
3362 uint64_t Size = getContext().getTypeSize(Ty);
3363 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
3364 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3365 }
3366 AllocatedVFP += Members;
Tim Northovera2ee4332014-03-29 15:09:45 +00003367 return ABIArgInfo::getExpand();
3368 }
3369
3370 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3371 uint64_t Size = getContext().getTypeSize(Ty);
3372 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003373 unsigned Alignment = getContext().getTypeAlign(Ty);
3374 if (!isDarwinPCS() && Alignment > 64)
3375 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3376
Tim Northovera2ee4332014-03-29 15:09:45 +00003377 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3378 AllocatedGPR += Size / 64;
3379 IsSmallAggr = true;
3380 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3381 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00003382 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003383 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3384 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3385 }
3386 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3387 }
3388
3389 AllocatedGPR++;
3390 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3391}
3392
3393ABIArgInfo ARM64ABIInfo::classifyReturnType(QualType RetTy) const {
3394 if (RetTy->isVoidType())
3395 return ABIArgInfo::getIgnore();
3396
3397 // Large vector types should be returned via memory.
3398 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3399 return ABIArgInfo::getIndirect(0);
3400
3401 if (!isAggregateTypeForABI(RetTy)) {
3402 // Treat an enum type as its underlying type.
3403 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3404 RetTy = EnumTy->getDecl()->getIntegerType();
3405
Tim Northover4dab6982014-04-18 13:46:08 +00003406 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3407 ? ABIArgInfo::getExtend()
3408 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00003409 }
3410
3411 // Structures with either a non-trivial destructor or a non-trivial
3412 // copy constructor are always indirect.
3413 if (isRecordReturnIndirect(RetTy, getCXXABI()))
3414 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3415
3416 if (isEmptyRecord(getContext(), RetTy, true))
3417 return ABIArgInfo::getIgnore();
3418
3419 const Type *Base = 0;
3420 if (isHomogeneousAggregate(RetTy, Base, getContext()))
3421 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3422 return ABIArgInfo::getDirect();
3423
3424 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3425 uint64_t Size = getContext().getTypeSize(RetTy);
3426 if (Size <= 128) {
3427 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3428 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3429 }
3430
3431 return ABIArgInfo::getIndirect(0);
3432}
3433
3434/// isIllegalVectorType - check whether the vector type is legal for ARM64.
3435bool ARM64ABIInfo::isIllegalVectorType(QualType Ty) const {
3436 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3437 // Check whether VT is legal.
3438 unsigned NumElements = VT->getNumElements();
3439 uint64_t Size = getContext().getTypeSize(VT);
3440 // NumElements should be power of 2 between 1 and 16.
3441 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3442 return true;
3443 return Size != 64 && (Size != 128 || NumElements == 1);
3444 }
3445 return false;
3446}
3447
3448static llvm::Value *EmitAArch64VAArg(llvm::Value *VAListAddr, QualType Ty,
3449 int AllocatedGPR, int AllocatedVFP,
3450 bool IsIndirect, CodeGenFunction &CGF) {
3451 // The AArch64 va_list type and handling is specified in the Procedure Call
3452 // Standard, section B.4:
3453 //
3454 // struct {
3455 // void *__stack;
3456 // void *__gr_top;
3457 // void *__vr_top;
3458 // int __gr_offs;
3459 // int __vr_offs;
3460 // };
3461
3462 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3463 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3464 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3465 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3466 auto &Ctx = CGF.getContext();
3467
3468 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
3469 int reg_top_index;
3470 int RegSize;
3471 if (AllocatedGPR) {
3472 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
3473 // 3 is the field number of __gr_offs
3474 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3475 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3476 reg_top_index = 1; // field number for __gr_top
3477 RegSize = 8 * AllocatedGPR;
3478 } else {
3479 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
3480 // 4 is the field number of __vr_offs.
3481 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3482 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3483 reg_top_index = 2; // field number for __vr_top
3484 RegSize = 16 * AllocatedVFP;
3485 }
3486
3487 //=======================================
3488 // Find out where argument was passed
3489 //=======================================
3490
3491 // If reg_offs >= 0 we're already using the stack for this type of
3492 // argument. We don't want to keep updating reg_offs (in case it overflows,
3493 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3494 // whatever they get).
3495 llvm::Value *UsingStack = 0;
3496 UsingStack = CGF.Builder.CreateICmpSGE(
3497 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
3498
3499 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3500
3501 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00003502 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00003503 CGF.EmitBlock(MaybeRegBlock);
3504
3505 // Integer arguments may need to correct register alignment (for example a
3506 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3507 // align __gr_offs to calculate the potential address.
3508 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3509 int Align = Ctx.getTypeAlign(Ty) / 8;
3510
3511 reg_offs = CGF.Builder.CreateAdd(
3512 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3513 "align_regoffs");
3514 reg_offs = CGF.Builder.CreateAnd(
3515 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3516 "aligned_regoffs");
3517 }
3518
3519 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
3520 llvm::Value *NewOffset = 0;
3521 NewOffset = CGF.Builder.CreateAdd(
3522 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
3523 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3524
3525 // Now we're in a position to decide whether this argument really was in
3526 // registers or not.
3527 llvm::Value *InRegs = 0;
3528 InRegs = CGF.Builder.CreateICmpSLE(
3529 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
3530
3531 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
3532
3533 //=======================================
3534 // Argument was in registers
3535 //=======================================
3536
3537 // Now we emit the code for if the argument was originally passed in
3538 // registers. First start the appropriate block:
3539 CGF.EmitBlock(InRegBlock);
3540
3541 llvm::Value *reg_top_p = 0, *reg_top = 0;
3542 reg_top_p =
3543 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
3544 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
3545 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
3546 llvm::Value *RegAddr = 0;
3547 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
3548
3549 if (IsIndirect) {
3550 // If it's been passed indirectly (actually a struct), whatever we find from
3551 // stored registers or on the stack will actually be a struct **.
3552 MemTy = llvm::PointerType::getUnqual(MemTy);
3553 }
3554
3555 const Type *Base = 0;
3556 uint64_t NumMembers;
3557 if (isHomogeneousAggregate(Ty, Base, Ctx, &NumMembers) && NumMembers > 1) {
3558 // Homogeneous aggregates passed in registers will have their elements split
3559 // and stored 16-bytes apart regardless of size (they're notionally in qN,
3560 // qN+1, ...). We reload and store into a temporary local variable
3561 // contiguously.
3562 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
3563 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
3564 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
3565 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
3566 int Offset = 0;
3567
3568 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
3569 Offset = 16 - Ctx.getTypeSize(Base) / 8;
3570 for (unsigned i = 0; i < NumMembers; ++i) {
3571 llvm::Value *BaseOffset =
3572 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
3573 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
3574 LoadAddr = CGF.Builder.CreateBitCast(
3575 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
3576 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
3577
3578 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
3579 CGF.Builder.CreateStore(Elem, StoreAddr);
3580 }
3581
3582 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
3583 } else {
3584 // Otherwise the object is contiguous in memory
3585 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
3586 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
3587 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
3588 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
3589 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
3590
3591 BaseAddr = CGF.Builder.CreateAdd(
3592 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3593
3594 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
3595 }
3596
3597 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
3598 }
3599
3600 CGF.EmitBranch(ContBlock);
3601
3602 //=======================================
3603 // Argument was on the stack
3604 //=======================================
3605 CGF.EmitBlock(OnStackBlock);
3606
3607 llvm::Value *stack_p = 0, *OnStackAddr = 0;
3608 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
3609 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
3610
3611 // Again, stack arguments may need realigmnent. In this case both integer and
3612 // floating-point ones might be affected.
3613 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3614 int Align = Ctx.getTypeAlign(Ty) / 8;
3615
3616 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3617
3618 OnStackAddr = CGF.Builder.CreateAdd(
3619 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
3620 "align_stack");
3621 OnStackAddr = CGF.Builder.CreateAnd(
3622 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
3623 "align_stack");
3624
3625 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3626 }
3627
3628 uint64_t StackSize;
3629 if (IsIndirect)
3630 StackSize = 8;
3631 else
3632 StackSize = Ctx.getTypeSize(Ty) / 8;
3633
3634 // All stack slots are 8 bytes
3635 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
3636
3637 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
3638 llvm::Value *NewStack =
3639 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
3640
3641 // Write the new value of __stack for the next call to va_arg
3642 CGF.Builder.CreateStore(NewStack, stack_p);
3643
3644 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
3645 Ctx.getTypeSize(Ty) < 64) {
3646 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
3647 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3648
3649 OnStackAddr = CGF.Builder.CreateAdd(
3650 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3651
3652 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3653 }
3654
3655 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
3656
3657 CGF.EmitBranch(ContBlock);
3658
3659 //=======================================
3660 // Tidy up
3661 //=======================================
3662 CGF.EmitBlock(ContBlock);
3663
3664 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
3665 ResAddr->addIncoming(RegAddr, InRegBlock);
3666 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
3667
3668 if (IsIndirect)
3669 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
3670
3671 return ResAddr;
3672}
3673
3674llvm::Value *ARM64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3675 CodeGenFunction &CGF) const {
3676
3677 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
3678 bool IsHA = false, IsSmallAggr = false;
Bob Wilson373af732014-04-21 01:23:39 +00003679 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
3680 IsSmallAggr, false /*IsNamedArg*/);
Tim Northovera2ee4332014-03-29 15:09:45 +00003681
3682 return EmitAArch64VAArg(VAListAddr, Ty, AllocatedGPR, AllocatedVFP,
3683 AI.isIndirect(), CGF);
3684}
3685
3686llvm::Value *ARM64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3687 CodeGenFunction &CGF) const {
3688 // We do not support va_arg for aggregates or illegal vector types.
3689 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
3690 // other cases.
3691 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
3692 return 0;
3693
3694 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
3695 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
3696
3697 const Type *Base = 0;
3698 bool isHA = isHomogeneousAggregate(Ty, Base, getContext());
3699
3700 bool isIndirect = false;
3701 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
3702 // be passed indirectly.
3703 if (Size > 16 && !isHA) {
3704 isIndirect = true;
3705 Size = 8;
3706 Align = 8;
3707 }
3708
3709 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
3710 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
3711
3712 CGBuilderTy &Builder = CGF.Builder;
3713 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3714 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3715
3716 if (isEmptyRecord(getContext(), Ty, true)) {
3717 // These are ignored for parameter passing purposes.
3718 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3719 return Builder.CreateBitCast(Addr, PTy);
3720 }
3721
3722 const uint64_t MinABIAlign = 8;
3723 if (Align > MinABIAlign) {
3724 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
3725 Addr = Builder.CreateGEP(Addr, Offset);
3726 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3727 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
3728 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
3729 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
3730 }
3731
3732 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
3733 llvm::Value *NextAddr = Builder.CreateGEP(
3734 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
3735 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3736
3737 if (isIndirect)
3738 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
3739 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3740 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3741
3742 return AddrTyped;
3743}
3744
3745//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003746// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00003747//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003748
3749namespace {
3750
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003751class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003752public:
3753 enum ABIKind {
3754 APCS = 0,
3755 AAPCS = 1,
3756 AAPCS_VFP
3757 };
3758
3759private:
3760 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00003761 mutable int VFPRegs[16];
3762 const unsigned NumVFPs;
3763 const unsigned NumGPRs;
3764 mutable unsigned AllocatedGPRs;
3765 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003766
3767public:
Oliver Stannard405bded2014-02-11 09:25:50 +00003768 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
3769 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00003770 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00003771 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00003772 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003773
John McCall3480ef22011-08-30 01:42:09 +00003774 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003775 switch (getTarget().getTriple().getEnvironment()) {
3776 case llvm::Triple::Android:
3777 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003778 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003779 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00003780 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003781 return true;
3782 default:
3783 return false;
3784 }
John McCall3480ef22011-08-30 01:42:09 +00003785 }
3786
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003787 bool isEABIHF() const {
3788 switch (getTarget().getTriple().getEnvironment()) {
3789 case llvm::Triple::EABIHF:
3790 case llvm::Triple::GNUEABIHF:
3791 return true;
3792 default:
3793 return false;
3794 }
3795 }
3796
Daniel Dunbar020daa92009-09-12 01:00:39 +00003797 ABIKind getABIKind() const { return Kind; }
3798
Tim Northovera484bc02013-10-01 14:34:25 +00003799private:
Amara Emerson9dc78782014-01-28 10:56:36 +00003800 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Oliver Stannard405bded2014-02-11 09:25:50 +00003801 ABIArgInfo classifyArgumentType(QualType RetTy, bool &IsHA, bool isVariadic,
3802 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00003803 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003804
Craig Topper4f12f102014-03-12 06:41:41 +00003805 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003806
Craig Topper4f12f102014-03-12 06:41:41 +00003807 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3808 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00003809
3810 llvm::CallingConv::ID getLLVMDefaultCC() const;
3811 llvm::CallingConv::ID getABIDefaultCC() const;
3812 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00003813
3814 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
3815 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
3816 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003817};
3818
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003819class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3820public:
Chris Lattner2b037972010-07-29 02:01:43 +00003821 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3822 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00003823
John McCall3480ef22011-08-30 01:42:09 +00003824 const ARMABIInfo &getABIInfo() const {
3825 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3826 }
3827
Craig Topper4f12f102014-03-12 06:41:41 +00003828 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00003829 return 13;
3830 }
Roman Divackyc1617352011-05-18 19:36:54 +00003831
Craig Topper4f12f102014-03-12 06:41:41 +00003832 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00003833 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3834 }
3835
Roman Divackyc1617352011-05-18 19:36:54 +00003836 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003837 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00003838 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00003839
3840 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00003841 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00003842 return false;
3843 }
John McCall3480ef22011-08-30 01:42:09 +00003844
Craig Topper4f12f102014-03-12 06:41:41 +00003845 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00003846 if (getABIInfo().isEABI()) return 88;
3847 return TargetCodeGenInfo::getSizeOfUnwindException();
3848 }
Tim Northovera484bc02013-10-01 14:34:25 +00003849
3850 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00003851 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00003852 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3853 if (!FD)
3854 return;
3855
3856 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3857 if (!Attr)
3858 return;
3859
3860 const char *Kind;
3861 switch (Attr->getInterrupt()) {
3862 case ARMInterruptAttr::Generic: Kind = ""; break;
3863 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3864 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3865 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3866 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3867 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3868 }
3869
3870 llvm::Function *Fn = cast<llvm::Function>(GV);
3871
3872 Fn->addFnAttr("interrupt", Kind);
3873
3874 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3875 return;
3876
3877 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3878 // however this is not necessarily true on taking any interrupt. Instruct
3879 // the backend to perform a realignment as part of the function prologue.
3880 llvm::AttrBuilder B;
3881 B.addStackAlignmentAttr(8);
3882 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3883 llvm::AttributeSet::get(CGM.getLLVMContext(),
3884 llvm::AttributeSet::FunctionIndex,
3885 B));
3886 }
3887
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003888};
3889
Daniel Dunbard59655c2009-09-12 00:59:49 +00003890}
3891
Chris Lattner22326a12010-07-29 02:31:05 +00003892void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003893 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00003894 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00003895 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3896 // VFP registers of the appropriate type unallocated then the argument is
3897 // allocated to the lowest-numbered sequence of such registers.
3898 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3899 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00003900 resetAllocatedRegs();
3901
Amara Emerson9dc78782014-01-28 10:56:36 +00003902 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003903 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00003904 unsigned PreAllocationVFPs = AllocatedVFPs;
3905 unsigned PreAllocationGPRs = AllocatedGPRs;
Manman Ren2a523d82012-10-30 23:21:41 +00003906 bool IsHA = false;
Oliver Stannard405bded2014-02-11 09:25:50 +00003907 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00003908 // 6.1.2.3 There is one VFP co-processor register class using registers
3909 // s0-s15 (d0-d7) for passing arguments.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003910 I.info = classifyArgumentType(I.type, IsHA, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00003911 assert((IsCPRC || !IsHA) && "Homogeneous aggregates must be CPRCs");
Manman Ren2a523d82012-10-30 23:21:41 +00003912 // If we do not have enough VFP registers for the HA, any VFP registers
3913 // that are unallocated are marked as unavailable. To achieve this, we add
Oliver Stannard405bded2014-02-11 09:25:50 +00003914 // padding of (NumVFPs - PreAllocationVFP) floats.
Amara Emerson9dc78782014-01-28 10:56:36 +00003915 // Note that IsHA will only be set when using the AAPCS-VFP calling convention,
3916 // and the callee is not variadic.
Oliver Stannard405bded2014-02-11 09:25:50 +00003917 if (IsHA && AllocatedVFPs > NumVFPs && PreAllocationVFPs < NumVFPs) {
Manman Ren2a523d82012-10-30 23:21:41 +00003918 llvm::Type *PaddingTy = llvm::ArrayType::get(
Oliver Stannard405bded2014-02-11 09:25:50 +00003919 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocationVFPs);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003920 I.info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00003921 }
3922
3923 // If we have allocated some arguments onto the stack (due to running
3924 // out of VFP registers), we cannot split an argument between GPRs and
3925 // the stack. If this situation occurs, we add padding to prevent the
3926 // GPRs from being used. In this situiation, the current argument could
3927 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
3928 // unusable anyway.
3929 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
3930 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs && StackUsed) {
3931 llvm::Type *PaddingTy = llvm::ArrayType::get(
3932 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003933 I.info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
Manman Ren2a523d82012-10-30 23:21:41 +00003934 }
3935 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003936
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003937 // Always honor user-specified calling convention.
3938 if (FI.getCallingConvention() != llvm::CallingConv::C)
3939 return;
3940
John McCall882987f2013-02-28 19:01:20 +00003941 llvm::CallingConv::ID cc = getRuntimeCC();
3942 if (cc != llvm::CallingConv::C)
3943 FI.setEffectiveCallingConvention(cc);
3944}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00003945
John McCall882987f2013-02-28 19:01:20 +00003946/// Return the default calling convention that LLVM will use.
3947llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3948 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003949 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00003950 return llvm::CallingConv::ARM_AAPCS_VFP;
3951 else if (isEABI())
3952 return llvm::CallingConv::ARM_AAPCS;
3953 else
3954 return llvm::CallingConv::ARM_APCS;
3955}
3956
3957/// Return the calling convention that our ABI would like us to use
3958/// as the C calling convention.
3959llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003960 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00003961 case APCS: return llvm::CallingConv::ARM_APCS;
3962 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3963 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003964 }
John McCall882987f2013-02-28 19:01:20 +00003965 llvm_unreachable("bad ABI kind");
3966}
3967
3968void ARMABIInfo::setRuntimeCC() {
3969 assert(getRuntimeCC() == llvm::CallingConv::C);
3970
3971 // Don't muddy up the IR with a ton of explicit annotations if
3972 // they'd just match what LLVM will infer from the triple.
3973 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3974 if (abiCC != getLLVMDefaultCC())
3975 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003976}
3977
Bob Wilsone826a2a2011-08-03 05:58:22 +00003978/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3979/// aggregate. If HAMembers is non-null, the number of base elements
3980/// contained in the type is returned through it; this is used for the
3981/// recursive calls that check aggregate component types.
3982static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
Tim Northovera2ee4332014-03-29 15:09:45 +00003983 ASTContext &Context, uint64_t *HAMembers) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003984 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003985 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3986 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3987 return false;
3988 Members *= AT->getSize().getZExtValue();
3989 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3990 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003991 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00003992 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003993
Bob Wilsone826a2a2011-08-03 05:58:22 +00003994 Members = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003995 for (const auto *FD : RD->fields()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00003996 uint64_t FldMembers;
3997 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3998 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003999
4000 Members = (RD->isUnion() ?
4001 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00004002 }
4003 } else {
4004 Members = 1;
4005 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4006 Members = 2;
4007 Ty = CT->getElementType();
4008 }
4009
4010 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4011 // double, or 64-bit or 128-bit vectors.
4012 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4013 if (BT->getKind() != BuiltinType::Float &&
Tim Northovereb752d42012-07-20 22:29:29 +00004014 BT->getKind() != BuiltinType::Double &&
4015 BT->getKind() != BuiltinType::LongDouble)
Bob Wilsone826a2a2011-08-03 05:58:22 +00004016 return false;
4017 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4018 unsigned VecSize = Context.getTypeSize(VT);
4019 if (VecSize != 64 && VecSize != 128)
4020 return false;
4021 } else {
4022 return false;
4023 }
4024
4025 // The base type must be the same for all members. Vector types of the
4026 // same total size are treated as being equivalent here.
4027 const Type *TyPtr = Ty.getTypePtr();
4028 if (!Base)
4029 Base = TyPtr;
Oliver Stannard5e8558f2014-02-07 11:25:57 +00004030
4031 if (Base != TyPtr) {
4032 // Homogeneous aggregates are defined as containing members with the
4033 // same machine type. There are two cases in which two members have
4034 // different TypePtrs but the same machine type:
4035
4036 // 1) Vectors of the same length, regardless of the type and number
4037 // of their members.
4038 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
4039 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4040
4041 // 2) In the 32-bit AAPCS, `double' and `long double' have the same
4042 // machine type. This is not the case for the 64-bit AAPCS.
4043 const bool SameSizeDoubles =
4044 ( ( Base->isSpecificBuiltinType(BuiltinType::Double)
4045 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
4046 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble)
4047 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
4048 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4049
4050 if (!SameLengthVectors && !SameSizeDoubles)
4051 return false;
4052 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004053 }
4054
4055 // Homogeneous Aggregates can have at most 4 members of the base type.
4056 if (HAMembers)
4057 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004058
4059 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00004060}
4061
Manman Renb505d332012-10-31 19:02:26 +00004062/// markAllocatedVFPs - update VFPRegs according to the alignment and
4063/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004064void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4065 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004066 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004067 if (AllocatedVFPs >= 16) {
4068 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4069 // the stack.
4070 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004071 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004072 }
Manman Renb505d332012-10-31 19:02:26 +00004073 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4074 // VFP registers of the appropriate type unallocated then the argument is
4075 // allocated to the lowest-numbered sequence of such registers.
4076 for (unsigned I = 0; I < 16; I += Alignment) {
4077 bool FoundSlot = true;
4078 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4079 if (J >= 16 || VFPRegs[J]) {
4080 FoundSlot = false;
4081 break;
4082 }
4083 if (FoundSlot) {
4084 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4085 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004086 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004087 return;
4088 }
4089 }
4090 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4091 // unallocated are marked as unavailable.
4092 for (unsigned I = 0; I < 16; I++)
4093 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004094 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004095}
4096
Oliver Stannard405bded2014-02-11 09:25:50 +00004097/// Update AllocatedGPRs to record the number of general purpose registers
4098/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4099/// this represents arguments being stored on the stack.
4100void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
4101 unsigned NumRequired) const {
4102 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4103
4104 if (Alignment == 2 && AllocatedGPRs & 0x1)
4105 AllocatedGPRs += 1;
4106
4107 AllocatedGPRs += NumRequired;
4108}
4109
4110void ARMABIInfo::resetAllocatedRegs(void) const {
4111 AllocatedGPRs = 0;
4112 AllocatedVFPs = 0;
4113 for (unsigned i = 0; i < NumVFPs; ++i)
4114 VFPRegs[i] = 0;
4115}
4116
4117ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool &IsHA,
4118 bool isVariadic,
4119 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004120 // We update number of allocated VFPs according to
4121 // 6.1.2.1 The following argument types are VFP CPRCs:
4122 // A single-precision floating-point type (including promoted
4123 // half-precision types); A double-precision floating-point type;
4124 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4125 // with a Base Type of a single- or double-precision floating-point type,
4126 // 64-bit containerized vectors or 128-bit containerized vectors with one
4127 // to four Elements.
4128
Manman Renfef9e312012-10-16 19:18:39 +00004129 // Handle illegal vector types here.
4130 if (isIllegalVectorType(Ty)) {
4131 uint64_t Size = getContext().getTypeSize(Ty);
4132 if (Size <= 32) {
4133 llvm::Type *ResType =
4134 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004135 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004136 return ABIArgInfo::getDirect(ResType);
4137 }
4138 if (Size == 64) {
4139 llvm::Type *ResType = llvm::VectorType::get(
4140 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004141 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4142 markAllocatedGPRs(2, 2);
4143 } else {
4144 markAllocatedVFPs(2, 2);
4145 IsCPRC = true;
4146 }
Manman Renfef9e312012-10-16 19:18:39 +00004147 return ABIArgInfo::getDirect(ResType);
4148 }
4149 if (Size == 128) {
4150 llvm::Type *ResType = llvm::VectorType::get(
4151 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004152 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4153 markAllocatedGPRs(2, 4);
4154 } else {
4155 markAllocatedVFPs(4, 4);
4156 IsCPRC = true;
4157 }
Manman Renfef9e312012-10-16 19:18:39 +00004158 return ABIArgInfo::getDirect(ResType);
4159 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004160 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004161 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4162 }
Manman Renb505d332012-10-31 19:02:26 +00004163 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004164 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4165 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4166 uint64_t Size = getContext().getTypeSize(VT);
4167 // Size of a legal vector should be power of 2 and above 64.
4168 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4169 IsCPRC = true;
4170 }
Manman Ren2a523d82012-10-30 23:21:41 +00004171 }
Manman Renb505d332012-10-31 19:02:26 +00004172 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004173 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4174 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4175 if (BT->getKind() == BuiltinType::Half ||
4176 BT->getKind() == BuiltinType::Float) {
4177 markAllocatedVFPs(1, 1);
4178 IsCPRC = true;
4179 }
4180 if (BT->getKind() == BuiltinType::Double ||
4181 BT->getKind() == BuiltinType::LongDouble) {
4182 markAllocatedVFPs(2, 2);
4183 IsCPRC = true;
4184 }
4185 }
Manman Ren2a523d82012-10-30 23:21:41 +00004186 }
Manman Renfef9e312012-10-16 19:18:39 +00004187
John McCalla1dee5302010-08-22 10:59:02 +00004188 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004189 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004190 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004191 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004192 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004193
Oliver Stannard405bded2014-02-11 09:25:50 +00004194 unsigned Size = getContext().getTypeSize(Ty);
4195 if (!IsCPRC)
4196 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00004197 return (Ty->isPromotableIntegerType() ?
4198 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004199 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004200
Oliver Stannard405bded2014-02-11 09:25:50 +00004201 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4202 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004203 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004204 }
Tim Northover1060eae2013-06-21 22:49:34 +00004205
Daniel Dunbar09d33622009-09-14 21:54:03 +00004206 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004207 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004208 return ABIArgInfo::getIgnore();
4209
Amara Emerson9dc78782014-01-28 10:56:36 +00004210 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
Manman Ren2a523d82012-10-30 23:21:41 +00004211 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4212 // into VFP registers.
Bob Wilsone826a2a2011-08-03 05:58:22 +00004213 const Type *Base = 0;
Manman Ren2a523d82012-10-30 23:21:41 +00004214 uint64_t Members = 0;
4215 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004216 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004217 // Base can be a floating-point or a vector.
4218 if (Base->isVectorType()) {
4219 // ElementSize is in number of floats.
4220 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004221 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004222 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004223 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004224 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004225 else {
4226 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4227 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004228 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004229 }
4230 IsHA = true;
Oliver Stannard405bded2014-02-11 09:25:50 +00004231 IsCPRC = true;
Bob Wilsone826a2a2011-08-03 05:58:22 +00004232 return ABIArgInfo::getExpand();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004233 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004234 }
4235
Manman Ren6c30e132012-08-13 21:23:55 +00004236 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004237 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4238 // most 8-byte. We realign the indirect argument if type alignment is bigger
4239 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004240 uint64_t ABIAlign = 4;
4241 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4242 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4243 getABIKind() == ARMABIInfo::AAPCS)
4244 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004245 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004246 // Update Allocated GPRs
4247 markAllocatedGPRs(1, 1);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004248 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004249 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004250 }
4251
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004252 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004253 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004254 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004255 // FIXME: Try to match the types of the arguments more accurately where
4256 // we can.
4257 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004258 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4259 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004260 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004261 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004262 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4263 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004264 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004265 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004266
Chris Lattnera5f58b02011-07-09 17:41:47 +00004267 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00004268 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastings4b214952011-04-28 18:16:06 +00004269 return ABIArgInfo::getDirect(STy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004270}
4271
Chris Lattner458b2aa2010-07-29 02:16:43 +00004272static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004273 llvm::LLVMContext &VMContext) {
4274 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4275 // is called integer-like if its size is less than or equal to one word, and
4276 // the offset of each of its addressable sub-fields is zero.
4277
4278 uint64_t Size = Context.getTypeSize(Ty);
4279
4280 // Check that the type fits in a word.
4281 if (Size > 32)
4282 return false;
4283
4284 // FIXME: Handle vector types!
4285 if (Ty->isVectorType())
4286 return false;
4287
Daniel Dunbard53bac72009-09-14 02:20:34 +00004288 // Float types are never treated as "integer like".
4289 if (Ty->isRealFloatingType())
4290 return false;
4291
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004292 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004293 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004294 return true;
4295
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004296 // Small complex integer types are "integer like".
4297 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4298 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004299
4300 // Single element and zero sized arrays should be allowed, by the definition
4301 // above, but they are not.
4302
4303 // Otherwise, it must be a record type.
4304 const RecordType *RT = Ty->getAs<RecordType>();
4305 if (!RT) return false;
4306
4307 // Ignore records with flexible arrays.
4308 const RecordDecl *RD = RT->getDecl();
4309 if (RD->hasFlexibleArrayMember())
4310 return false;
4311
4312 // Check that all sub-fields are at offset 0, and are themselves "integer
4313 // like".
4314 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4315
4316 bool HadField = false;
4317 unsigned idx = 0;
4318 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4319 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004320 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004321
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004322 // Bit-fields are not addressable, we only need to verify they are "integer
4323 // like". We still have to disallow a subsequent non-bitfield, for example:
4324 // struct { int : 0; int x }
4325 // is non-integer like according to gcc.
4326 if (FD->isBitField()) {
4327 if (!RD->isUnion())
4328 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004329
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004330 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4331 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004332
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004333 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004334 }
4335
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004336 // Check if this field is at offset 0.
4337 if (Layout.getFieldOffset(idx) != 0)
4338 return false;
4339
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004340 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4341 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004342
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004343 // Only allow at most one field in a structure. This doesn't match the
4344 // wording above, but follows gcc in situations with a field following an
4345 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004346 if (!RD->isUnion()) {
4347 if (HadField)
4348 return false;
4349
4350 HadField = true;
4351 }
4352 }
4353
4354 return true;
4355}
4356
Oliver Stannard405bded2014-02-11 09:25:50 +00004357ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4358 bool isVariadic) const {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004359 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004360 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004361
Daniel Dunbar19964db2010-09-23 01:54:32 +00004362 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004363 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4364 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004365 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004366 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004367
John McCalla1dee5302010-08-22 10:59:02 +00004368 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004369 // Treat an enum type as its underlying type.
4370 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4371 RetTy = EnumTy->getDecl()->getIntegerType();
4372
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00004373 return (RetTy->isPromotableIntegerType() ?
4374 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004375 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004376
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00004377 // Structures with either a non-trivial destructor or a non-trivial
4378 // copy constructor are always indirect.
Oliver Stannard405bded2014-02-11 09:25:50 +00004379 if (isRecordReturnIndirect(RetTy, getCXXABI())) {
4380 markAllocatedGPRs(1, 1);
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00004381 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Oliver Stannard405bded2014-02-11 09:25:50 +00004382 }
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00004383
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004384 // Are we following APCS?
4385 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004386 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004387 return ABIArgInfo::getIgnore();
4388
Daniel Dunbareedf1512010-02-01 23:31:19 +00004389 // Complex types are all returned as packed integers.
4390 //
4391 // FIXME: Consider using 2 x vector types if the back end handles them
4392 // correctly.
4393 if (RetTy->isAnyComplexType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004394 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00004395 getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004396
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004397 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004398 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004399 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004400 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004401 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004402 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004403 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004404 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4405 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004406 }
4407
4408 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004409 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004410 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004411 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004412
4413 // Otherwise this is an AAPCS variant.
4414
Chris Lattner458b2aa2010-07-29 02:16:43 +00004415 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004416 return ABIArgInfo::getIgnore();
4417
Bob Wilson1d9269a2011-11-02 04:51:36 +00004418 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00004419 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Bob Wilson1d9269a2011-11-02 04:51:36 +00004420 const Type *Base = 0;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004421 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
4422 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004423 // Homogeneous Aggregates are returned directly.
4424 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004425 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004426 }
4427
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004428 // Aggregates <= 4 bytes are returned in r0; other aggregates
4429 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004430 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004431 if (Size <= 32) {
4432 // Return in the smallest viable integer type.
4433 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004434 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004435 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004436 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4437 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004438 }
4439
Oliver Stannard405bded2014-02-11 09:25:50 +00004440 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004441 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004442}
4443
Manman Renfef9e312012-10-16 19:18:39 +00004444/// isIllegalVector - check whether Ty is an illegal vector type.
4445bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4446 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4447 // Check whether VT is legal.
4448 unsigned NumElements = VT->getNumElements();
4449 uint64_t Size = getContext().getTypeSize(VT);
4450 // NumElements should be power of 2.
4451 if ((NumElements & (NumElements - 1)) != 0)
4452 return true;
4453 // Size should be greater than 32 bits.
4454 return Size <= 32;
4455 }
4456 return false;
4457}
4458
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004459llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004460 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004461 llvm::Type *BP = CGF.Int8PtrTy;
4462 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004463
4464 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004465 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004466 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004467
Tim Northover1711cc92013-06-21 23:05:33 +00004468 if (isEmptyRecord(getContext(), Ty, true)) {
4469 // These are ignored for parameter passing purposes.
4470 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4471 return Builder.CreateBitCast(Addr, PTy);
4472 }
4473
Manman Rencca54d02012-10-16 19:01:37 +00004474 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004475 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004476 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004477
4478 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4479 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004480 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4481 getABIKind() == ARMABIInfo::AAPCS)
4482 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4483 else
4484 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004485 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4486 if (isIllegalVectorType(Ty) && Size > 16) {
4487 IsIndirect = true;
4488 Size = 4;
4489 TyAlign = 4;
4490 }
Manman Rencca54d02012-10-16 19:01:37 +00004491
4492 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004493 if (TyAlign > 4) {
4494 assert((TyAlign & (TyAlign - 1)) == 0 &&
4495 "Alignment is not power of 2!");
4496 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4497 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4498 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004499 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004500 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004501
4502 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004503 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004504 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004505 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004506 "ap.next");
4507 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4508
Manman Renfef9e312012-10-16 19:18:39 +00004509 if (IsIndirect)
4510 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004511 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004512 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4513 // may not be correctly aligned for the vector type. We create an aligned
4514 // temporary space and copy the content over from ap.cur to the temporary
4515 // space. This is necessary if the natural alignment of the type is greater
4516 // than the ABI alignment.
4517 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4518 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4519 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4520 "var.align");
4521 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4522 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4523 Builder.CreateMemCpy(Dst, Src,
4524 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4525 TyAlign, false);
4526 Addr = AlignedTemp; //The content is in aligned location.
4527 }
4528 llvm::Type *PTy =
4529 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4530 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4531
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004532 return AddrTyped;
4533}
4534
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004535namespace {
4536
Derek Schuffa2020962012-10-16 22:30:41 +00004537class NaClARMABIInfo : public ABIInfo {
4538 public:
4539 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4540 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004541 void computeInfo(CGFunctionInfo &FI) const override;
4542 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4543 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00004544 private:
4545 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
4546 ARMABIInfo NInfo; // Used for everything else.
4547};
4548
4549class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
4550 public:
4551 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4552 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
4553};
4554
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004555}
4556
Derek Schuffa2020962012-10-16 22:30:41 +00004557void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4558 if (FI.getASTCallingConvention() == CC_PnaclCall)
4559 PInfo.computeInfo(FI);
4560 else
4561 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
4562}
4563
4564llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4565 CodeGenFunction &CGF) const {
4566 // Always use the native convention; calling pnacl-style varargs functions
4567 // is unsupported.
4568 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
4569}
4570
Chris Lattner0cf24192010-06-28 20:05:43 +00004571//===----------------------------------------------------------------------===//
Tim Northover9bb857a2013-01-31 12:13:10 +00004572// AArch64 ABI Implementation
4573//===----------------------------------------------------------------------===//
4574
4575namespace {
4576
4577class AArch64ABIInfo : public ABIInfo {
4578public:
4579 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4580
4581private:
4582 // The AArch64 PCS is explicit about return types and argument types being
4583 // handled identically, so we don't need to draw a distinction between
4584 // Argument and Return classification.
4585 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
4586 int &FreeVFPRegs) const;
4587
4588 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
4589 llvm::Type *DirectTy = 0) const;
4590
Craig Topper4f12f102014-03-12 06:41:41 +00004591 void computeInfo(CGFunctionInfo &FI) const override;
Tim Northover9bb857a2013-01-31 12:13:10 +00004592
Craig Topper4f12f102014-03-12 06:41:41 +00004593 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4594 CodeGenFunction &CGF) const override;
Tim Northover9bb857a2013-01-31 12:13:10 +00004595};
4596
4597class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
4598public:
4599 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
4600 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
4601
4602 const AArch64ABIInfo &getABIInfo() const {
4603 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
4604 }
4605
Craig Topper4f12f102014-03-12 06:41:41 +00004606 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tim Northover9bb857a2013-01-31 12:13:10 +00004607 return 31;
4608 }
4609
4610 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004611 llvm::Value *Address) const override {
Tim Northover9bb857a2013-01-31 12:13:10 +00004612 // 0-31 are x0-x30 and sp: 8 bytes each
4613 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
4614 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
4615
4616 // 64-95 are v0-v31: 16 bytes each
4617 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
4618 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
4619
4620 return false;
4621 }
4622
4623};
4624
4625}
4626
4627void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4628 int FreeIntRegs = 8, FreeVFPRegs = 8;
4629
4630 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
4631 FreeIntRegs, FreeVFPRegs);
4632
4633 FreeIntRegs = FreeVFPRegs = 8;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004634 for (auto &I : FI.arguments()) {
4635 I.info = classifyGenericType(I.type, FreeIntRegs, FreeVFPRegs);
Tim Northover9bb857a2013-01-31 12:13:10 +00004636
4637 }
4638}
4639
4640ABIArgInfo
4641AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
4642 bool IsInt, llvm::Type *DirectTy) const {
4643 if (FreeRegs >= RegsNeeded) {
4644 FreeRegs -= RegsNeeded;
4645 return ABIArgInfo::getDirect(DirectTy);
4646 }
4647
4648 llvm::Type *Padding = 0;
4649
4650 // We need padding so that later arguments don't get filled in anyway. That
4651 // wouldn't happen if only ByVal arguments followed in the same category, but
4652 // a large structure will simply seem to be a pointer as far as LLVM is
4653 // concerned.
4654 if (FreeRegs > 0) {
4655 if (IsInt)
4656 Padding = llvm::Type::getInt64Ty(getVMContext());
4657 else
4658 Padding = llvm::Type::getFloatTy(getVMContext());
4659
4660 // Either [N x i64] or [N x float].
4661 Padding = llvm::ArrayType::get(Padding, FreeRegs);
4662 FreeRegs = 0;
4663 }
4664
4665 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
4666 /*IsByVal=*/ true, /*Realign=*/ false,
4667 Padding);
4668}
4669
4670
4671ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
4672 int &FreeIntRegs,
4673 int &FreeVFPRegs) const {
4674 // Can only occurs for return, but harmless otherwise.
4675 if (Ty->isVoidType())
4676 return ABIArgInfo::getIgnore();
4677
4678 // Large vector types should be returned via memory. There's no such concept
4679 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
4680 // classified they'd go into memory (see B.3).
4681 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
4682 if (FreeIntRegs > 0)
4683 --FreeIntRegs;
4684 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4685 }
4686
4687 // All non-aggregate LLVM types have a concrete ABI representation so they can
4688 // be passed directly. After this block we're guaranteed to be in a
4689 // complicated case.
4690 if (!isAggregateTypeForABI(Ty)) {
4691 // Treat an enum type as its underlying type.
4692 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4693 Ty = EnumTy->getDecl()->getIntegerType();
4694
4695 if (Ty->isFloatingType() || Ty->isVectorType())
4696 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
4697
4698 assert(getContext().getTypeSize(Ty) <= 128 &&
4699 "unexpectedly large scalar type");
4700
4701 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
4702
4703 // If the type may need padding registers to ensure "alignment", we must be
4704 // careful when this is accounted for. Increasing the effective size covers
4705 // all cases.
4706 if (getContext().getTypeAlign(Ty) == 128)
4707 RegsNeeded += FreeIntRegs % 2 != 0;
4708
4709 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
4710 }
4711
Mark Lacey3825e832013-10-06 01:33:34 +00004712 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004713 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northover9bb857a2013-01-31 12:13:10 +00004714 --FreeIntRegs;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004715 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northover9bb857a2013-01-31 12:13:10 +00004716 }
4717
4718 if (isEmptyRecord(getContext(), Ty, true)) {
4719 if (!getContext().getLangOpts().CPlusPlus) {
4720 // Empty structs outside C++ mode are a GNU extension, so no ABI can
4721 // possibly tell us what to do. It turns out (I believe) that GCC ignores
4722 // the object for parameter-passsing purposes.
4723 return ABIArgInfo::getIgnore();
4724 }
4725
4726 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
4727 // description of va_arg in the PCS require that an empty struct does
4728 // actually occupy space for parameter-passing. I'm hoping for a
4729 // clarification giving an explicit paragraph to point to in future.
4730 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
4731 llvm::Type::getInt8Ty(getVMContext()));
4732 }
4733
4734 // Homogeneous vector aggregates get passed in registers or on the stack.
4735 const Type *Base = 0;
4736 uint64_t NumMembers = 0;
4737 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
4738 assert(Base && "Base class should be set for homogeneous aggregate");
4739 // Homogeneous aggregates are passed and returned directly.
4740 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
4741 /*IsInt=*/ false);
4742 }
4743
4744 uint64_t Size = getContext().getTypeSize(Ty);
4745 if (Size <= 128) {
4746 // Small structs can use the same direct type whether they're in registers
4747 // or on the stack.
4748 llvm::Type *BaseTy;
4749 unsigned NumBases;
4750 int SizeInRegs = (Size + 63) / 64;
4751
4752 if (getContext().getTypeAlign(Ty) == 128) {
4753 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
4754 NumBases = 1;
4755
4756 // If the type may need padding registers to ensure "alignment", we must
4757 // be careful when this is accounted for. Increasing the effective size
4758 // covers all cases.
4759 SizeInRegs += FreeIntRegs % 2 != 0;
4760 } else {
4761 BaseTy = llvm::Type::getInt64Ty(getVMContext());
4762 NumBases = SizeInRegs;
4763 }
4764 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
4765
4766 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
4767 /*IsInt=*/ true, DirectTy);
4768 }
4769
4770 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
4771 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
4772 --FreeIntRegs;
4773 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
4774}
4775
4776llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4777 CodeGenFunction &CGF) const {
Tim Northover9bb857a2013-01-31 12:13:10 +00004778 int FreeIntRegs = 8, FreeVFPRegs = 8;
4779 Ty = CGF.getContext().getCanonicalType(Ty);
4780 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
4781
Tim Northovera2ee4332014-03-29 15:09:45 +00004782 return EmitAArch64VAArg(VAListAddr, Ty, 8 - FreeIntRegs, 8 - FreeVFPRegs,
4783 AI.isIndirect(), CGF);
Tim Northover9bb857a2013-01-31 12:13:10 +00004784}
4785
4786//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004787// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004788//===----------------------------------------------------------------------===//
4789
4790namespace {
4791
Justin Holewinski83e96682012-05-24 17:43:12 +00004792class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004793public:
Justin Holewinski36837432013-03-30 14:38:24 +00004794 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004795
4796 ABIArgInfo classifyReturnType(QualType RetTy) const;
4797 ABIArgInfo classifyArgumentType(QualType Ty) const;
4798
Craig Topper4f12f102014-03-12 06:41:41 +00004799 void computeInfo(CGFunctionInfo &FI) const override;
4800 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4801 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004802};
4803
Justin Holewinski83e96682012-05-24 17:43:12 +00004804class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004805public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004806 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4807 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004808
4809 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4810 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00004811private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00004812 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
4813 // resulting MDNode to the nvvm.annotations MDNode.
4814 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004815};
4816
Justin Holewinski83e96682012-05-24 17:43:12 +00004817ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004818 if (RetTy->isVoidType())
4819 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004820
4821 // note: this is different from default ABI
4822 if (!RetTy->isScalarType())
4823 return ABIArgInfo::getDirect();
4824
4825 // Treat an enum type as its underlying type.
4826 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4827 RetTy = EnumTy->getDecl()->getIntegerType();
4828
4829 return (RetTy->isPromotableIntegerType() ?
4830 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004831}
4832
Justin Holewinski83e96682012-05-24 17:43:12 +00004833ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004834 // Treat an enum type as its underlying type.
4835 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4836 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004837
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004838 return (Ty->isPromotableIntegerType() ?
4839 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004840}
4841
Justin Holewinski83e96682012-05-24 17:43:12 +00004842void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004843 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004844 for (auto &I : FI.arguments())
4845 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004846
4847 // Always honor user-specified calling convention.
4848 if (FI.getCallingConvention() != llvm::CallingConv::C)
4849 return;
4850
John McCall882987f2013-02-28 19:01:20 +00004851 FI.setEffectiveCallingConvention(getRuntimeCC());
4852}
4853
Justin Holewinski83e96682012-05-24 17:43:12 +00004854llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4855 CodeGenFunction &CFG) const {
4856 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004857}
4858
Justin Holewinski83e96682012-05-24 17:43:12 +00004859void NVPTXTargetCodeGenInfo::
4860SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4861 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004862 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4863 if (!FD) return;
4864
4865 llvm::Function *F = cast<llvm::Function>(GV);
4866
4867 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004868 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004869 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004870 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004871 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004872 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00004873 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4874 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00004875 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004876 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004877 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004878 }
Justin Holewinski38031972011-10-05 17:58:44 +00004879
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004880 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004881 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004882 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004883 // __global__ functions cannot be called from the device, we do not
4884 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00004885 if (FD->hasAttr<CUDAGlobalAttr>()) {
4886 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4887 addNVVMMetadata(F, "kernel", 1);
4888 }
4889 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
4890 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
4891 addNVVMMetadata(F, "maxntidx",
4892 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
4893 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
4894 // zero value from getMinBlocks either means it was not specified in
4895 // __launch_bounds__ or the user specified a 0 value. In both cases, we
4896 // don't have to add a PTX directive.
4897 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
4898 if (MinCTASM > 0) {
4899 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
4900 addNVVMMetadata(F, "minctasm", MinCTASM);
4901 }
4902 }
Justin Holewinski38031972011-10-05 17:58:44 +00004903 }
4904}
4905
Eli Benderskye06a2c42014-04-15 16:57:05 +00004906void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
4907 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00004908 llvm::Module *M = F->getParent();
4909 llvm::LLVMContext &Ctx = M->getContext();
4910
4911 // Get "nvvm.annotations" metadata node
4912 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4913
Eli Benderskye1627b42014-04-15 17:19:26 +00004914 llvm::Value *MDVals[] = {
4915 F, llvm::MDString::get(Ctx, Name),
4916 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
Justin Holewinski36837432013-03-30 14:38:24 +00004917 // Append metadata to nvvm.annotations
4918 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4919}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004920}
4921
4922//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00004923// SystemZ ABI Implementation
4924//===----------------------------------------------------------------------===//
4925
4926namespace {
4927
4928class SystemZABIInfo : public ABIInfo {
4929public:
4930 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4931
4932 bool isPromotableIntegerType(QualType Ty) const;
4933 bool isCompoundType(QualType Ty) const;
4934 bool isFPArgumentType(QualType Ty) const;
4935
4936 ABIArgInfo classifyReturnType(QualType RetTy) const;
4937 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4938
Craig Topper4f12f102014-03-12 06:41:41 +00004939 void computeInfo(CGFunctionInfo &FI) const override {
Ulrich Weigand47445072013-05-06 16:26:41 +00004940 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004941 for (auto &I : FI.arguments())
4942 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00004943 }
4944
Craig Topper4f12f102014-03-12 06:41:41 +00004945 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4946 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00004947};
4948
4949class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4950public:
4951 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4952 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4953};
4954
4955}
4956
4957bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4958 // Treat an enum type as its underlying type.
4959 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4960 Ty = EnumTy->getDecl()->getIntegerType();
4961
4962 // Promotable integer types are required to be promoted by the ABI.
4963 if (Ty->isPromotableIntegerType())
4964 return true;
4965
4966 // 32-bit values must also be promoted.
4967 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4968 switch (BT->getKind()) {
4969 case BuiltinType::Int:
4970 case BuiltinType::UInt:
4971 return true;
4972 default:
4973 return false;
4974 }
4975 return false;
4976}
4977
4978bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4979 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4980}
4981
4982bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4983 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4984 switch (BT->getKind()) {
4985 case BuiltinType::Float:
4986 case BuiltinType::Double:
4987 return true;
4988 default:
4989 return false;
4990 }
4991
4992 if (const RecordType *RT = Ty->getAsStructureType()) {
4993 const RecordDecl *RD = RT->getDecl();
4994 bool Found = false;
4995
4996 // If this is a C++ record, check the bases first.
4997 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00004998 for (const auto &I : CXXRD->bases()) {
4999 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005000
5001 // Empty bases don't affect things either way.
5002 if (isEmptyRecord(getContext(), Base, true))
5003 continue;
5004
5005 if (Found)
5006 return false;
5007 Found = isFPArgumentType(Base);
5008 if (!Found)
5009 return false;
5010 }
5011
5012 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005013 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005014 // Empty bitfields don't affect things either way.
5015 // Unlike isSingleElementStruct(), empty structure and array fields
5016 // do count. So do anonymous bitfields that aren't zero-sized.
5017 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5018 return true;
5019
5020 // Unlike isSingleElementStruct(), arrays do not count.
5021 // Nested isFPArgumentType structures still do though.
5022 if (Found)
5023 return false;
5024 Found = isFPArgumentType(FD->getType());
5025 if (!Found)
5026 return false;
5027 }
5028
5029 // Unlike isSingleElementStruct(), trailing padding is allowed.
5030 // An 8-byte aligned struct s { float f; } is passed as a double.
5031 return Found;
5032 }
5033
5034 return false;
5035}
5036
5037llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5038 CodeGenFunction &CGF) const {
5039 // Assume that va_list type is correct; should be pointer to LLVM type:
5040 // struct {
5041 // i64 __gpr;
5042 // i64 __fpr;
5043 // i8 *__overflow_arg_area;
5044 // i8 *__reg_save_area;
5045 // };
5046
5047 // Every argument occupies 8 bytes and is passed by preference in either
5048 // GPRs or FPRs.
5049 Ty = CGF.getContext().getCanonicalType(Ty);
5050 ABIArgInfo AI = classifyArgumentType(Ty);
5051 bool InFPRs = isFPArgumentType(Ty);
5052
5053 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5054 bool IsIndirect = AI.isIndirect();
5055 unsigned UnpaddedBitSize;
5056 if (IsIndirect) {
5057 APTy = llvm::PointerType::getUnqual(APTy);
5058 UnpaddedBitSize = 64;
5059 } else
5060 UnpaddedBitSize = getContext().getTypeSize(Ty);
5061 unsigned PaddedBitSize = 64;
5062 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5063
5064 unsigned PaddedSize = PaddedBitSize / 8;
5065 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5066
5067 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5068 if (InFPRs) {
5069 MaxRegs = 4; // Maximum of 4 FPR arguments
5070 RegCountField = 1; // __fpr
5071 RegSaveIndex = 16; // save offset for f0
5072 RegPadding = 0; // floats are passed in the high bits of an FPR
5073 } else {
5074 MaxRegs = 5; // Maximum of 5 GPR arguments
5075 RegCountField = 0; // __gpr
5076 RegSaveIndex = 2; // save offset for r2
5077 RegPadding = Padding; // values are passed in the low bits of a GPR
5078 }
5079
5080 llvm::Value *RegCountPtr =
5081 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5082 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5083 llvm::Type *IndexTy = RegCount->getType();
5084 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5085 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005086 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005087
5088 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5089 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5090 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5091 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5092
5093 // Emit code to load the value if it was passed in registers.
5094 CGF.EmitBlock(InRegBlock);
5095
5096 // Work out the address of an argument register.
5097 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5098 llvm::Value *ScaledRegCount =
5099 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5100 llvm::Value *RegBase =
5101 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5102 llvm::Value *RegOffset =
5103 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5104 llvm::Value *RegSaveAreaPtr =
5105 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5106 llvm::Value *RegSaveArea =
5107 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5108 llvm::Value *RawRegAddr =
5109 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5110 llvm::Value *RegAddr =
5111 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5112
5113 // Update the register count
5114 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5115 llvm::Value *NewRegCount =
5116 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5117 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5118 CGF.EmitBranch(ContBlock);
5119
5120 // Emit code to load the value if it was passed in memory.
5121 CGF.EmitBlock(InMemBlock);
5122
5123 // Work out the address of a stack argument.
5124 llvm::Value *OverflowArgAreaPtr =
5125 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5126 llvm::Value *OverflowArgArea =
5127 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5128 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5129 llvm::Value *RawMemAddr =
5130 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5131 llvm::Value *MemAddr =
5132 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5133
5134 // Update overflow_arg_area_ptr pointer
5135 llvm::Value *NewOverflowArgArea =
5136 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5137 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5138 CGF.EmitBranch(ContBlock);
5139
5140 // Return the appropriate result.
5141 CGF.EmitBlock(ContBlock);
5142 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5143 ResAddr->addIncoming(RegAddr, InRegBlock);
5144 ResAddr->addIncoming(MemAddr, InMemBlock);
5145
5146 if (IsIndirect)
5147 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5148
5149 return ResAddr;
5150}
5151
John McCall1fe2a8c2013-06-18 02:46:29 +00005152bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
5153 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
5154 assert(Triple.getArch() == llvm::Triple::x86);
5155
5156 switch (Opts.getStructReturnConvention()) {
5157 case CodeGenOptions::SRCK_Default:
5158 break;
5159 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
5160 return false;
5161 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
5162 return true;
5163 }
5164
5165 if (Triple.isOSDarwin())
5166 return true;
5167
5168 switch (Triple.getOS()) {
John McCall1fe2a8c2013-06-18 02:46:29 +00005169 case llvm::Triple::AuroraUX:
5170 case llvm::Triple::DragonFly:
5171 case llvm::Triple::FreeBSD:
5172 case llvm::Triple::OpenBSD:
5173 case llvm::Triple::Bitrig:
John McCall1fe2a8c2013-06-18 02:46:29 +00005174 return true;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00005175 case llvm::Triple::Win32:
5176 switch (Triple.getEnvironment()) {
5177 case llvm::Triple::UnknownEnvironment:
5178 case llvm::Triple::Cygnus:
5179 case llvm::Triple::GNU:
5180 case llvm::Triple::MSVC:
5181 return true;
5182 default:
5183 return false;
5184 }
John McCall1fe2a8c2013-06-18 02:46:29 +00005185 default:
5186 return false;
5187 }
5188}
Ulrich Weigand47445072013-05-06 16:26:41 +00005189
5190ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5191 if (RetTy->isVoidType())
5192 return ABIArgInfo::getIgnore();
5193 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5194 return ABIArgInfo::getIndirect(0);
5195 return (isPromotableIntegerType(RetTy) ?
5196 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5197}
5198
5199ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5200 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005201 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005202 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5203
5204 // Integers and enums are extended to full register width.
5205 if (isPromotableIntegerType(Ty))
5206 return ABIArgInfo::getExtend();
5207
5208 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5209 uint64_t Size = getContext().getTypeSize(Ty);
5210 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005211 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005212
5213 // Handle small structures.
5214 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5215 // Structures with flexible arrays have variable length, so really
5216 // fail the size test above.
5217 const RecordDecl *RD = RT->getDecl();
5218 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005219 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005220
5221 // The structure is passed as an unextended integer, a float, or a double.
5222 llvm::Type *PassTy;
5223 if (isFPArgumentType(Ty)) {
5224 assert(Size == 32 || Size == 64);
5225 if (Size == 32)
5226 PassTy = llvm::Type::getFloatTy(getVMContext());
5227 else
5228 PassTy = llvm::Type::getDoubleTy(getVMContext());
5229 } else
5230 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5231 return ABIArgInfo::getDirect(PassTy);
5232 }
5233
5234 // Non-structure compounds are passed indirectly.
5235 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005236 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005237
5238 return ABIArgInfo::getDirect(0);
5239}
5240
5241//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005242// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005243//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005244
5245namespace {
5246
5247class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5248public:
Chris Lattner2b037972010-07-29 02:01:43 +00005249 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5250 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005251 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005252 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005253};
5254
5255}
5256
5257void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5258 llvm::GlobalValue *GV,
5259 CodeGen::CodeGenModule &M) const {
5260 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5261 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5262 // Handle 'interrupt' attribute:
5263 llvm::Function *F = cast<llvm::Function>(GV);
5264
5265 // Step 1: Set ISR calling convention.
5266 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5267
5268 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005269 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005270
5271 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005272 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005273 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005274 "__isr_" + Twine(Num),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005275 GV, &M.getModule());
5276 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005277 }
5278}
5279
Chris Lattner0cf24192010-06-28 20:05:43 +00005280//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005281// MIPS ABI Implementation. This works for both little-endian and
5282// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005283//===----------------------------------------------------------------------===//
5284
John McCall943fae92010-05-27 06:19:26 +00005285namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005286class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005287 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005288 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5289 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005290 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005291 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005292 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005293 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005294public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005295 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005296 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005297 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005298
5299 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005300 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005301 void computeInfo(CGFunctionInfo &FI) const override;
5302 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5303 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005304};
5305
John McCall943fae92010-05-27 06:19:26 +00005306class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005307 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005308public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005309 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5310 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005311 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005312
Craig Topper4f12f102014-03-12 06:41:41 +00005313 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005314 return 29;
5315 }
5316
Reed Kotler373feca2013-01-16 17:10:28 +00005317 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005318 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005319 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5320 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005321 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005322 if (FD->hasAttr<Mips16Attr>()) {
5323 Fn->addFnAttr("mips16");
5324 }
5325 else if (FD->hasAttr<NoMips16Attr>()) {
5326 Fn->addFnAttr("nomips16");
5327 }
Reed Kotler373feca2013-01-16 17:10:28 +00005328 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005329
John McCall943fae92010-05-27 06:19:26 +00005330 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005331 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005332
Craig Topper4f12f102014-03-12 06:41:41 +00005333 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005334 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005335 }
John McCall943fae92010-05-27 06:19:26 +00005336};
5337}
5338
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005339void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005340 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005341 llvm::IntegerType *IntTy =
5342 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005343
5344 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5345 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5346 ArgList.push_back(IntTy);
5347
5348 // If necessary, add one more integer type to ArgList.
5349 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5350
5351 if (R)
5352 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005353}
5354
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005355// In N32/64, an aligned double precision floating point field is passed in
5356// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005357llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005358 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5359
5360 if (IsO32) {
5361 CoerceToIntArgs(TySize, ArgList);
5362 return llvm::StructType::get(getVMContext(), ArgList);
5363 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005364
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005365 if (Ty->isComplexType())
5366 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005367
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005368 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005369
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005370 // Unions/vectors are passed in integer registers.
5371 if (!RT || !RT->isStructureOrClassType()) {
5372 CoerceToIntArgs(TySize, ArgList);
5373 return llvm::StructType::get(getVMContext(), ArgList);
5374 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005375
5376 const RecordDecl *RD = RT->getDecl();
5377 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005378 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005379
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005380 uint64_t LastOffset = 0;
5381 unsigned idx = 0;
5382 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5383
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005384 // Iterate over fields in the struct/class and check if there are any aligned
5385 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005386 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5387 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005388 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005389 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5390
5391 if (!BT || BT->getKind() != BuiltinType::Double)
5392 continue;
5393
5394 uint64_t Offset = Layout.getFieldOffset(idx);
5395 if (Offset % 64) // Ignore doubles that are not aligned.
5396 continue;
5397
5398 // Add ((Offset - LastOffset) / 64) args of type i64.
5399 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5400 ArgList.push_back(I64);
5401
5402 // Add double type.
5403 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5404 LastOffset = Offset + 64;
5405 }
5406
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005407 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5408 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005409
5410 return llvm::StructType::get(getVMContext(), ArgList);
5411}
5412
Akira Hatanakaddd66342013-10-29 18:41:15 +00005413llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5414 uint64_t Offset) const {
5415 if (OrigOffset + MinABIStackAlignInBytes > Offset)
5416 return 0;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005417
Akira Hatanakaddd66342013-10-29 18:41:15 +00005418 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005419}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005420
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005421ABIArgInfo
5422MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005423 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005424 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005425 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005426
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005427 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5428 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005429 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5430 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005431
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005432 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005433 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005434 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005435 return ABIArgInfo::getIgnore();
5436
Mark Lacey3825e832013-10-06 01:33:34 +00005437 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005438 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005439 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005440 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005441
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005442 // If we have reached here, aggregates are passed directly by coercing to
5443 // another structure type. Padding is inserted if the offset of the
5444 // aggregate is unaligned.
5445 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00005446 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005447 }
5448
5449 // Treat an enum type as its underlying type.
5450 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5451 Ty = EnumTy->getDecl()->getIntegerType();
5452
Akira Hatanaka1632af62012-01-09 19:31:25 +00005453 if (Ty->isPromotableIntegerType())
5454 return ABIArgInfo::getExtend();
5455
Akira Hatanakaddd66342013-10-29 18:41:15 +00005456 return ABIArgInfo::getDirect(
5457 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005458}
5459
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005460llvm::Type*
5461MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005462 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005463 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005464
Akira Hatanakab6f74432012-02-09 18:49:26 +00005465 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005466 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005467 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5468 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005469
Akira Hatanakab6f74432012-02-09 18:49:26 +00005470 // N32/64 returns struct/classes in floating point registers if the
5471 // following conditions are met:
5472 // 1. The size of the struct/class is no larger than 128-bit.
5473 // 2. The struct/class has one or two fields all of which are floating
5474 // point types.
5475 // 3. The offset of the first field is zero (this follows what gcc does).
5476 //
5477 // Any other composite results are returned in integer registers.
5478 //
5479 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5480 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5481 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005482 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005483
Akira Hatanakab6f74432012-02-09 18:49:26 +00005484 if (!BT || !BT->isFloatingPoint())
5485 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005486
David Blaikie2d7c57e2012-04-30 02:36:29 +00005487 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005488 }
5489
5490 if (b == e)
5491 return llvm::StructType::get(getVMContext(), RTList,
5492 RD->hasAttr<PackedAttr>());
5493
5494 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005495 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005496 }
5497
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005498 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005499 return llvm::StructType::get(getVMContext(), RTList);
5500}
5501
Akira Hatanakab579fe52011-06-02 00:09:17 +00005502ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005503 uint64_t Size = getContext().getTypeSize(RetTy);
5504
5505 if (RetTy->isVoidType() || Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005506 return ABIArgInfo::getIgnore();
5507
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005508 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey3825e832013-10-06 01:33:34 +00005509 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005510 return ABIArgInfo::getIndirect(0);
5511
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005512 if (Size <= 128) {
5513 if (RetTy->isAnyComplexType())
5514 return ABIArgInfo::getDirect();
5515
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005516 // O32 returns integer vectors in registers.
5517 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
5518 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5519
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005520 if (!IsO32)
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005521 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5522 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005523
5524 return ABIArgInfo::getIndirect(0);
5525 }
5526
5527 // Treat an enum type as its underlying type.
5528 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5529 RetTy = EnumTy->getDecl()->getIntegerType();
5530
5531 return (RetTy->isPromotableIntegerType() ?
5532 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5533}
5534
5535void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005536 ABIArgInfo &RetInfo = FI.getReturnInfo();
5537 RetInfo = classifyReturnType(FI.getReturnType());
5538
5539 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005540 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005541
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005542 for (auto &I : FI.arguments())
5543 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005544}
5545
5546llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5547 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00005548 llvm::Type *BP = CGF.Int8PtrTy;
5549 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005550
5551 CGBuilderTy &Builder = CGF.Builder;
5552 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5553 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka37715282012-01-23 23:59:52 +00005554 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005555 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5556 llvm::Value *AddrTyped;
John McCallc8e01702013-04-16 22:48:15 +00005557 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka37715282012-01-23 23:59:52 +00005558 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005559
5560 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka37715282012-01-23 23:59:52 +00005561 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5562 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5563 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5564 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005565 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5566 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5567 }
5568 else
5569 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5570
5571 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka37715282012-01-23 23:59:52 +00005572 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005573 uint64_t Offset =
5574 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5575 llvm::Value *NextAddr =
Akira Hatanaka37715282012-01-23 23:59:52 +00005576 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005577 "ap.next");
5578 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5579
5580 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005581}
5582
John McCall943fae92010-05-27 06:19:26 +00005583bool
5584MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5585 llvm::Value *Address) const {
5586 // This information comes from gcc's implementation, which seems to
5587 // as canonical as it gets.
5588
John McCall943fae92010-05-27 06:19:26 +00005589 // Everything on MIPS is 4 bytes. Double-precision FP registers
5590 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005591 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005592
5593 // 0-31 are the general purpose registers, $0 - $31.
5594 // 32-63 are the floating-point registers, $f0 - $f31.
5595 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5596 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005597 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005598
5599 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5600 // They are one bit wide and ignored here.
5601
5602 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5603 // (coprocessor 1 is the FP unit)
5604 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5605 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5606 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005607 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005608 return false;
5609}
5610
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005611//===----------------------------------------------------------------------===//
5612// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5613// Currently subclassed only to implement custom OpenCL C function attribute
5614// handling.
5615//===----------------------------------------------------------------------===//
5616
5617namespace {
5618
5619class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5620public:
5621 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5622 : DefaultTargetCodeGenInfo(CGT) {}
5623
Craig Topper4f12f102014-03-12 06:41:41 +00005624 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5625 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005626};
5627
5628void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5629 llvm::GlobalValue *GV,
5630 CodeGen::CodeGenModule &M) const {
5631 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5632 if (!FD) return;
5633
5634 llvm::Function *F = cast<llvm::Function>(GV);
5635
David Blaikiebbafb8a2012-03-11 07:00:24 +00005636 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005637 if (FD->hasAttr<OpenCLKernelAttr>()) {
5638 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005639 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005640 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5641 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005642 // Convert the reqd_work_group_size() attributes to metadata.
5643 llvm::LLVMContext &Context = F->getContext();
5644 llvm::NamedMDNode *OpenCLMetadata =
5645 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5646
5647 SmallVector<llvm::Value*, 5> Operands;
5648 Operands.push_back(F);
5649
Chris Lattnerece04092012-02-07 00:39:47 +00005650 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005651 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005652 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005653 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005654 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005655 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005656
5657 // Add a boolean constant operand for "required" (true) or "hint" (false)
5658 // for implementing the work_group_size_hint attr later. Currently
5659 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005660 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005661 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5662 }
5663 }
5664 }
5665}
5666
5667}
John McCall943fae92010-05-27 06:19:26 +00005668
Tony Linthicum76329bf2011-12-12 21:14:55 +00005669//===----------------------------------------------------------------------===//
5670// Hexagon ABI Implementation
5671//===----------------------------------------------------------------------===//
5672
5673namespace {
5674
5675class HexagonABIInfo : public ABIInfo {
5676
5677
5678public:
5679 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5680
5681private:
5682
5683 ABIArgInfo classifyReturnType(QualType RetTy) const;
5684 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5685
Craig Topper4f12f102014-03-12 06:41:41 +00005686 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005687
Craig Topper4f12f102014-03-12 06:41:41 +00005688 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5689 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005690};
5691
5692class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5693public:
5694 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5695 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5696
Craig Topper4f12f102014-03-12 06:41:41 +00005697 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005698 return 29;
5699 }
5700};
5701
5702}
5703
5704void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5705 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005706 for (auto &I : FI.arguments())
5707 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005708}
5709
5710ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5711 if (!isAggregateTypeForABI(Ty)) {
5712 // Treat an enum type as its underlying type.
5713 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5714 Ty = EnumTy->getDecl()->getIntegerType();
5715
5716 return (Ty->isPromotableIntegerType() ?
5717 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5718 }
5719
5720 // Ignore empty records.
5721 if (isEmptyRecord(getContext(), Ty, true))
5722 return ABIArgInfo::getIgnore();
5723
Mark Lacey3825e832013-10-06 01:33:34 +00005724 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005725 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005726
5727 uint64_t Size = getContext().getTypeSize(Ty);
5728 if (Size > 64)
5729 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5730 // Pass in the smallest viable integer type.
5731 else if (Size > 32)
5732 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5733 else if (Size > 16)
5734 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5735 else if (Size > 8)
5736 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5737 else
5738 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5739}
5740
5741ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5742 if (RetTy->isVoidType())
5743 return ABIArgInfo::getIgnore();
5744
5745 // Large vector types should be returned via memory.
5746 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5747 return ABIArgInfo::getIndirect(0);
5748
5749 if (!isAggregateTypeForABI(RetTy)) {
5750 // Treat an enum type as its underlying type.
5751 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5752 RetTy = EnumTy->getDecl()->getIntegerType();
5753
5754 return (RetTy->isPromotableIntegerType() ?
5755 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5756 }
5757
5758 // Structures with either a non-trivial destructor or a non-trivial
5759 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00005760 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum76329bf2011-12-12 21:14:55 +00005761 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5762
5763 if (isEmptyRecord(getContext(), RetTy, true))
5764 return ABIArgInfo::getIgnore();
5765
5766 // Aggregates <= 8 bytes are returned in r0; other aggregates
5767 // are returned indirectly.
5768 uint64_t Size = getContext().getTypeSize(RetTy);
5769 if (Size <= 64) {
5770 // Return in the smallest viable integer type.
5771 if (Size <= 8)
5772 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5773 if (Size <= 16)
5774 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5775 if (Size <= 32)
5776 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5777 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5778 }
5779
5780 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5781}
5782
5783llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005784 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005785 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005786 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005787
5788 CGBuilderTy &Builder = CGF.Builder;
5789 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5790 "ap");
5791 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5792 llvm::Type *PTy =
5793 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5794 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5795
5796 uint64_t Offset =
5797 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5798 llvm::Value *NextAddr =
5799 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5800 "ap.next");
5801 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5802
5803 return AddrTyped;
5804}
5805
5806
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005807//===----------------------------------------------------------------------===//
5808// SPARC v9 ABI Implementation.
5809// Based on the SPARC Compliance Definition version 2.4.1.
5810//
5811// Function arguments a mapped to a nominal "parameter array" and promoted to
5812// registers depending on their type. Each argument occupies 8 or 16 bytes in
5813// the array, structs larger than 16 bytes are passed indirectly.
5814//
5815// One case requires special care:
5816//
5817// struct mixed {
5818// int i;
5819// float f;
5820// };
5821//
5822// When a struct mixed is passed by value, it only occupies 8 bytes in the
5823// parameter array, but the int is passed in an integer register, and the float
5824// is passed in a floating point register. This is represented as two arguments
5825// with the LLVM IR inreg attribute:
5826//
5827// declare void f(i32 inreg %i, float inreg %f)
5828//
5829// The code generator will only allocate 4 bytes from the parameter array for
5830// the inreg arguments. All other arguments are allocated a multiple of 8
5831// bytes.
5832//
5833namespace {
5834class SparcV9ABIInfo : public ABIInfo {
5835public:
5836 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5837
5838private:
5839 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005840 void computeInfo(CGFunctionInfo &FI) const override;
5841 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5842 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005843
5844 // Coercion type builder for structs passed in registers. The coercion type
5845 // serves two purposes:
5846 //
5847 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5848 // in registers.
5849 // 2. Expose aligned floating point elements as first-level elements, so the
5850 // code generator knows to pass them in floating point registers.
5851 //
5852 // We also compute the InReg flag which indicates that the struct contains
5853 // aligned 32-bit floats.
5854 //
5855 struct CoerceBuilder {
5856 llvm::LLVMContext &Context;
5857 const llvm::DataLayout &DL;
5858 SmallVector<llvm::Type*, 8> Elems;
5859 uint64_t Size;
5860 bool InReg;
5861
5862 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5863 : Context(c), DL(dl), Size(0), InReg(false) {}
5864
5865 // Pad Elems with integers until Size is ToSize.
5866 void pad(uint64_t ToSize) {
5867 assert(ToSize >= Size && "Cannot remove elements");
5868 if (ToSize == Size)
5869 return;
5870
5871 // Finish the current 64-bit word.
5872 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5873 if (Aligned > Size && Aligned <= ToSize) {
5874 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5875 Size = Aligned;
5876 }
5877
5878 // Add whole 64-bit words.
5879 while (Size + 64 <= ToSize) {
5880 Elems.push_back(llvm::Type::getInt64Ty(Context));
5881 Size += 64;
5882 }
5883
5884 // Final in-word padding.
5885 if (Size < ToSize) {
5886 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5887 Size = ToSize;
5888 }
5889 }
5890
5891 // Add a floating point element at Offset.
5892 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5893 // Unaligned floats are treated as integers.
5894 if (Offset % Bits)
5895 return;
5896 // The InReg flag is only required if there are any floats < 64 bits.
5897 if (Bits < 64)
5898 InReg = true;
5899 pad(Offset);
5900 Elems.push_back(Ty);
5901 Size = Offset + Bits;
5902 }
5903
5904 // Add a struct type to the coercion type, starting at Offset (in bits).
5905 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5906 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5907 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5908 llvm::Type *ElemTy = StrTy->getElementType(i);
5909 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5910 switch (ElemTy->getTypeID()) {
5911 case llvm::Type::StructTyID:
5912 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5913 break;
5914 case llvm::Type::FloatTyID:
5915 addFloat(ElemOffset, ElemTy, 32);
5916 break;
5917 case llvm::Type::DoubleTyID:
5918 addFloat(ElemOffset, ElemTy, 64);
5919 break;
5920 case llvm::Type::FP128TyID:
5921 addFloat(ElemOffset, ElemTy, 128);
5922 break;
5923 case llvm::Type::PointerTyID:
5924 if (ElemOffset % 64 == 0) {
5925 pad(ElemOffset);
5926 Elems.push_back(ElemTy);
5927 Size += 64;
5928 }
5929 break;
5930 default:
5931 break;
5932 }
5933 }
5934 }
5935
5936 // Check if Ty is a usable substitute for the coercion type.
5937 bool isUsableType(llvm::StructType *Ty) const {
5938 if (Ty->getNumElements() != Elems.size())
5939 return false;
5940 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5941 if (Elems[i] != Ty->getElementType(i))
5942 return false;
5943 return true;
5944 }
5945
5946 // Get the coercion type as a literal struct type.
5947 llvm::Type *getType() const {
5948 if (Elems.size() == 1)
5949 return Elems.front();
5950 else
5951 return llvm::StructType::get(Context, Elems);
5952 }
5953 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005954};
5955} // end anonymous namespace
5956
5957ABIArgInfo
5958SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5959 if (Ty->isVoidType())
5960 return ABIArgInfo::getIgnore();
5961
5962 uint64_t Size = getContext().getTypeSize(Ty);
5963
5964 // Anything too big to fit in registers is passed with an explicit indirect
5965 // pointer / sret pointer.
5966 if (Size > SizeLimit)
5967 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5968
5969 // Treat an enum type as its underlying type.
5970 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5971 Ty = EnumTy->getDecl()->getIntegerType();
5972
5973 // Integer types smaller than a register are extended.
5974 if (Size < 64 && Ty->isIntegerType())
5975 return ABIArgInfo::getExtend();
5976
5977 // Other non-aggregates go in registers.
5978 if (!isAggregateTypeForABI(Ty))
5979 return ABIArgInfo::getDirect();
5980
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00005981 // If a C++ object has either a non-trivial copy constructor or a non-trivial
5982 // destructor, it is passed with an explicit indirect pointer / sret pointer.
5983 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5984 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5985
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005986 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005987 // Build a coercion type from the LLVM struct type.
5988 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5989 if (!StrTy)
5990 return ABIArgInfo::getDirect();
5991
5992 CoerceBuilder CB(getVMContext(), getDataLayout());
5993 CB.addStruct(0, StrTy);
5994 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5995
5996 // Try to use the original type for coercion.
5997 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5998
5999 if (CB.InReg)
6000 return ABIArgInfo::getDirectInReg(CoerceTy);
6001 else
6002 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006003}
6004
6005llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6006 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006007 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6008 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6009 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6010 AI.setCoerceToType(ArgTy);
6011
6012 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6013 CGBuilderTy &Builder = CGF.Builder;
6014 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6015 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6016 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6017 llvm::Value *ArgAddr;
6018 unsigned Stride;
6019
6020 switch (AI.getKind()) {
6021 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006022 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006023 llvm_unreachable("Unsupported ABI kind for va_arg");
6024
6025 case ABIArgInfo::Extend:
6026 Stride = 8;
6027 ArgAddr = Builder
6028 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6029 "extend");
6030 break;
6031
6032 case ABIArgInfo::Direct:
6033 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6034 ArgAddr = Addr;
6035 break;
6036
6037 case ABIArgInfo::Indirect:
6038 Stride = 8;
6039 ArgAddr = Builder.CreateBitCast(Addr,
6040 llvm::PointerType::getUnqual(ArgPtrTy),
6041 "indirect");
6042 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6043 break;
6044
6045 case ABIArgInfo::Ignore:
6046 return llvm::UndefValue::get(ArgPtrTy);
6047 }
6048
6049 // Update VAList.
6050 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6051 Builder.CreateStore(Addr, VAListAddrAsBPP);
6052
6053 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006054}
6055
6056void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6057 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006058 for (auto &I : FI.arguments())
6059 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006060}
6061
6062namespace {
6063class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6064public:
6065 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6066 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006067
Craig Topper4f12f102014-03-12 06:41:41 +00006068 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006069 return 14;
6070 }
6071
6072 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006073 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006074};
6075} // end anonymous namespace
6076
Roman Divackyf02c9942014-02-24 18:46:27 +00006077bool
6078SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6079 llvm::Value *Address) const {
6080 // This is calculated from the LLVM and GCC tables and verified
6081 // against gcc output. AFAIK all ABIs use the same encoding.
6082
6083 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6084
6085 llvm::IntegerType *i8 = CGF.Int8Ty;
6086 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6087 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6088
6089 // 0-31: the 8-byte general-purpose registers
6090 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6091
6092 // 32-63: f0-31, the 4-byte floating-point registers
6093 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6094
6095 // Y = 64
6096 // PSR = 65
6097 // WIM = 66
6098 // TBR = 67
6099 // PC = 68
6100 // NPC = 69
6101 // FSR = 70
6102 // CSR = 71
6103 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6104
6105 // 72-87: d0-15, the 8-byte floating-point registers
6106 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6107
6108 return false;
6109}
6110
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006111
Robert Lytton0e076492013-08-13 09:43:10 +00006112//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006113// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006114//===----------------------------------------------------------------------===//
6115namespace {
Robert Lytton7d1db152013-08-19 09:46:39 +00006116class XCoreABIInfo : public DefaultABIInfo {
6117public:
6118 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006119 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6120 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006121};
6122
Robert Lyttond21e2d72014-03-03 13:45:29 +00006123class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton0e076492013-08-13 09:43:10 +00006124public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006125 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006126 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton0e076492013-08-13 09:43:10 +00006127};
Robert Lytton2d196952013-10-11 10:29:34 +00006128} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006129
Robert Lytton7d1db152013-08-19 09:46:39 +00006130llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6131 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006132 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006133
Robert Lytton2d196952013-10-11 10:29:34 +00006134 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006135 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6136 CGF.Int8PtrPtrTy);
6137 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006138
Robert Lytton2d196952013-10-11 10:29:34 +00006139 // Handle the argument.
6140 ABIArgInfo AI = classifyArgumentType(Ty);
6141 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6142 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6143 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006144 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006145 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006146 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006147 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006148 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006149 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006150 llvm_unreachable("Unsupported ABI kind for va_arg");
6151 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006152 Val = llvm::UndefValue::get(ArgPtrTy);
6153 ArgSize = 0;
6154 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006155 case ABIArgInfo::Extend:
6156 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006157 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6158 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6159 if (ArgSize < 4)
6160 ArgSize = 4;
6161 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006162 case ABIArgInfo::Indirect:
6163 llvm::Value *ArgAddr;
6164 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6165 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006166 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6167 ArgSize = 4;
6168 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006169 }
Robert Lytton2d196952013-10-11 10:29:34 +00006170
6171 // Increment the VAList.
6172 if (ArgSize) {
6173 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6174 Builder.CreateStore(APN, VAListAddrAsBPP);
6175 }
6176 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006177}
Robert Lytton0e076492013-08-13 09:43:10 +00006178
6179//===----------------------------------------------------------------------===//
6180// Driver code
6181//===----------------------------------------------------------------------===//
6182
Chris Lattner2b037972010-07-29 02:01:43 +00006183const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006184 if (TheTargetCodeGenInfo)
6185 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006186
John McCallc8e01702013-04-16 22:48:15 +00006187 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00006188 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00006189 default:
Chris Lattner2b037972010-07-29 02:01:43 +00006190 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00006191
Derek Schuff09338a22012-09-06 17:37:28 +00006192 case llvm::Triple::le32:
6193 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00006194 case llvm::Triple::mips:
6195 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006196 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
6197
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00006198 case llvm::Triple::mips64:
6199 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006200 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
6201
James Molloy7f4ba532014-04-23 10:26:08 +00006202 case llvm::Triple::arm64:
6203 case llvm::Triple::arm64_be: {
Tim Northovera2ee4332014-03-29 15:09:45 +00006204 ARM64ABIInfo::ABIKind Kind = ARM64ABIInfo::AAPCS;
6205 if (strcmp(getTarget().getABI(), "darwinpcs") == 0)
6206 Kind = ARM64ABIInfo::DarwinPCS;
6207
6208 return *(TheTargetCodeGenInfo = new ARM64TargetCodeGenInfo(Types, Kind));
6209 }
6210
Tim Northover9bb857a2013-01-31 12:13:10 +00006211 case llvm::Triple::aarch64:
Christian Pirker9b019ae2014-02-25 13:51:00 +00006212 case llvm::Triple::aarch64_be:
Tim Northover9bb857a2013-01-31 12:13:10 +00006213 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
6214
Daniel Dunbard59655c2009-09-12 00:59:49 +00006215 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006216 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00006217 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006218 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006219 {
6220 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCallc8e01702013-04-16 22:48:15 +00006221 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006222 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00006223 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00006224 (CodeGenOpts.FloatABI != "soft" &&
6225 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006226 Kind = ARMABIInfo::AAPCS_VFP;
6227
Derek Schuffa2020962012-10-16 22:30:41 +00006228 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00006229 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00006230 return *(TheTargetCodeGenInfo =
6231 new NaClARMTargetCodeGenInfo(Types, Kind));
6232 default:
6233 return *(TheTargetCodeGenInfo =
6234 new ARMTargetCodeGenInfo(Types, Kind));
6235 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006236 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00006237
John McCallea8d8bb2010-03-11 00:10:12 +00006238 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00006239 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00006240 case llvm::Triple::ppc64:
Bill Schmidt25cb3492012-10-03 19:18:57 +00006241 if (Triple.isOSBinFormatELF())
6242 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
6243 else
6244 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidt778d3872013-07-26 01:36:11 +00006245 case llvm::Triple::ppc64le:
6246 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
6247 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallea8d8bb2010-03-11 00:10:12 +00006248
Peter Collingbournec947aae2012-05-20 23:28:41 +00006249 case llvm::Triple::nvptx:
6250 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00006251 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006252
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006253 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00006254 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00006255
Ulrich Weigand47445072013-05-06 16:26:41 +00006256 case llvm::Triple::systemz:
6257 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
6258
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006259 case llvm::Triple::tce:
6260 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
6261
Eli Friedman33465822011-07-08 23:31:17 +00006262 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00006263 bool IsDarwinVectorABI = Triple.isOSDarwin();
6264 bool IsSmallStructInRegABI =
6265 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00006266 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00006267
John McCall1fe2a8c2013-06-18 02:46:29 +00006268 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00006269 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00006270 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00006271 IsDarwinVectorABI, IsSmallStructInRegABI,
6272 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00006273 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00006274 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006275 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00006276 new X86_32TargetCodeGenInfo(Types,
6277 IsDarwinVectorABI, IsSmallStructInRegABI,
6278 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00006279 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006280 }
Eli Friedman33465822011-07-08 23:31:17 +00006281 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006282
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006283 case llvm::Triple::x86_64: {
John McCallc8e01702013-04-16 22:48:15 +00006284 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006285
Chris Lattner04dc9572010-08-31 16:44:54 +00006286 switch (Triple.getOS()) {
6287 case llvm::Triple::Win32:
NAKAMURA Takumi31ea2f12011-02-17 08:51:38 +00006288 case llvm::Triple::MinGW32:
Chris Lattner04dc9572010-08-31 16:44:54 +00006289 case llvm::Triple::Cygwin:
6290 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00006291 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00006292 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
6293 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00006294 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006295 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
6296 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00006297 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00006298 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00006299 case llvm::Triple::hexagon:
6300 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006301 case llvm::Triple::sparcv9:
6302 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00006303 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006304 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006305 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006306}