blob: 93b869bfda863a05139088ddbe47466d69f5e061 [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());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000371 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
372 it != ie; ++it)
Chris Lattner458b2aa2010-07-29 02:16:43 +0000373 it->info = classifyArgumentType(it->type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000374 }
375
Craig Topper4f12f102014-03-12 06:41:41 +0000376 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
377 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000378};
379
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000380class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
381public:
Chris Lattner2b037972010-07-29 02:01:43 +0000382 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
383 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000384};
385
386llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
387 CodeGenFunction &CGF) const {
388 return 0;
389}
390
Chris Lattner458b2aa2010-07-29 02:16:43 +0000391ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Jan Wen Voung180319f2011-11-03 00:59:44 +0000392 if (isAggregateTypeForABI(Ty)) {
Alp Tokerd4733632013-12-05 04:47:09 +0000393 // Records with non-trivial destructors/constructors should not be passed
Jan Wen Voung180319f2011-11-03 00:59:44 +0000394 // by value.
Mark Lacey3825e832013-10-06 01:33:34 +0000395 if (isRecordReturnIndirect(Ty, getCXXABI()))
Jan Wen Voung180319f2011-11-03 00:59:44 +0000396 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
397
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000398 return ABIArgInfo::getIndirect(0);
Jan Wen Voung180319f2011-11-03 00:59:44 +0000399 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000400
Chris Lattner9723d6c2010-03-11 18:19:55 +0000401 // Treat an enum type as its underlying type.
402 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
403 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000404
Chris Lattner9723d6c2010-03-11 18:19:55 +0000405 return (Ty->isPromotableIntegerType() ?
406 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000407}
408
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000409ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
410 if (RetTy->isVoidType())
411 return ABIArgInfo::getIgnore();
412
413 if (isAggregateTypeForABI(RetTy))
414 return ABIArgInfo::getIndirect(0);
415
416 // Treat an enum type as its underlying type.
417 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
418 RetTy = EnumTy->getDecl()->getIntegerType();
419
420 return (RetTy->isPromotableIntegerType() ?
421 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
422}
423
Derek Schuff09338a22012-09-06 17:37:28 +0000424//===----------------------------------------------------------------------===//
425// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000426//
427// This is a simplified version of the x86_32 ABI. Arguments and return values
428// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000429//===----------------------------------------------------------------------===//
430
431class PNaClABIInfo : public ABIInfo {
432 public:
433 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
434
435 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000436 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000437
Craig Topper4f12f102014-03-12 06:41:41 +0000438 void computeInfo(CGFunctionInfo &FI) const override;
439 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
440 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000441};
442
443class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
444 public:
445 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
446 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
447};
448
449void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
450 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
451
Derek Schuff09338a22012-09-06 17:37:28 +0000452 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
453 it != ie; ++it)
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000454 it->info = classifyArgumentType(it->type);
Derek Schuff09338a22012-09-06 17:37:28 +0000455 }
456
457llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
458 CodeGenFunction &CGF) const {
459 return 0;
460}
461
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000462/// \brief Classify argument of given type \p Ty.
463ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000464 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000465 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000466 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000467 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000468 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
469 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000470 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000471 } else if (Ty->isFloatingType()) {
472 // Floating-point types don't go inreg.
473 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000474 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000475
476 return (Ty->isPromotableIntegerType() ?
477 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000478}
479
480ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
481 if (RetTy->isVoidType())
482 return ABIArgInfo::getIgnore();
483
Eli Benderskye20dad62013-04-04 22:49:35 +0000484 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000485 if (isAggregateTypeForABI(RetTy))
486 return ABIArgInfo::getIndirect(0);
487
488 // Treat an enum type as its underlying type.
489 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
490 RetTy = EnumTy->getDecl()->getIntegerType();
491
492 return (RetTy->isPromotableIntegerType() ?
493 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
494}
495
Chad Rosier651c1832013-03-25 21:00:27 +0000496/// IsX86_MMXType - Return true if this is an MMX type.
497bool IsX86_MMXType(llvm::Type *IRType) {
498 // 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 +0000499 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
500 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
501 IRType->getScalarSizeInBits() != 64;
502}
503
Jay Foad7c57be32011-07-11 09:56:20 +0000504static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000505 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000506 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000507 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
508 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
509 // Invalid MMX constraint
510 return 0;
511 }
512
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000513 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000514 }
515
516 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000517 return Ty;
518}
519
Chris Lattner0cf24192010-06-28 20:05:43 +0000520//===----------------------------------------------------------------------===//
521// X86-32 ABI Implementation
522//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000523
Reid Kleckner661f35b2014-01-18 01:12:41 +0000524/// \brief Similar to llvm::CCState, but for Clang.
525struct CCState {
526 CCState(unsigned CC) : CC(CC), FreeRegs(0) {}
527
528 unsigned CC;
529 unsigned FreeRegs;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000530 unsigned StackOffset;
531 bool UseInAlloca;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000532};
533
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000534/// X86_32ABIInfo - The X86-32 ABI information.
535class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000536 enum Class {
537 Integer,
538 Float
539 };
540
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000541 static const unsigned MinABIStackAlignInBytes = 4;
542
David Chisnallde3a0692009-08-17 23:08:21 +0000543 bool IsDarwinVectorABI;
544 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000545 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000546 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000547
548 static bool isRegisterSize(unsigned Size) {
549 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
550 }
551
Reid Kleckner4982b822014-01-31 22:54:50 +0000552 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
553 bool IsInstanceMethod) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000554
Daniel Dunbar557893d2010-04-21 19:10:51 +0000555 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
556 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000557 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
558
559 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000560
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000561 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000562 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000563
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000564 Class classify(QualType Ty) const;
Reid Kleckner4982b822014-01-31 22:54:50 +0000565 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State,
566 bool IsInstanceMethod) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000567 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
568 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000569
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000570 /// \brief Rewrite the function info so that all memory arguments use
571 /// inalloca.
572 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
573
574 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
575 unsigned &StackOffset, ABIArgInfo &Info,
576 QualType Type) const;
577
Rafael Espindola75419dc2012-07-23 23:30:29 +0000578public:
579
Craig Topper4f12f102014-03-12 06:41:41 +0000580 void computeInfo(CGFunctionInfo &FI) const override;
581 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
582 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000583
Chad Rosier651c1832013-03-25 21:00:27 +0000584 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000585 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000586 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000587 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000588};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000589
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000590class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
591public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000592 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000593 bool d, bool p, bool w, unsigned r)
594 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000595
John McCall1fe2a8c2013-06-18 02:46:29 +0000596 static bool isStructReturnInRegABI(
597 const llvm::Triple &Triple, const CodeGenOptions &Opts);
598
Charles Davis4ea31ab2010-02-13 15:54:06 +0000599 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000600 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000601
Craig Topper4f12f102014-03-12 06:41:41 +0000602 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000603 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000604 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000605 return 4;
606 }
607
608 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000609 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000610
Jay Foad7c57be32011-07-11 09:56:20 +0000611 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000612 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000613 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000614 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
615 }
616
Craig Topper4f12f102014-03-12 06:41:41 +0000617 llvm::Constant *
618 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000619 unsigned Sig = (0xeb << 0) | // jmp rel8
620 (0x06 << 8) | // .+0x08
621 ('F' << 16) |
622 ('T' << 24);
623 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
624 }
625
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000626};
627
628}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000629
630/// shouldReturnTypeInRegister - Determine if the given type should be
631/// passed in a register (for the Darwin ABI).
Reid Kleckner4982b822014-01-31 22:54:50 +0000632bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
633 bool IsInstanceMethod) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000634 uint64_t Size = Context.getTypeSize(Ty);
635
636 // Type must be register sized.
637 if (!isRegisterSize(Size))
638 return false;
639
640 if (Ty->isVectorType()) {
641 // 64- and 128- bit vectors inside structures are not returned in
642 // registers.
643 if (Size == 64 || Size == 128)
644 return false;
645
646 return true;
647 }
648
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000649 // If this is a builtin, pointer, enum, complex type, member pointer, or
650 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000651 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000652 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000653 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000654 return true;
655
656 // Arrays are treated like records.
657 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman3c424412012-02-22 03:04:13 +0000658 return shouldReturnTypeInRegister(AT->getElementType(), Context,
Reid Kleckner4982b822014-01-31 22:54:50 +0000659 IsInstanceMethod);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000660
661 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000662 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000663 if (!RT) return false;
664
Anders Carlsson40446e82010-01-27 03:25:19 +0000665 // FIXME: Traverse bases here too.
666
Aaron Ballman3c424412012-02-22 03:04:13 +0000667 // For thiscall conventions, structures will never be returned in
668 // a register. This is for compatibility with the MSVC ABI
Reid Kleckner4982b822014-01-31 22:54:50 +0000669 if (IsWin32StructABI && IsInstanceMethod && RT->isStructureType())
Aaron Ballman3c424412012-02-22 03:04:13 +0000670 return false;
Aaron Ballman3c424412012-02-22 03:04:13 +0000671
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000672 // Structure types are passed in register if all fields would be
673 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000674 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000675 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000676 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000677 continue;
678
679 // Check fields recursively.
Reid Kleckner4982b822014-01-31 22:54:50 +0000680 if (!shouldReturnTypeInRegister(FD->getType(), Context, IsInstanceMethod))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000681 return false;
682 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000683 return true;
684}
685
Reid Kleckner661f35b2014-01-18 01:12:41 +0000686ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
687 // If the return value is indirect, then the hidden argument is consuming one
688 // integer register.
689 if (State.FreeRegs) {
690 --State.FreeRegs;
691 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
692 }
693 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
694}
695
Reid Kleckner4982b822014-01-31 22:54:50 +0000696ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State,
697 bool IsInstanceMethod) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000698 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000699 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000700
Chris Lattner458b2aa2010-07-29 02:16:43 +0000701 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000702 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000703 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000704 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000705
706 // 128-bit vectors are a special case; they are returned in
707 // registers and we need to make sure to pick a type the LLVM
708 // backend will like.
709 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000710 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000711 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000712
713 // Always return in register if it fits in a general purpose
714 // register, or if it is 64 bits and has a single element.
715 if ((Size == 8 || Size == 16 || Size == 32) ||
716 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000717 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000718 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000719
Reid Kleckner661f35b2014-01-18 01:12:41 +0000720 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000721 }
722
723 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000724 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000725
John McCalla1dee5302010-08-22 10:59:02 +0000726 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000727 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Mark Lacey3825e832013-10-06 01:33:34 +0000728 if (isRecordReturnIndirect(RT, getCXXABI()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000729 return getIndirectReturnResult(State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000730
Anders Carlsson5789c492009-10-20 22:07:59 +0000731 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000732 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000733 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000734 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000735
David Chisnallde3a0692009-08-17 23:08:21 +0000736 // If specified, structs and unions are always indirect.
737 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000738 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000739
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000740 // Small structures which are register sized are generally returned
741 // in a register.
Reid Kleckner4982b822014-01-31 22:54:50 +0000742 if (shouldReturnTypeInRegister(RetTy, getContext(), IsInstanceMethod)) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000743 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000744
745 // As a special-case, if the struct is a "single-element" struct, and
746 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000747 // floating-point register. (MSVC does not apply this special case.)
748 // We apply a similar transformation for pointer types to improve the
749 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000750 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000751 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000752 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000753 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
754
755 // FIXME: We should be able to narrow this integer in cases with dead
756 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000757 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000758 }
759
Reid Kleckner661f35b2014-01-18 01:12:41 +0000760 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000761 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000762
Chris Lattner458b2aa2010-07-29 02:16:43 +0000763 // Treat an enum type as its underlying type.
764 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
765 RetTy = EnumTy->getDecl()->getIntegerType();
766
767 return (RetTy->isPromotableIntegerType() ?
768 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000769}
770
Eli Friedman7919bea2012-06-05 19:40:46 +0000771static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
772 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
773}
774
Daniel Dunbared23de32010-09-16 20:42:00 +0000775static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
776 const RecordType *RT = Ty->getAs<RecordType>();
777 if (!RT)
778 return 0;
779 const RecordDecl *RD = RT->getDecl();
780
781 // If this is a C++ record, check the bases first.
782 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000783 for (const auto &I : CXXRD->bases())
784 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000785 return false;
786
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000787 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000788 QualType FT = i->getType();
789
Eli Friedman7919bea2012-06-05 19:40:46 +0000790 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000791 return true;
792
793 if (isRecordWithSSEVectorType(Context, FT))
794 return true;
795 }
796
797 return false;
798}
799
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000800unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
801 unsigned Align) const {
802 // Otherwise, if the alignment is less than or equal to the minimum ABI
803 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000804 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000805 return 0; // Use default alignment.
806
807 // On non-Darwin, the stack type alignment is always 4.
808 if (!IsDarwinVectorABI) {
809 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000810 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000811 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000812
Daniel Dunbared23de32010-09-16 20:42:00 +0000813 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000814 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
815 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000816 return 16;
817
818 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000819}
820
Rafael Espindola703c47f2012-10-19 05:04:37 +0000821ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000822 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000823 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000824 if (State.FreeRegs) {
825 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000826 return ABIArgInfo::getIndirectInReg(0, false);
827 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000828 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000829 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000830
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000831 // Compute the byval alignment.
832 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
833 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
834 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000835 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000836
837 // If the stack alignment is less than the type alignment, realign the
838 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000839 bool Realign = TypeAlign > StackAlign;
840 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000841}
842
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000843X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
844 const Type *T = isSingleElementStruct(Ty, getContext());
845 if (!T)
846 T = Ty.getTypePtr();
847
848 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
849 BuiltinType::Kind K = BT->getKind();
850 if (K == BuiltinType::Float || K == BuiltinType::Double)
851 return Float;
852 }
853 return Integer;
854}
855
Reid Kleckner661f35b2014-01-18 01:12:41 +0000856bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
857 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000858 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000859 Class C = classify(Ty);
860 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000861 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000862
Rafael Espindola077dd592012-10-24 01:58:58 +0000863 unsigned Size = getContext().getTypeSize(Ty);
864 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000865
866 if (SizeInRegs == 0)
867 return false;
868
Reid Kleckner661f35b2014-01-18 01:12:41 +0000869 if (SizeInRegs > State.FreeRegs) {
870 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000871 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000872 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000873
Reid Kleckner661f35b2014-01-18 01:12:41 +0000874 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000875
Reid Kleckner661f35b2014-01-18 01:12:41 +0000876 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000877 if (Size > 32)
878 return false;
879
880 if (Ty->isIntegralOrEnumerationType())
881 return true;
882
883 if (Ty->isPointerType())
884 return true;
885
886 if (Ty->isReferenceType())
887 return true;
888
Reid Kleckner661f35b2014-01-18 01:12:41 +0000889 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000890 NeedsPadding = true;
891
Rafael Espindola077dd592012-10-24 01:58:58 +0000892 return false;
893 }
894
Rafael Espindola703c47f2012-10-19 05:04:37 +0000895 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000896}
897
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000898ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
899 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000900 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000901 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000902 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000903 // Check with the C++ ABI first.
904 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
905 if (RAA == CGCXXABI::RAA_Indirect) {
906 return getIndirectResult(Ty, false, State);
907 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
908 // The field index doesn't matter, we'll fix it up later.
909 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
910 }
911
912 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000913 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000914 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000915
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000916 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000917 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000918 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +0000919 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000920
Eli Friedman9f061a32011-11-18 00:28:11 +0000921 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000922 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000923 return ABIArgInfo::getIgnore();
924
Rafael Espindolafad28de2012-10-24 01:59:00 +0000925 llvm::LLVMContext &LLVMContext = getVMContext();
926 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
927 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000928 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000929 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000930 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000931 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
932 return ABIArgInfo::getDirectInReg(Result);
933 }
Rafael Espindolafad28de2012-10-24 01:59:00 +0000934 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000935
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000936 // Expand small (<= 128-bit) record types when we know that the stack layout
937 // of those arguments will match the struct. This is important because the
938 // LLVM backend isn't smart enough to remove byval, which inhibits many
939 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +0000940 if (getContext().getTypeSize(Ty) <= 4*32 &&
941 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000942 return ABIArgInfo::getExpandWithPadding(
943 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000944
Reid Kleckner661f35b2014-01-18 01:12:41 +0000945 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000946 }
947
Chris Lattnerd774ae92010-08-26 20:05:13 +0000948 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +0000949 // On Darwin, some vectors are passed in memory, we handle this by passing
950 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +0000951 if (IsDarwinVectorABI) {
952 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +0000953 if ((Size == 8 || Size == 16 || Size == 32) ||
954 (Size == 64 && VT->getNumElements() == 1))
955 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
956 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +0000957 }
Bill Wendling5cd41c42010-10-18 03:41:31 +0000958
Chad Rosier651c1832013-03-25 21:00:27 +0000959 if (IsX86_MMXType(CGT.ConvertType(Ty)))
960 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000961
Chris Lattnerd774ae92010-08-26 20:05:13 +0000962 return ABIArgInfo::getDirect();
963 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000964
965
Chris Lattner458b2aa2010-07-29 02:16:43 +0000966 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
967 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000968
Rafael Espindolafad28de2012-10-24 01:59:00 +0000969 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000970 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000971
972 if (Ty->isPromotableIntegerType()) {
973 if (InReg)
974 return ABIArgInfo::getExtendInReg();
975 return ABIArgInfo::getExtend();
976 }
977 if (InReg)
978 return ABIArgInfo::getDirectInReg();
979 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000980}
981
Rafael Espindolaa6472962012-07-24 00:01:07 +0000982void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000983 CCState State(FI.getCallingConvention());
984 if (State.CC == llvm::CallingConv::X86_FastCall)
985 State.FreeRegs = 2;
Rafael Espindola077dd592012-10-24 01:58:58 +0000986 else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000987 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +0000988 else
Reid Kleckner661f35b2014-01-18 01:12:41 +0000989 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000990
Reid Kleckner4982b822014-01-31 22:54:50 +0000991 FI.getReturnInfo() =
992 classifyReturnType(FI.getReturnType(), State, FI.isInstanceMethod());
993
994 // On win32, use the x86_cdeclmethodcc convention for cdecl methods that use
995 // sret. This convention swaps the order of the first two parameters behind
996 // the scenes to match MSVC.
997 if (IsWin32StructABI && FI.isInstanceMethod() &&
998 FI.getCallingConvention() == llvm::CallingConv::C &&
999 FI.getReturnInfo().isIndirect())
1000 FI.setEffectiveCallingConvention(llvm::CallingConv::X86_CDeclMethod);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001001
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001002 bool UsedInAlloca = false;
Rafael Espindolaa6472962012-07-24 00:01:07 +00001003 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001004 it != ie; ++it) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001005 it->info = classifyArgumentType(it->type, State);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001006 UsedInAlloca |= (it->info.getKind() == ABIArgInfo::InAlloca);
1007 }
1008
1009 // If we needed to use inalloca for any argument, do a second pass and rewrite
1010 // all the memory arguments to use inalloca.
1011 if (UsedInAlloca)
1012 rewriteWithInAlloca(FI);
1013}
1014
1015void
1016X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1017 unsigned &StackOffset,
1018 ABIArgInfo &Info, QualType Type) const {
1019 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1020 // byte aligned.
1021 unsigned Align = 4U;
1022 if (Info.getKind() == ABIArgInfo::Indirect && Info.getIndirectByVal())
1023 Align = std::max(Align, Info.getIndirectAlign());
1024 if (StackOffset & (Align - 1)) {
1025 unsigned OldOffset = StackOffset;
1026 StackOffset = llvm::RoundUpToAlignment(StackOffset, Align);
1027 unsigned NumBytes = StackOffset - OldOffset;
1028 assert(NumBytes);
1029 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1030 Ty = llvm::ArrayType::get(Ty, NumBytes);
1031 FrameFields.push_back(Ty);
1032 }
1033
1034 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1035 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1036 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1037}
1038
1039void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1040 assert(IsWin32StructABI && "inalloca only supported on win32");
1041
1042 // Build a packed struct type for all of the arguments in memory.
1043 SmallVector<llvm::Type *, 6> FrameFields;
1044
1045 unsigned StackOffset = 0;
1046
1047 // Put the sret parameter into the inalloca struct if it's in memory.
1048 ABIArgInfo &Ret = FI.getReturnInfo();
1049 if (Ret.isIndirect() && !Ret.getInReg()) {
1050 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1051 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001052 // On Windows, the hidden sret parameter is always returned in eax.
1053 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001054 }
1055
1056 // Skip the 'this' parameter in ecx.
1057 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1058 if (FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall)
1059 ++I;
1060
1061 // Put arguments passed in memory into the struct.
1062 for (; I != E; ++I) {
1063
1064 // Leave ignored and inreg arguments alone.
1065 switch (I->info.getKind()) {
1066 case ABIArgInfo::Indirect:
1067 assert(I->info.getIndirectByVal());
1068 break;
1069 case ABIArgInfo::Ignore:
1070 continue;
1071 case ABIArgInfo::Direct:
1072 case ABIArgInfo::Extend:
1073 if (I->info.getInReg())
1074 continue;
1075 break;
1076 default:
1077 break;
1078 }
1079
1080 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1081 }
1082
1083 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1084 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001085}
1086
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001087llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1088 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001089 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001090
1091 CGBuilderTy &Builder = CGF.Builder;
1092 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1093 "ap");
1094 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001095
1096 // Compute if the address needs to be aligned
1097 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1098 Align = getTypeStackAlignInBytes(Ty, Align);
1099 Align = std::max(Align, 4U);
1100 if (Align > 4) {
1101 // addr = (addr + align - 1) & -align;
1102 llvm::Value *Offset =
1103 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1104 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1105 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1106 CGF.Int32Ty);
1107 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1108 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1109 Addr->getType(),
1110 "ap.cur.aligned");
1111 }
1112
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001113 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001114 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001115 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1116
1117 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001118 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001119 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001120 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001121 "ap.next");
1122 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1123
1124 return AddrTyped;
1125}
1126
Charles Davis4ea31ab2010-02-13 15:54:06 +00001127void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1128 llvm::GlobalValue *GV,
1129 CodeGen::CodeGenModule &CGM) const {
1130 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1131 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1132 // Get the LLVM function.
1133 llvm::Function *Fn = cast<llvm::Function>(GV);
1134
1135 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001136 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001137 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001138 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1139 llvm::AttributeSet::get(CGM.getLLVMContext(),
1140 llvm::AttributeSet::FunctionIndex,
1141 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001142 }
1143 }
1144}
1145
John McCallbeec5a02010-03-06 00:35:14 +00001146bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1147 CodeGen::CodeGenFunction &CGF,
1148 llvm::Value *Address) const {
1149 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001150
Chris Lattnerece04092012-02-07 00:39:47 +00001151 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001152
John McCallbeec5a02010-03-06 00:35:14 +00001153 // 0-7 are the eight integer registers; the order is different
1154 // on Darwin (for EH), but the range is the same.
1155 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001156 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001157
John McCallc8e01702013-04-16 22:48:15 +00001158 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001159 // 12-16 are st(0..4). Not sure why we stop at 4.
1160 // These have size 16, which is sizeof(long double) on
1161 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001162 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001163 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001164
John McCallbeec5a02010-03-06 00:35:14 +00001165 } else {
1166 // 9 is %eflags, which doesn't get a size on Darwin for some
1167 // reason.
1168 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1169
1170 // 11-16 are st(0..5). Not sure why we stop at 5.
1171 // These have size 12, which is sizeof(long double) on
1172 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001173 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001174 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1175 }
John McCallbeec5a02010-03-06 00:35:14 +00001176
1177 return false;
1178}
1179
Chris Lattner0cf24192010-06-28 20:05:43 +00001180//===----------------------------------------------------------------------===//
1181// X86-64 ABI Implementation
1182//===----------------------------------------------------------------------===//
1183
1184
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001185namespace {
1186/// X86_64ABIInfo - The X86_64 ABI information.
1187class X86_64ABIInfo : public ABIInfo {
1188 enum Class {
1189 Integer = 0,
1190 SSE,
1191 SSEUp,
1192 X87,
1193 X87Up,
1194 ComplexX87,
1195 NoClass,
1196 Memory
1197 };
1198
1199 /// merge - Implement the X86_64 ABI merging algorithm.
1200 ///
1201 /// Merge an accumulating classification \arg Accum with a field
1202 /// classification \arg Field.
1203 ///
1204 /// \param Accum - The accumulating classification. This should
1205 /// always be either NoClass or the result of a previous merge
1206 /// call. In addition, this should never be Memory (the caller
1207 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001208 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001209
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001210 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1211 ///
1212 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1213 /// final MEMORY or SSE classes when necessary.
1214 ///
1215 /// \param AggregateSize - The size of the current aggregate in
1216 /// the classification process.
1217 ///
1218 /// \param Lo - The classification for the parts of the type
1219 /// residing in the low word of the containing object.
1220 ///
1221 /// \param Hi - The classification for the parts of the type
1222 /// residing in the higher words of the containing object.
1223 ///
1224 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1225
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001226 /// classify - Determine the x86_64 register classes in which the
1227 /// given type T should be passed.
1228 ///
1229 /// \param Lo - The classification for the parts of the type
1230 /// residing in the low word of the containing object.
1231 ///
1232 /// \param Hi - The classification for the parts of the type
1233 /// residing in the high word of the containing object.
1234 ///
1235 /// \param OffsetBase - The bit offset of this type in the
1236 /// containing object. Some parameters are classified different
1237 /// depending on whether they straddle an eightbyte boundary.
1238 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001239 /// \param isNamedArg - Whether the argument in question is a "named"
1240 /// argument, as used in AMD64-ABI 3.5.7.
1241 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001242 /// If a word is unused its result will be NoClass; if a type should
1243 /// be passed in Memory then at least the classification of \arg Lo
1244 /// will be Memory.
1245 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001246 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001247 ///
1248 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1249 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001250 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1251 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001252
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001253 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001254 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1255 unsigned IROffset, QualType SourceTy,
1256 unsigned SourceOffset) const;
1257 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1258 unsigned IROffset, QualType SourceTy,
1259 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001260
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001261 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001262 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001263 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001264
1265 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001266 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001267 ///
1268 /// \param freeIntRegs - The number of free integer registers remaining
1269 /// available.
1270 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001271
Chris Lattner458b2aa2010-07-29 02:16:43 +00001272 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001273
Bill Wendling5cd41c42010-10-18 03:41:31 +00001274 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001275 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001276 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001277 unsigned &neededSSE,
1278 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001279
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001280 bool IsIllegalVectorType(QualType Ty) const;
1281
John McCalle0fda732011-04-21 01:20:55 +00001282 /// The 0.98 ABI revision clarified a lot of ambiguities,
1283 /// unfortunately in ways that were not always consistent with
1284 /// certain previous compilers. In particular, platforms which
1285 /// required strict binary compatibility with older versions of GCC
1286 /// may need to exempt themselves.
1287 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001288 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001289 }
1290
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001291 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001292 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1293 // 64-bit hardware.
1294 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001295
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001296public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001297 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001298 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001299 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001300 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001301
John McCalla729c622012-02-17 03:33:10 +00001302 bool isPassedUsingAVXType(QualType type) const {
1303 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001304 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001305 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1306 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001307 if (info.isDirect()) {
1308 llvm::Type *ty = info.getCoerceToType();
1309 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1310 return (vectorTy->getBitWidth() > 128);
1311 }
1312 return false;
1313 }
1314
Craig Topper4f12f102014-03-12 06:41:41 +00001315 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001316
Craig Topper4f12f102014-03-12 06:41:41 +00001317 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1318 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001319};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001320
Chris Lattner04dc9572010-08-31 16:44:54 +00001321/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001322class WinX86_64ABIInfo : public ABIInfo {
1323
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001324 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001325
Chris Lattner04dc9572010-08-31 16:44:54 +00001326public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001327 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1328
Craig Topper4f12f102014-03-12 06:41:41 +00001329 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001330
Craig Topper4f12f102014-03-12 06:41:41 +00001331 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1332 CodeGenFunction &CGF) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001333};
1334
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001335class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1336public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001337 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffc7dd7222012-10-11 15:52:22 +00001338 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001339
John McCalla729c622012-02-17 03:33:10 +00001340 const X86_64ABIInfo &getABIInfo() const {
1341 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1342 }
1343
Craig Topper4f12f102014-03-12 06:41:41 +00001344 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001345 return 7;
1346 }
1347
1348 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001349 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001350 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001351
John McCall943fae92010-05-27 06:19:26 +00001352 // 0-15 are the 16 integer registers.
1353 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001354 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001355 return false;
1356 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001357
Jay Foad7c57be32011-07-11 09:56:20 +00001358 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001359 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001360 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001361 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1362 }
1363
John McCalla729c622012-02-17 03:33:10 +00001364 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001365 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001366 // The default CC on x86-64 sets %al to the number of SSA
1367 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001368 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001369 // that when AVX types are involved: the ABI explicitly states it is
1370 // undefined, and it doesn't work in practice because of how the ABI
1371 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001372 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001373 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001374 for (CallArgList::const_iterator
1375 it = args.begin(), ie = args.end(); it != ie; ++it) {
1376 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1377 HasAVXType = true;
1378 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001379 }
1380 }
John McCalla729c622012-02-17 03:33:10 +00001381
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001382 if (!HasAVXType)
1383 return true;
1384 }
John McCallcbc038a2011-09-21 08:08:30 +00001385
John McCalla729c622012-02-17 03:33:10 +00001386 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001387 }
1388
Craig Topper4f12f102014-03-12 06:41:41 +00001389 llvm::Constant *
1390 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001391 unsigned Sig = (0xeb << 0) | // jmp rel8
1392 (0x0a << 8) | // .+0x0c
1393 ('F' << 16) |
1394 ('T' << 24);
1395 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1396 }
1397
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001398};
1399
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001400static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1401 // If the argument does not end in .lib, automatically add the suffix. This
1402 // matches the behavior of MSVC.
1403 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001404 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001405 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001406 return ArgStr;
1407}
1408
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001409class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1410public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001411 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1412 bool d, bool p, bool w, unsigned RegParms)
1413 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001414
1415 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001416 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001417 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001418 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001419 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001420
1421 void getDetectMismatchOption(llvm::StringRef Name,
1422 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001423 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001424 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001425 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001426};
1427
Chris Lattner04dc9572010-08-31 16:44:54 +00001428class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1429public:
1430 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1431 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1432
Craig Topper4f12f102014-03-12 06:41:41 +00001433 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001434 return 7;
1435 }
1436
1437 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001438 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001439 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001440
Chris Lattner04dc9572010-08-31 16:44:54 +00001441 // 0-15 are the 16 integer registers.
1442 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001443 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001444 return false;
1445 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001446
1447 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001448 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001449 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001450 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001451 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001452
1453 void getDetectMismatchOption(llvm::StringRef Name,
1454 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001455 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001456 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001457 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001458};
1459
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001460}
1461
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001462void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1463 Class &Hi) const {
1464 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1465 //
1466 // (a) If one of the classes is Memory, the whole argument is passed in
1467 // memory.
1468 //
1469 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1470 // memory.
1471 //
1472 // (c) If the size of the aggregate exceeds two eightbytes and the first
1473 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1474 // argument is passed in memory. NOTE: This is necessary to keep the
1475 // ABI working for processors that don't support the __m256 type.
1476 //
1477 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1478 //
1479 // Some of these are enforced by the merging logic. Others can arise
1480 // only with unions; for example:
1481 // union { _Complex double; unsigned; }
1482 //
1483 // Note that clauses (b) and (c) were added in 0.98.
1484 //
1485 if (Hi == Memory)
1486 Lo = Memory;
1487 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1488 Lo = Memory;
1489 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1490 Lo = Memory;
1491 if (Hi == SSEUp && Lo != SSE)
1492 Hi = SSE;
1493}
1494
Chris Lattnerd776fb12010-06-28 21:43:59 +00001495X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001496 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1497 // classified recursively so that always two fields are
1498 // considered. The resulting class is calculated according to
1499 // the classes of the fields in the eightbyte:
1500 //
1501 // (a) If both classes are equal, this is the resulting class.
1502 //
1503 // (b) If one of the classes is NO_CLASS, the resulting class is
1504 // the other class.
1505 //
1506 // (c) If one of the classes is MEMORY, the result is the MEMORY
1507 // class.
1508 //
1509 // (d) If one of the classes is INTEGER, the result is the
1510 // INTEGER.
1511 //
1512 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1513 // MEMORY is used as class.
1514 //
1515 // (f) Otherwise class SSE is used.
1516
1517 // Accum should never be memory (we should have returned) or
1518 // ComplexX87 (because this cannot be passed in a structure).
1519 assert((Accum != Memory && Accum != ComplexX87) &&
1520 "Invalid accumulated classification during merge.");
1521 if (Accum == Field || Field == NoClass)
1522 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001523 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001524 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001525 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001526 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001527 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001528 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001529 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1530 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001531 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001532 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001533}
1534
Chris Lattner5c740f12010-06-30 19:14:05 +00001535void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001536 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001537 // FIXME: This code can be simplified by introducing a simple value class for
1538 // Class pairs with appropriate constructor methods for the various
1539 // situations.
1540
1541 // FIXME: Some of the split computations are wrong; unaligned vectors
1542 // shouldn't be passed in registers for example, so there is no chance they
1543 // can straddle an eightbyte. Verify & simplify.
1544
1545 Lo = Hi = NoClass;
1546
1547 Class &Current = OffsetBase < 64 ? Lo : Hi;
1548 Current = Memory;
1549
John McCall9dd450b2009-09-21 23:43:11 +00001550 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001551 BuiltinType::Kind k = BT->getKind();
1552
1553 if (k == BuiltinType::Void) {
1554 Current = NoClass;
1555 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1556 Lo = Integer;
1557 Hi = Integer;
1558 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1559 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001560 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1561 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001562 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001563 Current = SSE;
1564 } else if (k == BuiltinType::LongDouble) {
1565 Lo = X87;
1566 Hi = X87Up;
1567 }
1568 // FIXME: _Decimal32 and _Decimal64 are SSE.
1569 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001570 return;
1571 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001572
Chris Lattnerd776fb12010-06-28 21:43:59 +00001573 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001574 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001575 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
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->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001580 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001581 return;
1582 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001583
Chris Lattnerd776fb12010-06-28 21:43:59 +00001584 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001585 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001586 Lo = Hi = Integer;
1587 else
1588 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001589 return;
1590 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001591
Chris Lattnerd776fb12010-06-28 21:43:59 +00001592 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001593 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001594 if (Size == 32) {
1595 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1596 // float> as integer.
1597 Current = Integer;
1598
1599 // If this type crosses an eightbyte boundary, it should be
1600 // split.
1601 uint64_t EB_Real = (OffsetBase) / 64;
1602 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1603 if (EB_Real != EB_Imag)
1604 Hi = Lo;
1605 } else if (Size == 64) {
1606 // gcc passes <1 x double> in memory. :(
1607 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1608 return;
1609
1610 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001611 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001612 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1613 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1614 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001615 Current = Integer;
1616 else
1617 Current = SSE;
1618
1619 // If this type crosses an eightbyte boundary, it should be
1620 // split.
1621 if (OffsetBase && OffsetBase != 64)
1622 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001623 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001624 // Arguments of 256-bits are split into four eightbyte chunks. The
1625 // least significant one belongs to class SSE and all the others to class
1626 // SSEUP. The original Lo and Hi design considers that types can't be
1627 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1628 // This design isn't correct for 256-bits, but since there're no cases
1629 // where the upper parts would need to be inspected, avoid adding
1630 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001631 //
1632 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1633 // registers if they are "named", i.e. not part of the "..." of a
1634 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001635 Lo = SSE;
1636 Hi = SSEUp;
1637 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001638 return;
1639 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001640
Chris Lattnerd776fb12010-06-28 21:43:59 +00001641 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001642 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001643
Chris Lattner2b037972010-07-29 02:01:43 +00001644 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001645 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001646 if (Size <= 64)
1647 Current = Integer;
1648 else if (Size <= 128)
1649 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001650 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001651 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001652 else if (ET == getContext().DoubleTy ||
1653 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001654 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001655 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001656 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001657 Current = ComplexX87;
1658
1659 // If this complex type crosses an eightbyte boundary then it
1660 // should be split.
1661 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001662 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001663 if (Hi == NoClass && EB_Real != EB_Imag)
1664 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001665
Chris Lattnerd776fb12010-06-28 21:43:59 +00001666 return;
1667 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001668
Chris Lattner2b037972010-07-29 02:01:43 +00001669 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001670 // Arrays are treated like structures.
1671
Chris Lattner2b037972010-07-29 02:01:43 +00001672 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001673
1674 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001675 // than four eightbytes, ..., it has class MEMORY.
1676 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001677 return;
1678
1679 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1680 // fields, it has class MEMORY.
1681 //
1682 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001683 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001684 return;
1685
1686 // Otherwise implement simplified merge. We could be smarter about
1687 // this, but it isn't worth it and would be harder to verify.
1688 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001689 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001690 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001691
1692 // The only case a 256-bit wide vector could be used is when the array
1693 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1694 // to work for sizes wider than 128, early check and fallback to memory.
1695 if (Size > 128 && EltSize != 256)
1696 return;
1697
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001698 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1699 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001700 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001701 Lo = merge(Lo, FieldLo);
1702 Hi = merge(Hi, FieldHi);
1703 if (Lo == Memory || Hi == Memory)
1704 break;
1705 }
1706
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001707 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001708 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001709 return;
1710 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001711
Chris Lattnerd776fb12010-06-28 21:43:59 +00001712 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001713 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001714
1715 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001716 // than four eightbytes, ..., it has class MEMORY.
1717 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001718 return;
1719
Anders Carlsson20759ad2009-09-16 15:53:40 +00001720 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1721 // copy constructor or a non-trivial destructor, it is passed by invisible
1722 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001723 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001724 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001725
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001726 const RecordDecl *RD = RT->getDecl();
1727
1728 // Assume variable sized types are passed in memory.
1729 if (RD->hasFlexibleArrayMember())
1730 return;
1731
Chris Lattner2b037972010-07-29 02:01:43 +00001732 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001733
1734 // Reset Lo class, this will be recomputed.
1735 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001736
1737 // If this is a C++ record, classify the bases first.
1738 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001739 for (const auto &I : CXXRD->bases()) {
1740 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001741 "Unexpected base class!");
1742 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001743 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001744
1745 // Classify this field.
1746 //
1747 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1748 // single eightbyte, each is classified separately. Each eightbyte gets
1749 // initialized to class NO_CLASS.
1750 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001751 uint64_t Offset =
1752 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001753 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001754 Lo = merge(Lo, FieldLo);
1755 Hi = merge(Hi, FieldHi);
1756 if (Lo == Memory || Hi == Memory)
1757 break;
1758 }
1759 }
1760
1761 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001762 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001763 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001764 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001765 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1766 bool BitField = i->isBitField();
1767
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001768 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1769 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001770 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001771 // The only case a 256-bit wide vector could be used is when the struct
1772 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1773 // to work for sizes wider than 128, early check and fallback to memory.
1774 //
1775 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1776 Lo = Memory;
1777 return;
1778 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001779 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001780 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001781 Lo = Memory;
1782 return;
1783 }
1784
1785 // Classify this field.
1786 //
1787 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1788 // exceeds a single eightbyte, each is classified
1789 // separately. Each eightbyte gets initialized to class
1790 // NO_CLASS.
1791 Class FieldLo, FieldHi;
1792
1793 // Bit-fields require special handling, they do not force the
1794 // structure to be passed in memory even if unaligned, and
1795 // therefore they can straddle an eightbyte.
1796 if (BitField) {
1797 // Ignore padding bit-fields.
1798 if (i->isUnnamedBitfield())
1799 continue;
1800
1801 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001802 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001803
1804 uint64_t EB_Lo = Offset / 64;
1805 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001806
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001807 if (EB_Lo) {
1808 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1809 FieldLo = NoClass;
1810 FieldHi = Integer;
1811 } else {
1812 FieldLo = Integer;
1813 FieldHi = EB_Hi ? Integer : NoClass;
1814 }
1815 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001816 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001817 Lo = merge(Lo, FieldLo);
1818 Hi = merge(Hi, FieldHi);
1819 if (Lo == Memory || Hi == Memory)
1820 break;
1821 }
1822
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001823 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001824 }
1825}
1826
Chris Lattner22a931e2010-06-29 06:01:59 +00001827ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001828 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1829 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001830 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001831 // Treat an enum type as its underlying type.
1832 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1833 Ty = EnumTy->getDecl()->getIntegerType();
1834
1835 return (Ty->isPromotableIntegerType() ?
1836 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1837 }
1838
1839 return ABIArgInfo::getIndirect(0);
1840}
1841
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001842bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1843 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1844 uint64_t Size = getContext().getTypeSize(VecTy);
1845 unsigned LargestVector = HasAVX ? 256 : 128;
1846 if (Size <= 64 || Size > LargestVector)
1847 return true;
1848 }
1849
1850 return false;
1851}
1852
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001853ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1854 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001855 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1856 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001857 //
1858 // This assumption is optimistic, as there could be free registers available
1859 // when we need to pass this argument in memory, and LLVM could try to pass
1860 // the argument in the free register. This does not seem to happen currently,
1861 // but this code would be much safer if we could mark the argument with
1862 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001863 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001864 // Treat an enum type as its underlying type.
1865 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1866 Ty = EnumTy->getDecl()->getIntegerType();
1867
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001868 return (Ty->isPromotableIntegerType() ?
1869 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001870 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001871
Mark Lacey3825e832013-10-06 01:33:34 +00001872 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001873 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001874
Chris Lattner44c2b902011-05-22 23:21:23 +00001875 // Compute the byval alignment. We specify the alignment of the byval in all
1876 // cases so that the mid-level optimizer knows the alignment of the byval.
1877 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001878
1879 // Attempt to avoid passing indirect results using byval when possible. This
1880 // is important for good codegen.
1881 //
1882 // We do this by coercing the value into a scalar type which the backend can
1883 // handle naturally (i.e., without using byval).
1884 //
1885 // For simplicity, we currently only do this when we have exhausted all of the
1886 // free integer registers. Doing this when there are free integer registers
1887 // would require more care, as we would have to ensure that the coerced value
1888 // did not claim the unused register. That would require either reording the
1889 // arguments to the function (so that any subsequent inreg values came first),
1890 // or only doing this optimization when there were no following arguments that
1891 // might be inreg.
1892 //
1893 // We currently expect it to be rare (particularly in well written code) for
1894 // arguments to be passed on the stack when there are still free integer
1895 // registers available (this would typically imply large structs being passed
1896 // by value), so this seems like a fair tradeoff for now.
1897 //
1898 // We can revisit this if the backend grows support for 'onstack' parameter
1899 // attributes. See PR12193.
1900 if (freeIntRegs == 0) {
1901 uint64_t Size = getContext().getTypeSize(Ty);
1902
1903 // If this type fits in an eightbyte, coerce it into the matching integral
1904 // type, which will end up on the stack (with alignment 8).
1905 if (Align == 8 && Size <= 64)
1906 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1907 Size));
1908 }
1909
Chris Lattner44c2b902011-05-22 23:21:23 +00001910 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001911}
1912
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001913/// GetByteVectorType - The ABI specifies that a value should be passed in an
1914/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00001915/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001916llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001917 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001918
Chris Lattner9fa15c32010-07-29 05:02:29 +00001919 // Wrapper structs that just contain vectors are passed just like vectors,
1920 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001921 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00001922 while (STy && STy->getNumElements() == 1) {
1923 IRType = STy->getElementType(0);
1924 STy = dyn_cast<llvm::StructType>(IRType);
1925 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001926
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00001927 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001928 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1929 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001930 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00001931 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00001932 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1933 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1934 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1935 EltTy->isIntegerTy(128)))
1936 return VT;
1937 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001938
Chris Lattner4200fe42010-07-29 04:56:46 +00001939 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1940}
1941
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001942/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1943/// is known to either be off the end of the specified type or being in
1944/// alignment padding. The user type specified is known to be at most 128 bits
1945/// in size, and have passed through X86_64ABIInfo::classify with a successful
1946/// classification that put one of the two halves in the INTEGER class.
1947///
1948/// It is conservatively correct to return false.
1949static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1950 unsigned EndBit, ASTContext &Context) {
1951 // If the bytes being queried are off the end of the type, there is no user
1952 // data hiding here. This handles analysis of builtins, vectors and other
1953 // types that don't contain interesting padding.
1954 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1955 if (TySize <= StartBit)
1956 return true;
1957
Chris Lattner98076a22010-07-29 07:43:55 +00001958 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1959 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1960 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1961
1962 // Check each element to see if the element overlaps with the queried range.
1963 for (unsigned i = 0; i != NumElts; ++i) {
1964 // If the element is after the span we care about, then we're done..
1965 unsigned EltOffset = i*EltSize;
1966 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001967
Chris Lattner98076a22010-07-29 07:43:55 +00001968 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1969 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1970 EndBit-EltOffset, Context))
1971 return false;
1972 }
1973 // If it overlaps no elements, then it is safe to process as padding.
1974 return true;
1975 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001976
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001977 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1978 const RecordDecl *RD = RT->getDecl();
1979 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001980
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001981 // If this is a C++ record, check the bases first.
1982 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001983 for (const auto &I : CXXRD->bases()) {
1984 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001985 "Unexpected base class!");
1986 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001987 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001988
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001989 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001990 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001991 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001992
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001993 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00001994 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001995 EndBit-BaseOffset, Context))
1996 return false;
1997 }
1998 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001999
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002000 // Verify that no field has data that overlaps the region of interest. Yes
2001 // this could be sped up a lot by being smarter about queried fields,
2002 // however we're only looking at structs up to 16 bytes, so we don't care
2003 // much.
2004 unsigned idx = 0;
2005 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2006 i != e; ++i, ++idx) {
2007 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002008
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002009 // If we found a field after the region we care about, then we're done.
2010 if (FieldOffset >= EndBit) break;
2011
2012 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2013 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2014 Context))
2015 return false;
2016 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002017
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002018 // If nothing in this record overlapped the area of interest, then we're
2019 // clean.
2020 return true;
2021 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002022
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002023 return false;
2024}
2025
Chris Lattnere556a712010-07-29 18:39:32 +00002026/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2027/// float member at the specified offset. For example, {int,{float}} has a
2028/// float at offset 4. It is conservatively correct for this routine to return
2029/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002030static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002031 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002032 // Base case if we find a float.
2033 if (IROffset == 0 && IRType->isFloatTy())
2034 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002035
Chris Lattnere556a712010-07-29 18:39:32 +00002036 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002037 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002038 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2039 unsigned Elt = SL->getElementContainingOffset(IROffset);
2040 IROffset -= SL->getElementOffset(Elt);
2041 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2042 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002043
Chris Lattnere556a712010-07-29 18:39:32 +00002044 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002045 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2046 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002047 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2048 IROffset -= IROffset/EltSize*EltSize;
2049 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2050 }
2051
2052 return false;
2053}
2054
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002055
2056/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2057/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002058llvm::Type *X86_64ABIInfo::
2059GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002060 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002061 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002062 // pass as float if the last 4 bytes is just padding. This happens for
2063 // structs that contain 3 floats.
2064 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2065 SourceOffset*8+64, getContext()))
2066 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002067
Chris Lattnere556a712010-07-29 18:39:32 +00002068 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2069 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2070 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002071 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2072 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002073 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002074
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002075 return llvm::Type::getDoubleTy(getVMContext());
2076}
2077
2078
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002079/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2080/// an 8-byte GPR. This means that we either have a scalar or we are talking
2081/// about the high or low part of an up-to-16-byte struct. This routine picks
2082/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002083/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2084/// etc).
2085///
2086/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2087/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2088/// the 8-byte value references. PrefType may be null.
2089///
2090/// SourceTy is the source level type for the entire argument. SourceOffset is
2091/// an offset into this that we're processing (which is always either 0 or 8).
2092///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002093llvm::Type *X86_64ABIInfo::
2094GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002095 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002096 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2097 // returning an 8-byte unit starting with it. See if we can safely use it.
2098 if (IROffset == 0) {
2099 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002100 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2101 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002102 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002103
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002104 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2105 // goodness in the source type is just tail padding. This is allowed to
2106 // kick in for struct {double,int} on the int, but not on
2107 // struct{double,int,int} because we wouldn't return the second int. We
2108 // have to do this analysis on the source type because we can't depend on
2109 // unions being lowered a specific way etc.
2110 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002111 IRType->isIntegerTy(32) ||
2112 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2113 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2114 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002115
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002116 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2117 SourceOffset*8+64, getContext()))
2118 return IRType;
2119 }
2120 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002121
Chris Lattner2192fe52011-07-18 04:24:23 +00002122 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002123 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002124 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002125 if (IROffset < SL->getSizeInBytes()) {
2126 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2127 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002128
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002129 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2130 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002131 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002132 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002133
Chris Lattner2192fe52011-07-18 04:24:23 +00002134 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002135 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002136 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002137 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002138 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2139 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002140 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002141
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002142 // Okay, we don't have any better idea of what to pass, so we pass this in an
2143 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002144 unsigned TySizeInBytes =
2145 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002146
Chris Lattner3f763422010-07-29 17:34:39 +00002147 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002148
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002149 // It is always safe to classify this as an integer type up to i64 that
2150 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002151 return llvm::IntegerType::get(getVMContext(),
2152 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002153}
2154
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002155
2156/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2157/// be used as elements of a two register pair to pass or return, return a
2158/// first class aggregate to represent them. For example, if the low part of
2159/// a by-value argument should be passed as i32* and the high part as float,
2160/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002161static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002162GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002163 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002164 // In order to correctly satisfy the ABI, we need to the high part to start
2165 // at offset 8. If the high and low parts we inferred are both 4-byte types
2166 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2167 // the second element at offset 8. Check for this:
2168 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2169 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002170 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002171 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002172
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002173 // To handle this, we have to increase the size of the low part so that the
2174 // second element will start at an 8 byte offset. We can't increase the size
2175 // of the second element because it might make us access off the end of the
2176 // struct.
2177 if (HiStart != 8) {
2178 // There are only two sorts of types the ABI generation code can produce for
2179 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2180 // Promote these to a larger type.
2181 if (Lo->isFloatTy())
2182 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2183 else {
2184 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2185 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2186 }
2187 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002188
Chris Lattnera5f58b02011-07-09 17:41:47 +00002189 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002190
2191
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002192 // Verify that the second element is at an 8-byte offset.
2193 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2194 "Invalid x86-64 argument pair!");
2195 return Result;
2196}
2197
Chris Lattner31faff52010-07-28 23:06:14 +00002198ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002199classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002200 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2201 // classification algorithm.
2202 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002203 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002204
2205 // Check some invariants.
2206 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002207 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2208
Chris Lattnera5f58b02011-07-09 17:41:47 +00002209 llvm::Type *ResType = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002210 switch (Lo) {
2211 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002212 if (Hi == NoClass)
2213 return ABIArgInfo::getIgnore();
2214 // If the low part is just padding, it takes no register, leave ResType
2215 // null.
2216 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2217 "Unknown missing lo part");
2218 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002219
2220 case SSEUp:
2221 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002222 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002223
2224 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2225 // hidden argument.
2226 case Memory:
2227 return getIndirectReturnResult(RetTy);
2228
2229 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2230 // available register of the sequence %rax, %rdx is used.
2231 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002232 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002233
Chris Lattner1f3a0632010-07-29 21:42:50 +00002234 // If we have a sign or zero extended integer, make sure to return Extend
2235 // so that the parameter gets the right LLVM IR attributes.
2236 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2237 // Treat an enum type as its underlying type.
2238 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2239 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002240
Chris Lattner1f3a0632010-07-29 21:42:50 +00002241 if (RetTy->isIntegralOrEnumerationType() &&
2242 RetTy->isPromotableIntegerType())
2243 return ABIArgInfo::getExtend();
2244 }
Chris Lattner31faff52010-07-28 23:06:14 +00002245 break;
2246
2247 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2248 // available SSE register of the sequence %xmm0, %xmm1 is used.
2249 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002250 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002251 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002252
2253 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2254 // returned on the X87 stack in %st0 as 80-bit x87 number.
2255 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002256 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002257 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002258
2259 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2260 // part of the value is returned in %st0 and the imaginary part in
2261 // %st1.
2262 case ComplexX87:
2263 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002264 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002265 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002266 NULL);
2267 break;
2268 }
2269
Chris Lattnera5f58b02011-07-09 17:41:47 +00002270 llvm::Type *HighPart = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002271 switch (Hi) {
2272 // Memory was handled previously and X87 should
2273 // never occur as a hi class.
2274 case Memory:
2275 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002276 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002277
2278 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002279 case NoClass:
2280 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002281
Chris Lattner52b3c132010-09-01 00:20:33 +00002282 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002283 HighPart = GetINTEGERTypeAtOffset(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;
Chris Lattner52b3c132010-09-01 00:20:33 +00002287 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002288 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002289 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2290 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002291 break;
2292
2293 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002294 // is passed in the next available eightbyte chunk if the last used
2295 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002296 //
Chris Lattner57540c52011-04-15 05:22:18 +00002297 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002298 case SSEUp:
2299 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002300 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002301 break;
2302
2303 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2304 // returned together with the previous X87 value in %st0.
2305 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002306 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002307 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002308 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002309 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002310 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002311 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002312 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2313 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002314 }
Chris Lattner31faff52010-07-28 23:06:14 +00002315 break;
2316 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002317
Chris Lattner52b3c132010-09-01 00:20:33 +00002318 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002319 // known to pass in the high eightbyte of the result. We do this by forming a
2320 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002321 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002322 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002323
Chris Lattner1f3a0632010-07-29 21:42:50 +00002324 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002325}
2326
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002327ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002328 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2329 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002330 const
2331{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002332 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002333 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002334
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002335 // Check some invariants.
2336 // FIXME: Enforce these by construction.
2337 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002338 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2339
2340 neededInt = 0;
2341 neededSSE = 0;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002342 llvm::Type *ResType = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002343 switch (Lo) {
2344 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002345 if (Hi == NoClass)
2346 return ABIArgInfo::getIgnore();
2347 // If the low part is just padding, it takes no register, leave ResType
2348 // null.
2349 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2350 "Unknown missing lo part");
2351 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002352
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002353 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2354 // on the stack.
2355 case Memory:
2356
2357 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2358 // COMPLEX_X87, it is passed in memory.
2359 case X87:
2360 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002361 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002362 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002363 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002364
2365 case SSEUp:
2366 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002367 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002368
2369 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2370 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2371 // and %r9 is used.
2372 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002373 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002374
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002375 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002376 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002377
2378 // If we have a sign or zero extended integer, make sure to return Extend
2379 // so that the parameter gets the right LLVM IR attributes.
2380 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2381 // Treat an enum type as its underlying type.
2382 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2383 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002384
Chris Lattner1f3a0632010-07-29 21:42:50 +00002385 if (Ty->isIntegralOrEnumerationType() &&
2386 Ty->isPromotableIntegerType())
2387 return ABIArgInfo::getExtend();
2388 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002389
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002390 break;
2391
2392 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2393 // available SSE register is used, the registers are taken in the
2394 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002395 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002396 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002397 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002398 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002399 break;
2400 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002401 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002402
Chris Lattnera5f58b02011-07-09 17:41:47 +00002403 llvm::Type *HighPart = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002404 switch (Hi) {
2405 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002406 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002407 // which is passed in memory.
2408 case Memory:
2409 case X87:
2410 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002411 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002412
2413 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002414
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002415 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002416 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002417 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002418 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002419
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002420 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2421 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002422 break;
2423
2424 // X87Up generally doesn't occur here (long double is passed in
2425 // memory), except in situations involving unions.
2426 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002427 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002428 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002429
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002430 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2431 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002432
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002433 ++neededSSE;
2434 break;
2435
2436 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2437 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002438 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002439 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002440 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002441 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002442 break;
2443 }
2444
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002445 // If a high part was specified, merge it together with the low part. It is
2446 // known to pass in the high eightbyte of the result. We do this by forming a
2447 // first class struct aggregate with the high and low part: {low, high}
2448 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002449 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002450
Chris Lattner1f3a0632010-07-29 21:42:50 +00002451 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002452}
2453
Chris Lattner22326a12010-07-29 02:31:05 +00002454void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002455
Chris Lattner458b2aa2010-07-29 02:16:43 +00002456 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002457
2458 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002459 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002460
2461 // If the return value is indirect, then the hidden argument is consuming one
2462 // integer register.
2463 if (FI.getReturnInfo().isIndirect())
2464 --freeIntRegs;
2465
Eli Friedman96fd2642013-06-12 00:13:45 +00002466 bool isVariadic = FI.isVariadic();
2467 unsigned numRequiredArgs = 0;
2468 if (isVariadic)
2469 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2470
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002471 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2472 // get assigned (in left-to-right order) for passing as follows...
2473 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2474 it != ie; ++it) {
Eli Friedman96fd2642013-06-12 00:13:45 +00002475 bool isNamedArg = true;
2476 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002477 isNamedArg = (it - FI.arg_begin()) <
2478 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002479
Bill Wendling9987c0e2010-10-18 23:51:38 +00002480 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002481 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002482 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002483
2484 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2485 // eightbyte of an argument, the whole argument is passed on the
2486 // stack. If registers have already been assigned for some
2487 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002488 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002489 freeIntRegs -= neededInt;
2490 freeSSERegs -= neededSSE;
2491 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002492 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002493 }
2494 }
2495}
2496
2497static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2498 QualType Ty,
2499 CodeGenFunction &CGF) {
2500 llvm::Value *overflow_arg_area_p =
2501 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2502 llvm::Value *overflow_arg_area =
2503 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2504
2505 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2506 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002507 // It isn't stated explicitly in the standard, but in practice we use
2508 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002509 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2510 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002511 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002512 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002513 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002514 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2515 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002516 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002517 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002518 overflow_arg_area =
2519 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2520 overflow_arg_area->getType(),
2521 "overflow_arg_area.align");
2522 }
2523
2524 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002525 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002526 llvm::Value *Res =
2527 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002528 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002529
2530 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2531 // l->overflow_arg_area + sizeof(type).
2532 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2533 // an 8 byte boundary.
2534
2535 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002536 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002537 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002538 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2539 "overflow_arg_area.next");
2540 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2541
2542 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2543 return Res;
2544}
2545
2546llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2547 CodeGenFunction &CGF) const {
2548 // Assume that va_list type is correct; should be pointer to LLVM type:
2549 // struct {
2550 // i32 gp_offset;
2551 // i32 fp_offset;
2552 // i8* overflow_arg_area;
2553 // i8* reg_save_area;
2554 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002555 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002556
Chris Lattner9723d6c2010-03-11 18:19:55 +00002557 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002558 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2559 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002560
2561 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2562 // in the registers. If not go to step 7.
2563 if (!neededInt && !neededSSE)
2564 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2565
2566 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2567 // general purpose registers needed to pass type and num_fp to hold
2568 // the number of floating point registers needed.
2569
2570 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2571 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2572 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2573 //
2574 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2575 // register save space).
2576
2577 llvm::Value *InRegs = 0;
2578 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2579 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2580 if (neededInt) {
2581 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2582 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002583 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2584 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002585 }
2586
2587 if (neededSSE) {
2588 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2589 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2590 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002591 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2592 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002593 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2594 }
2595
2596 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2597 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2598 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2599 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2600
2601 // Emit code to load the value if it was passed in registers.
2602
2603 CGF.EmitBlock(InRegBlock);
2604
2605 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2606 // an offset of l->gp_offset and/or l->fp_offset. This may require
2607 // copying to a temporary location in case the parameter is passed
2608 // in different register classes or requires an alignment greater
2609 // than 8 for general purpose registers and 16 for XMM registers.
2610 //
2611 // FIXME: This really results in shameful code when we end up needing to
2612 // collect arguments from different places; often what should result in a
2613 // simple assembling of a structure from scattered addresses has many more
2614 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002615 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002616 llvm::Value *RegAddr =
2617 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2618 "reg_save_area");
2619 if (neededInt && neededSSE) {
2620 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002621 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002622 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002623 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2624 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002625 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002626 llvm::Type *TyLo = ST->getElementType(0);
2627 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002628 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002629 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002630 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2631 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002632 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2633 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sands998f9d92010-02-15 16:14:01 +00002634 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2635 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002636 llvm::Value *V =
2637 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2638 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2639 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2640 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2641
Owen Anderson170229f2009-07-14 23:10:40 +00002642 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002643 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002644 } else if (neededInt) {
2645 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2646 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002647 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002648
2649 // Copy to a temporary if necessary to ensure the appropriate alignment.
2650 std::pair<CharUnits, CharUnits> SizeAlign =
2651 CGF.getContext().getTypeInfoInChars(Ty);
2652 uint64_t TySize = SizeAlign.first.getQuantity();
2653 unsigned TyAlign = SizeAlign.second.getQuantity();
2654 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002655 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2656 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2657 RegAddr = Tmp;
2658 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002659 } else if (neededSSE == 1) {
2660 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2661 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2662 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002663 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002664 assert(neededSSE == 2 && "Invalid number of needed registers!");
2665 // SSE registers are spaced 16 bytes apart in the register save
2666 // area, we need to collect the two eightbytes together.
2667 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002668 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002669 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002670 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002671 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002672 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2673 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2674 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002675 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2676 DblPtrTy));
2677 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2678 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2679 DblPtrTy));
2680 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2681 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2682 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002683 }
2684
2685 // AMD64-ABI 3.5.7p5: Step 5. Set:
2686 // l->gp_offset = l->gp_offset + num_gp * 8
2687 // l->fp_offset = l->fp_offset + num_fp * 16.
2688 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002689 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002690 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2691 gp_offset_p);
2692 }
2693 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002694 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002695 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2696 fp_offset_p);
2697 }
2698 CGF.EmitBranch(ContBlock);
2699
2700 // Emit code to load the value if it was passed in memory.
2701
2702 CGF.EmitBlock(InMemBlock);
2703 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2704
2705 // Return the appropriate result.
2706
2707 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002708 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002709 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002710 ResAddr->addIncoming(RegAddr, InRegBlock);
2711 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002712 return ResAddr;
2713}
2714
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002715ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002716
2717 if (Ty->isVoidType())
2718 return ABIArgInfo::getIgnore();
2719
2720 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2721 Ty = EnumTy->getDecl()->getIntegerType();
2722
2723 uint64_t Size = getContext().getTypeSize(Ty);
2724
2725 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002726 if (IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002727 if (isRecordReturnIndirect(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002728 return ABIArgInfo::getIndirect(0, false);
2729 } else {
Mark Lacey3825e832013-10-06 01:33:34 +00002730 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002731 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2732 }
2733
2734 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002735 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2736
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002737 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCallc8e01702013-04-16 22:48:15 +00002738 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002739 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2740 Size));
2741
2742 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2743 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2744 if (Size <= 64 &&
NAKAMURA Takumie03c6032011-01-19 00:11:33 +00002745 (Size & (Size - 1)) == 0)
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002746 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2747 Size));
2748
2749 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2750 }
2751
2752 if (Ty->isPromotableIntegerType())
2753 return ABIArgInfo::getExtend();
2754
2755 return ABIArgInfo::getDirect();
2756}
2757
2758void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2759
2760 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002761 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002762
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002763 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2764 it != ie; ++it)
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002765 it->info = classify(it->type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002766}
2767
Chris Lattner04dc9572010-08-31 16:44:54 +00002768llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2769 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002770 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002771
Chris Lattner04dc9572010-08-31 16:44:54 +00002772 CGBuilderTy &Builder = CGF.Builder;
2773 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2774 "ap");
2775 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2776 llvm::Type *PTy =
2777 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2778 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2779
2780 uint64_t Offset =
2781 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2782 llvm::Value *NextAddr =
2783 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2784 "ap.next");
2785 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2786
2787 return AddrTyped;
2788}
Chris Lattner0cf24192010-06-28 20:05:43 +00002789
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002790namespace {
2791
Derek Schuffa2020962012-10-16 22:30:41 +00002792class NaClX86_64ABIInfo : public ABIInfo {
2793 public:
2794 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2795 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Craig Topper4f12f102014-03-12 06:41:41 +00002796 void computeInfo(CGFunctionInfo &FI) const override;
2797 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2798 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00002799 private:
2800 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2801 X86_64ABIInfo NInfo; // Used for everything else.
2802};
2803
2804class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2805 public:
2806 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2807 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2808};
2809
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002810}
2811
Derek Schuffa2020962012-10-16 22:30:41 +00002812void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2813 if (FI.getASTCallingConvention() == CC_PnaclCall)
2814 PInfo.computeInfo(FI);
2815 else
2816 NInfo.computeInfo(FI);
2817}
2818
2819llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2820 CodeGenFunction &CGF) const {
2821 // Always use the native convention; calling pnacl-style varargs functions
2822 // is unuspported.
2823 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2824}
2825
2826
John McCallea8d8bb2010-03-11 00:10:12 +00002827// PowerPC-32
2828
2829namespace {
2830class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2831public:
Chris Lattner2b037972010-07-29 02:01:43 +00002832 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002833
Craig Topper4f12f102014-03-12 06:41:41 +00002834 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00002835 // This is recovered from gcc output.
2836 return 1; // r1 is the dedicated stack pointer
2837 }
2838
2839 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002840 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00002841};
2842
2843}
2844
2845bool
2846PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2847 llvm::Value *Address) const {
2848 // This is calculated from the LLVM and GCC tables and verified
2849 // against gcc output. AFAIK all ABIs use the same encoding.
2850
2851 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002852
Chris Lattnerece04092012-02-07 00:39:47 +00002853 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002854 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2855 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2856 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2857
2858 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002859 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002860
2861 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002862 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00002863
2864 // 64-76 are various 4-byte special-purpose registers:
2865 // 64: mq
2866 // 65: lr
2867 // 66: ctr
2868 // 67: ap
2869 // 68-75 cr0-7
2870 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00002871 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002872
2873 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002874 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002875
2876 // 109: vrsave
2877 // 110: vscr
2878 // 111: spe_acc
2879 // 112: spefscr
2880 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002881 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002882
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002883 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002884}
2885
Roman Divackyd966e722012-05-09 18:22:46 +00002886// PowerPC-64
2887
2888namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002889/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2890class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2891
2892public:
2893 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2894
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002895 bool isPromotableTypeForABI(QualType Ty) const;
2896
2897 ABIArgInfo classifyReturnType(QualType RetTy) const;
2898 ABIArgInfo classifyArgumentType(QualType Ty) const;
2899
Bill Schmidt84d37792012-10-12 19:26:17 +00002900 // TODO: We can add more logic to computeInfo to improve performance.
2901 // Example: For aggregate arguments that fit in a register, we could
2902 // use getDirectInReg (as is done below for structs containing a single
2903 // floating-point value) to avoid pushing them to memory on function
2904 // entry. This would require changing the logic in PPCISelLowering
2905 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00002906 void computeInfo(CGFunctionInfo &FI) const override {
Bill Schmidt84d37792012-10-12 19:26:17 +00002907 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2908 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2909 it != ie; ++it) {
2910 // We rely on the default argument classification for the most part.
2911 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00002912 // or vector item must be passed in a register if one is available.
Bill Schmidt84d37792012-10-12 19:26:17 +00002913 const Type *T = isSingleElementStruct(it->type, getContext());
2914 if (T) {
2915 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidt179afae2013-07-23 22:15:57 +00002916 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002917 QualType QT(T, 0);
2918 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2919 continue;
2920 }
2921 }
2922 it->info = classifyArgumentType(it->type);
2923 }
2924 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00002925
Craig Topper4f12f102014-03-12 06:41:41 +00002926 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2927 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00002928};
2929
2930class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2931public:
2932 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2933 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2934
Craig Topper4f12f102014-03-12 06:41:41 +00002935 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002936 // This is recovered from gcc output.
2937 return 1; // r1 is the dedicated stack pointer
2938 }
2939
2940 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002941 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00002942};
2943
Roman Divackyd966e722012-05-09 18:22:46 +00002944class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2945public:
2946 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2947
Craig Topper4f12f102014-03-12 06:41:41 +00002948 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00002949 // This is recovered from gcc output.
2950 return 1; // r1 is the dedicated stack pointer
2951 }
2952
2953 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002954 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00002955};
2956
2957}
2958
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002959// Return true if the ABI requires Ty to be passed sign- or zero-
2960// extended to 64 bits.
2961bool
2962PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2963 // Treat an enum type as its underlying type.
2964 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2965 Ty = EnumTy->getDecl()->getIntegerType();
2966
2967 // Promotable integer types are required to be promoted by the ABI.
2968 if (Ty->isPromotableIntegerType())
2969 return true;
2970
2971 // In addition to the usual promotable integer types, we also need to
2972 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2973 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2974 switch (BT->getKind()) {
2975 case BuiltinType::Int:
2976 case BuiltinType::UInt:
2977 return true;
2978 default:
2979 break;
2980 }
2981
2982 return false;
2983}
2984
2985ABIArgInfo
2986PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00002987 if (Ty->isAnyComplexType())
2988 return ABIArgInfo::getDirect();
2989
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002990 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00002991 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002992 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002993
2994 return ABIArgInfo::getIndirect(0);
2995 }
2996
2997 return (isPromotableTypeForABI(Ty) ?
2998 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2999}
3000
3001ABIArgInfo
3002PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3003 if (RetTy->isVoidType())
3004 return ABIArgInfo::getIgnore();
3005
Bill Schmidta3d121c2012-12-17 04:20:17 +00003006 if (RetTy->isAnyComplexType())
3007 return ABIArgInfo::getDirect();
3008
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003009 if (isAggregateTypeForABI(RetTy))
3010 return ABIArgInfo::getIndirect(0);
3011
3012 return (isPromotableTypeForABI(RetTy) ?
3013 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3014}
3015
Bill Schmidt25cb3492012-10-03 19:18:57 +00003016// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3017llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3018 QualType Ty,
3019 CodeGenFunction &CGF) const {
3020 llvm::Type *BP = CGF.Int8PtrTy;
3021 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3022
3023 CGBuilderTy &Builder = CGF.Builder;
3024 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3025 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3026
Bill Schmidt924c4782013-01-14 17:45:36 +00003027 // Update the va_list pointer. The pointer should be bumped by the
3028 // size of the object. We can trust getTypeSize() except for a complex
3029 // type whose base type is smaller than a doubleword. For these, the
3030 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003031 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003032 QualType BaseTy;
3033 unsigned CplxBaseSize = 0;
3034
3035 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3036 BaseTy = CTy->getElementType();
3037 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3038 if (CplxBaseSize < 8)
3039 SizeInBytes = 16;
3040 }
3041
Bill Schmidt25cb3492012-10-03 19:18:57 +00003042 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3043 llvm::Value *NextAddr =
3044 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3045 "ap.next");
3046 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3047
Bill Schmidt924c4782013-01-14 17:45:36 +00003048 // If we have a complex type and the base type is smaller than 8 bytes,
3049 // the ABI calls for the real and imaginary parts to be right-adjusted
3050 // in separate doublewords. However, Clang expects us to produce a
3051 // pointer to a structure with the two parts packed tightly. So generate
3052 // loads of the real and imaginary parts relative to the va_list pointer,
3053 // and store them to a temporary structure.
3054 if (CplxBaseSize && CplxBaseSize < 8) {
3055 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3056 llvm::Value *ImagAddr = RealAddr;
3057 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3058 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3059 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3060 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3061 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3062 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3063 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3064 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3065 "vacplx");
3066 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3067 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3068 Builder.CreateStore(Real, RealPtr, false);
3069 Builder.CreateStore(Imag, ImagPtr, false);
3070 return Ptr;
3071 }
3072
Bill Schmidt25cb3492012-10-03 19:18:57 +00003073 // If the argument is smaller than 8 bytes, it is right-adjusted in
3074 // its doubleword slot. Adjust the pointer to pick it up from the
3075 // correct offset.
3076 if (SizeInBytes < 8) {
3077 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3078 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3079 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3080 }
3081
3082 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3083 return Builder.CreateBitCast(Addr, PTy);
3084}
3085
3086static bool
3087PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3088 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003089 // This is calculated from the LLVM and GCC tables and verified
3090 // against gcc output. AFAIK all ABIs use the same encoding.
3091
3092 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3093
3094 llvm::IntegerType *i8 = CGF.Int8Ty;
3095 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3096 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3097 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3098
3099 // 0-31: r0-31, the 8-byte general-purpose registers
3100 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3101
3102 // 32-63: fp0-31, the 8-byte floating-point registers
3103 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3104
3105 // 64-76 are various 4-byte special-purpose registers:
3106 // 64: mq
3107 // 65: lr
3108 // 66: ctr
3109 // 67: ap
3110 // 68-75 cr0-7
3111 // 76: xer
3112 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3113
3114 // 77-108: v0-31, the 16-byte vector registers
3115 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3116
3117 // 109: vrsave
3118 // 110: vscr
3119 // 111: spe_acc
3120 // 112: spefscr
3121 // 113: sfp
3122 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3123
3124 return false;
3125}
John McCallea8d8bb2010-03-11 00:10:12 +00003126
Bill Schmidt25cb3492012-10-03 19:18:57 +00003127bool
3128PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3129 CodeGen::CodeGenFunction &CGF,
3130 llvm::Value *Address) const {
3131
3132 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3133}
3134
3135bool
3136PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3137 llvm::Value *Address) const {
3138
3139 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3140}
3141
Chris Lattner0cf24192010-06-28 20:05:43 +00003142//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003143// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00003144//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003145
3146namespace {
3147
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003148class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003149public:
3150 enum ABIKind {
3151 APCS = 0,
3152 AAPCS = 1,
3153 AAPCS_VFP
3154 };
3155
3156private:
3157 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00003158 mutable int VFPRegs[16];
3159 const unsigned NumVFPs;
3160 const unsigned NumGPRs;
3161 mutable unsigned AllocatedGPRs;
3162 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003163
3164public:
Oliver Stannard405bded2014-02-11 09:25:50 +00003165 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
3166 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00003167 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00003168 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00003169 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003170
John McCall3480ef22011-08-30 01:42:09 +00003171 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003172 switch (getTarget().getTriple().getEnvironment()) {
3173 case llvm::Triple::Android:
3174 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003175 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003176 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00003177 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003178 return true;
3179 default:
3180 return false;
3181 }
John McCall3480ef22011-08-30 01:42:09 +00003182 }
3183
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003184 bool isEABIHF() const {
3185 switch (getTarget().getTriple().getEnvironment()) {
3186 case llvm::Triple::EABIHF:
3187 case llvm::Triple::GNUEABIHF:
3188 return true;
3189 default:
3190 return false;
3191 }
3192 }
3193
Daniel Dunbar020daa92009-09-12 01:00:39 +00003194 ABIKind getABIKind() const { return Kind; }
3195
Tim Northovera484bc02013-10-01 14:34:25 +00003196private:
Amara Emerson9dc78782014-01-28 10:56:36 +00003197 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Oliver Stannard405bded2014-02-11 09:25:50 +00003198 ABIArgInfo classifyArgumentType(QualType RetTy, bool &IsHA, bool isVariadic,
3199 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00003200 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003201
Craig Topper4f12f102014-03-12 06:41:41 +00003202 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003203
Craig Topper4f12f102014-03-12 06:41:41 +00003204 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3205 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00003206
3207 llvm::CallingConv::ID getLLVMDefaultCC() const;
3208 llvm::CallingConv::ID getABIDefaultCC() const;
3209 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00003210
3211 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
3212 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
3213 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003214};
3215
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003216class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3217public:
Chris Lattner2b037972010-07-29 02:01:43 +00003218 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3219 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00003220
John McCall3480ef22011-08-30 01:42:09 +00003221 const ARMABIInfo &getABIInfo() const {
3222 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3223 }
3224
Craig Topper4f12f102014-03-12 06:41:41 +00003225 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00003226 return 13;
3227 }
Roman Divackyc1617352011-05-18 19:36:54 +00003228
Craig Topper4f12f102014-03-12 06:41:41 +00003229 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00003230 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3231 }
3232
Roman Divackyc1617352011-05-18 19:36:54 +00003233 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003234 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00003235 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00003236
3237 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00003238 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00003239 return false;
3240 }
John McCall3480ef22011-08-30 01:42:09 +00003241
Craig Topper4f12f102014-03-12 06:41:41 +00003242 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00003243 if (getABIInfo().isEABI()) return 88;
3244 return TargetCodeGenInfo::getSizeOfUnwindException();
3245 }
Tim Northovera484bc02013-10-01 14:34:25 +00003246
3247 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00003248 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00003249 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3250 if (!FD)
3251 return;
3252
3253 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3254 if (!Attr)
3255 return;
3256
3257 const char *Kind;
3258 switch (Attr->getInterrupt()) {
3259 case ARMInterruptAttr::Generic: Kind = ""; break;
3260 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3261 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3262 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3263 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3264 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3265 }
3266
3267 llvm::Function *Fn = cast<llvm::Function>(GV);
3268
3269 Fn->addFnAttr("interrupt", Kind);
3270
3271 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3272 return;
3273
3274 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3275 // however this is not necessarily true on taking any interrupt. Instruct
3276 // the backend to perform a realignment as part of the function prologue.
3277 llvm::AttrBuilder B;
3278 B.addStackAlignmentAttr(8);
3279 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3280 llvm::AttributeSet::get(CGM.getLLVMContext(),
3281 llvm::AttributeSet::FunctionIndex,
3282 B));
3283 }
3284
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003285};
3286
Daniel Dunbard59655c2009-09-12 00:59:49 +00003287}
3288
Chris Lattner22326a12010-07-29 02:31:05 +00003289void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003290 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00003291 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00003292 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3293 // VFP registers of the appropriate type unallocated then the argument is
3294 // allocated to the lowest-numbered sequence of such registers.
3295 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3296 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00003297 resetAllocatedRegs();
3298
Amara Emerson9dc78782014-01-28 10:56:36 +00003299 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003300 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Manman Ren2a523d82012-10-30 23:21:41 +00003301 it != ie; ++it) {
Oliver Stannard405bded2014-02-11 09:25:50 +00003302 unsigned PreAllocationVFPs = AllocatedVFPs;
3303 unsigned PreAllocationGPRs = AllocatedGPRs;
Manman Ren2a523d82012-10-30 23:21:41 +00003304 bool IsHA = false;
Oliver Stannard405bded2014-02-11 09:25:50 +00003305 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00003306 // 6.1.2.3 There is one VFP co-processor register class using registers
3307 // s0-s15 (d0-d7) for passing arguments.
Oliver Stannard405bded2014-02-11 09:25:50 +00003308 it->info = classifyArgumentType(it->type, IsHA, FI.isVariadic(), IsCPRC);
3309 assert((IsCPRC || !IsHA) && "Homogeneous aggregates must be CPRCs");
Manman Ren2a523d82012-10-30 23:21:41 +00003310 // If we do not have enough VFP registers for the HA, any VFP registers
3311 // that are unallocated are marked as unavailable. To achieve this, we add
Oliver Stannard405bded2014-02-11 09:25:50 +00003312 // padding of (NumVFPs - PreAllocationVFP) floats.
Amara Emerson9dc78782014-01-28 10:56:36 +00003313 // Note that IsHA will only be set when using the AAPCS-VFP calling convention,
3314 // and the callee is not variadic.
Oliver Stannard405bded2014-02-11 09:25:50 +00003315 if (IsHA && AllocatedVFPs > NumVFPs && PreAllocationVFPs < NumVFPs) {
Manman Ren2a523d82012-10-30 23:21:41 +00003316 llvm::Type *PaddingTy = llvm::ArrayType::get(
Oliver Stannard405bded2014-02-11 09:25:50 +00003317 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocationVFPs);
3318 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3319 }
3320
3321 // If we have allocated some arguments onto the stack (due to running
3322 // out of VFP registers), we cannot split an argument between GPRs and
3323 // the stack. If this situation occurs, we add padding to prevent the
3324 // GPRs from being used. In this situiation, the current argument could
3325 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
3326 // unusable anyway.
3327 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
3328 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs && StackUsed) {
3329 llvm::Type *PaddingTy = llvm::ArrayType::get(
3330 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Manman Ren2a523d82012-10-30 23:21:41 +00003331 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3332 }
3333 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003334
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003335 // Always honor user-specified calling convention.
3336 if (FI.getCallingConvention() != llvm::CallingConv::C)
3337 return;
3338
John McCall882987f2013-02-28 19:01:20 +00003339 llvm::CallingConv::ID cc = getRuntimeCC();
3340 if (cc != llvm::CallingConv::C)
3341 FI.setEffectiveCallingConvention(cc);
3342}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00003343
John McCall882987f2013-02-28 19:01:20 +00003344/// Return the default calling convention that LLVM will use.
3345llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3346 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003347 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00003348 return llvm::CallingConv::ARM_AAPCS_VFP;
3349 else if (isEABI())
3350 return llvm::CallingConv::ARM_AAPCS;
3351 else
3352 return llvm::CallingConv::ARM_APCS;
3353}
3354
3355/// Return the calling convention that our ABI would like us to use
3356/// as the C calling convention.
3357llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003358 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00003359 case APCS: return llvm::CallingConv::ARM_APCS;
3360 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3361 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003362 }
John McCall882987f2013-02-28 19:01:20 +00003363 llvm_unreachable("bad ABI kind");
3364}
3365
3366void ARMABIInfo::setRuntimeCC() {
3367 assert(getRuntimeCC() == llvm::CallingConv::C);
3368
3369 // Don't muddy up the IR with a ton of explicit annotations if
3370 // they'd just match what LLVM will infer from the triple.
3371 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3372 if (abiCC != getLLVMDefaultCC())
3373 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003374}
3375
Bob Wilsone826a2a2011-08-03 05:58:22 +00003376/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3377/// aggregate. If HAMembers is non-null, the number of base elements
3378/// contained in the type is returned through it; this is used for the
3379/// recursive calls that check aggregate component types.
3380static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3381 ASTContext &Context,
3382 uint64_t *HAMembers = 0) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003383 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003384 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3385 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3386 return false;
3387 Members *= AT->getSize().getZExtValue();
3388 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3389 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003390 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00003391 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003392
Bob Wilsone826a2a2011-08-03 05:58:22 +00003393 Members = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003394 for (const auto *FD : RD->fields()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00003395 uint64_t FldMembers;
3396 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3397 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003398
3399 Members = (RD->isUnion() ?
3400 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003401 }
3402 } else {
3403 Members = 1;
3404 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3405 Members = 2;
3406 Ty = CT->getElementType();
3407 }
3408
3409 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3410 // double, or 64-bit or 128-bit vectors.
3411 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3412 if (BT->getKind() != BuiltinType::Float &&
Tim Northovereb752d42012-07-20 22:29:29 +00003413 BT->getKind() != BuiltinType::Double &&
3414 BT->getKind() != BuiltinType::LongDouble)
Bob Wilsone826a2a2011-08-03 05:58:22 +00003415 return false;
3416 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3417 unsigned VecSize = Context.getTypeSize(VT);
3418 if (VecSize != 64 && VecSize != 128)
3419 return false;
3420 } else {
3421 return false;
3422 }
3423
3424 // The base type must be the same for all members. Vector types of the
3425 // same total size are treated as being equivalent here.
3426 const Type *TyPtr = Ty.getTypePtr();
3427 if (!Base)
3428 Base = TyPtr;
Oliver Stannard5e8558f2014-02-07 11:25:57 +00003429
3430 if (Base != TyPtr) {
3431 // Homogeneous aggregates are defined as containing members with the
3432 // same machine type. There are two cases in which two members have
3433 // different TypePtrs but the same machine type:
3434
3435 // 1) Vectors of the same length, regardless of the type and number
3436 // of their members.
3437 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
3438 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
3439
3440 // 2) In the 32-bit AAPCS, `double' and `long double' have the same
3441 // machine type. This is not the case for the 64-bit AAPCS.
3442 const bool SameSizeDoubles =
3443 ( ( Base->isSpecificBuiltinType(BuiltinType::Double)
3444 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
3445 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble)
3446 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
3447 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
3448
3449 if (!SameLengthVectors && !SameSizeDoubles)
3450 return false;
3451 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003452 }
3453
3454 // Homogeneous Aggregates can have at most 4 members of the base type.
3455 if (HAMembers)
3456 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003457
3458 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003459}
3460
Manman Renb505d332012-10-31 19:02:26 +00003461/// markAllocatedVFPs - update VFPRegs according to the alignment and
3462/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00003463void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
3464 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00003465 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00003466 if (AllocatedVFPs >= 16) {
3467 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
3468 // the stack.
3469 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00003470 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00003471 }
Manman Renb505d332012-10-31 19:02:26 +00003472 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3473 // VFP registers of the appropriate type unallocated then the argument is
3474 // allocated to the lowest-numbered sequence of such registers.
3475 for (unsigned I = 0; I < 16; I += Alignment) {
3476 bool FoundSlot = true;
3477 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3478 if (J >= 16 || VFPRegs[J]) {
3479 FoundSlot = false;
3480 break;
3481 }
3482 if (FoundSlot) {
3483 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3484 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00003485 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00003486 return;
3487 }
3488 }
3489 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3490 // unallocated are marked as unavailable.
3491 for (unsigned I = 0; I < 16; I++)
3492 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00003493 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00003494}
3495
Oliver Stannard405bded2014-02-11 09:25:50 +00003496/// Update AllocatedGPRs to record the number of general purpose registers
3497/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
3498/// this represents arguments being stored on the stack.
3499void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
3500 unsigned NumRequired) const {
3501 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
3502
3503 if (Alignment == 2 && AllocatedGPRs & 0x1)
3504 AllocatedGPRs += 1;
3505
3506 AllocatedGPRs += NumRequired;
3507}
3508
3509void ARMABIInfo::resetAllocatedRegs(void) const {
3510 AllocatedGPRs = 0;
3511 AllocatedVFPs = 0;
3512 for (unsigned i = 0; i < NumVFPs; ++i)
3513 VFPRegs[i] = 0;
3514}
3515
3516ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool &IsHA,
3517 bool isVariadic,
3518 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003519 // We update number of allocated VFPs according to
3520 // 6.1.2.1 The following argument types are VFP CPRCs:
3521 // A single-precision floating-point type (including promoted
3522 // half-precision types); A double-precision floating-point type;
3523 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3524 // with a Base Type of a single- or double-precision floating-point type,
3525 // 64-bit containerized vectors or 128-bit containerized vectors with one
3526 // to four Elements.
3527
Manman Renfef9e312012-10-16 19:18:39 +00003528 // Handle illegal vector types here.
3529 if (isIllegalVectorType(Ty)) {
3530 uint64_t Size = getContext().getTypeSize(Ty);
3531 if (Size <= 32) {
3532 llvm::Type *ResType =
3533 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00003534 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00003535 return ABIArgInfo::getDirect(ResType);
3536 }
3537 if (Size == 64) {
3538 llvm::Type *ResType = llvm::VectorType::get(
3539 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00003540 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
3541 markAllocatedGPRs(2, 2);
3542 } else {
3543 markAllocatedVFPs(2, 2);
3544 IsCPRC = true;
3545 }
Manman Renfef9e312012-10-16 19:18:39 +00003546 return ABIArgInfo::getDirect(ResType);
3547 }
3548 if (Size == 128) {
3549 llvm::Type *ResType = llvm::VectorType::get(
3550 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00003551 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
3552 markAllocatedGPRs(2, 4);
3553 } else {
3554 markAllocatedVFPs(4, 4);
3555 IsCPRC = true;
3556 }
Manman Renfef9e312012-10-16 19:18:39 +00003557 return ABIArgInfo::getDirect(ResType);
3558 }
Oliver Stannard405bded2014-02-11 09:25:50 +00003559 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00003560 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3561 }
Manman Renb505d332012-10-31 19:02:26 +00003562 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00003563 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
3564 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3565 uint64_t Size = getContext().getTypeSize(VT);
3566 // Size of a legal vector should be power of 2 and above 64.
3567 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
3568 IsCPRC = true;
3569 }
Manman Ren2a523d82012-10-30 23:21:41 +00003570 }
Manman Renb505d332012-10-31 19:02:26 +00003571 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00003572 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
3573 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3574 if (BT->getKind() == BuiltinType::Half ||
3575 BT->getKind() == BuiltinType::Float) {
3576 markAllocatedVFPs(1, 1);
3577 IsCPRC = true;
3578 }
3579 if (BT->getKind() == BuiltinType::Double ||
3580 BT->getKind() == BuiltinType::LongDouble) {
3581 markAllocatedVFPs(2, 2);
3582 IsCPRC = true;
3583 }
3584 }
Manman Ren2a523d82012-10-30 23:21:41 +00003585 }
Manman Renfef9e312012-10-16 19:18:39 +00003586
John McCalla1dee5302010-08-22 10:59:02 +00003587 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003588 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00003589 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003590 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00003591 }
Douglas Gregora71cc152010-02-02 20:10:50 +00003592
Oliver Stannard405bded2014-02-11 09:25:50 +00003593 unsigned Size = getContext().getTypeSize(Ty);
3594 if (!IsCPRC)
3595 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003596 return (Ty->isPromotableIntegerType() ?
3597 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003598 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003599
Oliver Stannard405bded2014-02-11 09:25:50 +00003600 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
3601 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00003602 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00003603 }
Tim Northover1060eae2013-06-21 22:49:34 +00003604
Daniel Dunbar09d33622009-09-14 21:54:03 +00003605 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003606 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00003607 return ABIArgInfo::getIgnore();
3608
Amara Emerson9dc78782014-01-28 10:56:36 +00003609 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
Manman Ren2a523d82012-10-30 23:21:41 +00003610 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3611 // into VFP registers.
Bob Wilsone826a2a2011-08-03 05:58:22 +00003612 const Type *Base = 0;
Manman Ren2a523d82012-10-30 23:21:41 +00003613 uint64_t Members = 0;
3614 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003615 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00003616 // Base can be a floating-point or a vector.
3617 if (Base->isVectorType()) {
3618 // ElementSize is in number of floats.
3619 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00003620 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00003621 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00003622 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00003623 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00003624 else {
3625 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3626 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00003627 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003628 }
3629 IsHA = true;
Oliver Stannard405bded2014-02-11 09:25:50 +00003630 IsCPRC = true;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003631 return ABIArgInfo::getExpand();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003632 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003633 }
3634
Manman Ren6c30e132012-08-13 21:23:55 +00003635 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00003636 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3637 // most 8-byte. We realign the indirect argument if type alignment is bigger
3638 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00003639 uint64_t ABIAlign = 4;
3640 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3641 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3642 getABIKind() == ARMABIInfo::AAPCS)
3643 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00003644 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard405bded2014-02-11 09:25:50 +00003645 // Update Allocated GPRs
3646 markAllocatedGPRs(1, 1);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00003647 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00003648 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00003649 }
3650
Daniel Dunbarb34b0802010-09-23 01:54:28 +00003651 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00003652 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003653 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00003654 // FIXME: Try to match the types of the arguments more accurately where
3655 // we can.
3656 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00003657 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3658 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00003659 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00003660 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00003661 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3662 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00003663 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00003664 }
Stuart Hastings4b214952011-04-28 18:16:06 +00003665
Chris Lattnera5f58b02011-07-09 17:41:47 +00003666 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00003667 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastings4b214952011-04-28 18:16:06 +00003668 return ABIArgInfo::getDirect(STy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003669}
3670
Chris Lattner458b2aa2010-07-29 02:16:43 +00003671static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003672 llvm::LLVMContext &VMContext) {
3673 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3674 // is called integer-like if its size is less than or equal to one word, and
3675 // the offset of each of its addressable sub-fields is zero.
3676
3677 uint64_t Size = Context.getTypeSize(Ty);
3678
3679 // Check that the type fits in a word.
3680 if (Size > 32)
3681 return false;
3682
3683 // FIXME: Handle vector types!
3684 if (Ty->isVectorType())
3685 return false;
3686
Daniel Dunbard53bac72009-09-14 02:20:34 +00003687 // Float types are never treated as "integer like".
3688 if (Ty->isRealFloatingType())
3689 return false;
3690
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003691 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00003692 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003693 return true;
3694
Daniel Dunbar96ebba52010-02-01 23:31:26 +00003695 // Small complex integer types are "integer like".
3696 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3697 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003698
3699 // Single element and zero sized arrays should be allowed, by the definition
3700 // above, but they are not.
3701
3702 // Otherwise, it must be a record type.
3703 const RecordType *RT = Ty->getAs<RecordType>();
3704 if (!RT) return false;
3705
3706 // Ignore records with flexible arrays.
3707 const RecordDecl *RD = RT->getDecl();
3708 if (RD->hasFlexibleArrayMember())
3709 return false;
3710
3711 // Check that all sub-fields are at offset 0, and are themselves "integer
3712 // like".
3713 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3714
3715 bool HadField = false;
3716 unsigned idx = 0;
3717 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3718 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00003719 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003720
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003721 // Bit-fields are not addressable, we only need to verify they are "integer
3722 // like". We still have to disallow a subsequent non-bitfield, for example:
3723 // struct { int : 0; int x }
3724 // is non-integer like according to gcc.
3725 if (FD->isBitField()) {
3726 if (!RD->isUnion())
3727 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003728
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003729 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3730 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003731
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003732 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003733 }
3734
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003735 // Check if this field is at offset 0.
3736 if (Layout.getFieldOffset(idx) != 0)
3737 return false;
3738
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003739 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3740 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003741
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003742 // Only allow at most one field in a structure. This doesn't match the
3743 // wording above, but follows gcc in situations with a field following an
3744 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003745 if (!RD->isUnion()) {
3746 if (HadField)
3747 return false;
3748
3749 HadField = true;
3750 }
3751 }
3752
3753 return true;
3754}
3755
Oliver Stannard405bded2014-02-11 09:25:50 +00003756ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
3757 bool isVariadic) const {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003758 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003759 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003760
Daniel Dunbar19964db2010-09-23 01:54:32 +00003761 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00003762 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
3763 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00003764 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00003765 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00003766
John McCalla1dee5302010-08-22 10:59:02 +00003767 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003768 // Treat an enum type as its underlying type.
3769 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3770 RetTy = EnumTy->getDecl()->getIntegerType();
3771
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003772 return (RetTy->isPromotableIntegerType() ?
3773 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003774 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003775
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003776 // Structures with either a non-trivial destructor or a non-trivial
3777 // copy constructor are always indirect.
Oliver Stannard405bded2014-02-11 09:25:50 +00003778 if (isRecordReturnIndirect(RetTy, getCXXABI())) {
3779 markAllocatedGPRs(1, 1);
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003780 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Oliver Stannard405bded2014-02-11 09:25:50 +00003781 }
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003782
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003783 // Are we following APCS?
3784 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00003785 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003786 return ABIArgInfo::getIgnore();
3787
Daniel Dunbareedf1512010-02-01 23:31:19 +00003788 // Complex types are all returned as packed integers.
3789 //
3790 // FIXME: Consider using 2 x vector types if the back end handles them
3791 // correctly.
3792 if (RetTy->isAnyComplexType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003793 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00003794 getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00003795
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003796 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003797 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003798 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003799 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003800 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003801 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003802 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003803 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3804 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003805 }
3806
3807 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00003808 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003809 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003810 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003811
3812 // Otherwise this is an AAPCS variant.
3813
Chris Lattner458b2aa2010-07-29 02:16:43 +00003814 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003815 return ABIArgInfo::getIgnore();
3816
Bob Wilson1d9269a2011-11-02 04:51:36 +00003817 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00003818 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Bob Wilson1d9269a2011-11-02 04:51:36 +00003819 const Type *Base = 0;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003820 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3821 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00003822 // Homogeneous Aggregates are returned directly.
3823 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003824 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00003825 }
3826
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003827 // Aggregates <= 4 bytes are returned in r0; other aggregates
3828 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003829 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003830 if (Size <= 32) {
3831 // Return in the smallest viable integer type.
3832 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003833 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003834 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003835 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3836 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003837 }
3838
Oliver Stannard405bded2014-02-11 09:25:50 +00003839 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003840 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003841}
3842
Manman Renfef9e312012-10-16 19:18:39 +00003843/// isIllegalVector - check whether Ty is an illegal vector type.
3844bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3845 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3846 // Check whether VT is legal.
3847 unsigned NumElements = VT->getNumElements();
3848 uint64_t Size = getContext().getTypeSize(VT);
3849 // NumElements should be power of 2.
3850 if ((NumElements & (NumElements - 1)) != 0)
3851 return true;
3852 // Size should be greater than 32 bits.
3853 return Size <= 32;
3854 }
3855 return false;
3856}
3857
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003858llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003859 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003860 llvm::Type *BP = CGF.Int8PtrTy;
3861 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003862
3863 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00003864 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003865 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00003866
Tim Northover1711cc92013-06-21 23:05:33 +00003867 if (isEmptyRecord(getContext(), Ty, true)) {
3868 // These are ignored for parameter passing purposes.
3869 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3870 return Builder.CreateBitCast(Addr, PTy);
3871 }
3872
Manman Rencca54d02012-10-16 19:01:37 +00003873 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00003874 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00003875 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00003876
3877 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3878 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00003879 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3880 getABIKind() == ARMABIInfo::AAPCS)
3881 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3882 else
3883 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00003884 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3885 if (isIllegalVectorType(Ty) && Size > 16) {
3886 IsIndirect = true;
3887 Size = 4;
3888 TyAlign = 4;
3889 }
Manman Rencca54d02012-10-16 19:01:37 +00003890
3891 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00003892 if (TyAlign > 4) {
3893 assert((TyAlign & (TyAlign - 1)) == 0 &&
3894 "Alignment is not power of 2!");
3895 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3896 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3897 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00003898 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00003899 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003900
3901 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00003902 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003903 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003904 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003905 "ap.next");
3906 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3907
Manman Renfef9e312012-10-16 19:18:39 +00003908 if (IsIndirect)
3909 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00003910 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00003911 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3912 // may not be correctly aligned for the vector type. We create an aligned
3913 // temporary space and copy the content over from ap.cur to the temporary
3914 // space. This is necessary if the natural alignment of the type is greater
3915 // than the ABI alignment.
3916 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3917 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3918 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3919 "var.align");
3920 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3921 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3922 Builder.CreateMemCpy(Dst, Src,
3923 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3924 TyAlign, false);
3925 Addr = AlignedTemp; //The content is in aligned location.
3926 }
3927 llvm::Type *PTy =
3928 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3929 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3930
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003931 return AddrTyped;
3932}
3933
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003934namespace {
3935
Derek Schuffa2020962012-10-16 22:30:41 +00003936class NaClARMABIInfo : public ABIInfo {
3937 public:
3938 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3939 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00003940 void computeInfo(CGFunctionInfo &FI) const override;
3941 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3942 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00003943 private:
3944 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3945 ARMABIInfo NInfo; // Used for everything else.
3946};
3947
3948class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3949 public:
3950 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3951 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3952};
3953
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003954}
3955
Derek Schuffa2020962012-10-16 22:30:41 +00003956void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3957 if (FI.getASTCallingConvention() == CC_PnaclCall)
3958 PInfo.computeInfo(FI);
3959 else
3960 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3961}
3962
3963llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3964 CodeGenFunction &CGF) const {
3965 // Always use the native convention; calling pnacl-style varargs functions
3966 // is unsupported.
3967 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3968}
3969
Chris Lattner0cf24192010-06-28 20:05:43 +00003970//===----------------------------------------------------------------------===//
Tim Northover9bb857a2013-01-31 12:13:10 +00003971// AArch64 ABI Implementation
3972//===----------------------------------------------------------------------===//
3973
3974namespace {
3975
3976class AArch64ABIInfo : public ABIInfo {
3977public:
3978 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3979
3980private:
3981 // The AArch64 PCS is explicit about return types and argument types being
3982 // handled identically, so we don't need to draw a distinction between
3983 // Argument and Return classification.
3984 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3985 int &FreeVFPRegs) const;
3986
3987 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3988 llvm::Type *DirectTy = 0) const;
3989
Craig Topper4f12f102014-03-12 06:41:41 +00003990 void computeInfo(CGFunctionInfo &FI) const override;
Tim Northover9bb857a2013-01-31 12:13:10 +00003991
Craig Topper4f12f102014-03-12 06:41:41 +00003992 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3993 CodeGenFunction &CGF) const override;
Tim Northover9bb857a2013-01-31 12:13:10 +00003994};
3995
3996class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3997public:
3998 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3999 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
4000
4001 const AArch64ABIInfo &getABIInfo() const {
4002 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
4003 }
4004
Craig Topper4f12f102014-03-12 06:41:41 +00004005 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tim Northover9bb857a2013-01-31 12:13:10 +00004006 return 31;
4007 }
4008
4009 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004010 llvm::Value *Address) const override {
Tim Northover9bb857a2013-01-31 12:13:10 +00004011 // 0-31 are x0-x30 and sp: 8 bytes each
4012 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
4013 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
4014
4015 // 64-95 are v0-v31: 16 bytes each
4016 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
4017 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
4018
4019 return false;
4020 }
4021
4022};
4023
4024}
4025
4026void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4027 int FreeIntRegs = 8, FreeVFPRegs = 8;
4028
4029 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
4030 FreeIntRegs, FreeVFPRegs);
4031
4032 FreeIntRegs = FreeVFPRegs = 8;
4033 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4034 it != ie; ++it) {
4035 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
4036
4037 }
4038}
4039
4040ABIArgInfo
4041AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
4042 bool IsInt, llvm::Type *DirectTy) const {
4043 if (FreeRegs >= RegsNeeded) {
4044 FreeRegs -= RegsNeeded;
4045 return ABIArgInfo::getDirect(DirectTy);
4046 }
4047
4048 llvm::Type *Padding = 0;
4049
4050 // We need padding so that later arguments don't get filled in anyway. That
4051 // wouldn't happen if only ByVal arguments followed in the same category, but
4052 // a large structure will simply seem to be a pointer as far as LLVM is
4053 // concerned.
4054 if (FreeRegs > 0) {
4055 if (IsInt)
4056 Padding = llvm::Type::getInt64Ty(getVMContext());
4057 else
4058 Padding = llvm::Type::getFloatTy(getVMContext());
4059
4060 // Either [N x i64] or [N x float].
4061 Padding = llvm::ArrayType::get(Padding, FreeRegs);
4062 FreeRegs = 0;
4063 }
4064
4065 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
4066 /*IsByVal=*/ true, /*Realign=*/ false,
4067 Padding);
4068}
4069
4070
4071ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
4072 int &FreeIntRegs,
4073 int &FreeVFPRegs) const {
4074 // Can only occurs for return, but harmless otherwise.
4075 if (Ty->isVoidType())
4076 return ABIArgInfo::getIgnore();
4077
4078 // Large vector types should be returned via memory. There's no such concept
4079 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
4080 // classified they'd go into memory (see B.3).
4081 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
4082 if (FreeIntRegs > 0)
4083 --FreeIntRegs;
4084 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4085 }
4086
4087 // All non-aggregate LLVM types have a concrete ABI representation so they can
4088 // be passed directly. After this block we're guaranteed to be in a
4089 // complicated case.
4090 if (!isAggregateTypeForABI(Ty)) {
4091 // Treat an enum type as its underlying type.
4092 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4093 Ty = EnumTy->getDecl()->getIntegerType();
4094
4095 if (Ty->isFloatingType() || Ty->isVectorType())
4096 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
4097
4098 assert(getContext().getTypeSize(Ty) <= 128 &&
4099 "unexpectedly large scalar type");
4100
4101 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
4102
4103 // If the type may need padding registers to ensure "alignment", we must be
4104 // careful when this is accounted for. Increasing the effective size covers
4105 // all cases.
4106 if (getContext().getTypeAlign(Ty) == 128)
4107 RegsNeeded += FreeIntRegs % 2 != 0;
4108
4109 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
4110 }
4111
Mark Lacey3825e832013-10-06 01:33:34 +00004112 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004113 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northover9bb857a2013-01-31 12:13:10 +00004114 --FreeIntRegs;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004115 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northover9bb857a2013-01-31 12:13:10 +00004116 }
4117
4118 if (isEmptyRecord(getContext(), Ty, true)) {
4119 if (!getContext().getLangOpts().CPlusPlus) {
4120 // Empty structs outside C++ mode are a GNU extension, so no ABI can
4121 // possibly tell us what to do. It turns out (I believe) that GCC ignores
4122 // the object for parameter-passsing purposes.
4123 return ABIArgInfo::getIgnore();
4124 }
4125
4126 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
4127 // description of va_arg in the PCS require that an empty struct does
4128 // actually occupy space for parameter-passing. I'm hoping for a
4129 // clarification giving an explicit paragraph to point to in future.
4130 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
4131 llvm::Type::getInt8Ty(getVMContext()));
4132 }
4133
4134 // Homogeneous vector aggregates get passed in registers or on the stack.
4135 const Type *Base = 0;
4136 uint64_t NumMembers = 0;
4137 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
4138 assert(Base && "Base class should be set for homogeneous aggregate");
4139 // Homogeneous aggregates are passed and returned directly.
4140 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
4141 /*IsInt=*/ false);
4142 }
4143
4144 uint64_t Size = getContext().getTypeSize(Ty);
4145 if (Size <= 128) {
4146 // Small structs can use the same direct type whether they're in registers
4147 // or on the stack.
4148 llvm::Type *BaseTy;
4149 unsigned NumBases;
4150 int SizeInRegs = (Size + 63) / 64;
4151
4152 if (getContext().getTypeAlign(Ty) == 128) {
4153 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
4154 NumBases = 1;
4155
4156 // If the type may need padding registers to ensure "alignment", we must
4157 // be careful when this is accounted for. Increasing the effective size
4158 // covers all cases.
4159 SizeInRegs += FreeIntRegs % 2 != 0;
4160 } else {
4161 BaseTy = llvm::Type::getInt64Ty(getVMContext());
4162 NumBases = SizeInRegs;
4163 }
4164 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
4165
4166 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
4167 /*IsInt=*/ true, DirectTy);
4168 }
4169
4170 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
4171 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
4172 --FreeIntRegs;
4173 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
4174}
4175
4176llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4177 CodeGenFunction &CGF) const {
4178 // The AArch64 va_list type and handling is specified in the Procedure Call
4179 // Standard, section B.4:
4180 //
4181 // struct {
4182 // void *__stack;
4183 // void *__gr_top;
4184 // void *__vr_top;
4185 // int __gr_offs;
4186 // int __vr_offs;
4187 // };
4188
Tim Northover9bb857a2013-01-31 12:13:10 +00004189 int FreeIntRegs = 8, FreeVFPRegs = 8;
4190 Ty = CGF.getContext().getCanonicalType(Ty);
4191 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
4192
4193 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4194 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4195 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4196 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4197
4198 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
4199 int reg_top_index;
4200 int RegSize;
4201 if (FreeIntRegs < 8) {
4202 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
4203 // 3 is the field number of __gr_offs
4204 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4205 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4206 reg_top_index = 1; // field number for __gr_top
4207 RegSize = 8 * (8 - FreeIntRegs);
4208 } else {
4209 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
4210 // 4 is the field number of __vr_offs.
4211 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4212 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4213 reg_top_index = 2; // field number for __vr_top
4214 RegSize = 16 * (8 - FreeVFPRegs);
4215 }
4216
4217 //=======================================
4218 // Find out where argument was passed
4219 //=======================================
4220
4221 // If reg_offs >= 0 we're already using the stack for this type of
4222 // argument. We don't want to keep updating reg_offs (in case it overflows,
4223 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4224 // whatever they get).
4225 llvm::Value *UsingStack = 0;
4226 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
4227 llvm::ConstantInt::get(CGF.Int32Ty, 0));
4228
4229 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4230
4231 // Otherwise, at least some kind of argument could go in these registers, the
4232 // quesiton is whether this particular type is too big.
4233 CGF.EmitBlock(MaybeRegBlock);
4234
4235 // Integer arguments may need to correct register alignment (for example a
4236 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4237 // align __gr_offs to calculate the potential address.
4238 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4239 int Align = getContext().getTypeAlign(Ty) / 8;
4240
4241 reg_offs = CGF.Builder.CreateAdd(reg_offs,
4242 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4243 "align_regoffs");
4244 reg_offs = CGF.Builder.CreateAnd(reg_offs,
4245 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4246 "aligned_regoffs");
4247 }
4248
4249 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4250 llvm::Value *NewOffset = 0;
4251 NewOffset = CGF.Builder.CreateAdd(reg_offs,
4252 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4253 "new_reg_offs");
4254 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4255
4256 // Now we're in a position to decide whether this argument really was in
4257 // registers or not.
4258 llvm::Value *InRegs = 0;
4259 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4260 llvm::ConstantInt::get(CGF.Int32Ty, 0),
4261 "inreg");
4262
4263 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4264
4265 //=======================================
4266 // Argument was in registers
4267 //=======================================
4268
4269 // Now we emit the code for if the argument was originally passed in
4270 // registers. First start the appropriate block:
4271 CGF.EmitBlock(InRegBlock);
4272
4273 llvm::Value *reg_top_p = 0, *reg_top = 0;
4274 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4275 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4276 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4277 llvm::Value *RegAddr = 0;
4278 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4279
4280 if (!AI.isDirect()) {
4281 // If it's been passed indirectly (actually a struct), whatever we find from
4282 // stored registers or on the stack will actually be a struct **.
4283 MemTy = llvm::PointerType::getUnqual(MemTy);
4284 }
4285
4286 const Type *Base = 0;
4287 uint64_t NumMembers;
4288 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4289 && NumMembers > 1) {
4290 // Homogeneous aggregates passed in registers will have their elements split
4291 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4292 // qN+1, ...). We reload and store into a temporary local variable
4293 // contiguously.
4294 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4295 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4296 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4297 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
Christian Pirkerf5164222014-03-14 11:51:06 +00004298 int Offset = 0;
Tim Northover9bb857a2013-01-31 12:13:10 +00004299
Christian Pirkerf5164222014-03-14 11:51:06 +00004300 if (CGF.CGM.getDataLayout().isBigEndian() &&
4301 getContext().getTypeSize(Base) < 128)
4302 Offset = 16 - getContext().getTypeSize(Base)/8;
Tim Northover9bb857a2013-01-31 12:13:10 +00004303 for (unsigned i = 0; i < NumMembers; ++i) {
Christian Pirkerf5164222014-03-14 11:51:06 +00004304 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty,
4305 16 * i + Offset);
Tim Northover9bb857a2013-01-31 12:13:10 +00004306 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4307 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4308 llvm::PointerType::getUnqual(BaseTy));
4309 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4310
4311 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4312 CGF.Builder.CreateStore(Elem, StoreAddr);
4313 }
4314
4315 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4316 } else {
4317 // Otherwise the object is contiguous in memory
Christian Pirkerf5164222014-03-14 11:51:06 +00004318 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
4319 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4320 getContext().getTypeSize(Ty) < (BeAlign * 8)) {
4321 int Offset = BeAlign - getContext().getTypeSize(Ty)/8;
4322 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4323
4324 BaseAddr = CGF.Builder.CreateAdd(BaseAddr,
4325 llvm::ConstantInt::get(CGF.Int64Ty,
4326 Offset),
4327 "align_be");
4328
4329 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4330 }
4331
Tim Northover9bb857a2013-01-31 12:13:10 +00004332 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4333 }
4334
4335 CGF.EmitBranch(ContBlock);
4336
4337 //=======================================
4338 // Argument was on the stack
4339 //=======================================
4340 CGF.EmitBlock(OnStackBlock);
4341
4342 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4343 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4344 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4345
4346 // Again, stack arguments may need realigmnent. In this case both integer and
4347 // floating-point ones might be affected.
4348 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4349 int Align = getContext().getTypeAlign(Ty) / 8;
4350
4351 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4352
4353 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4354 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4355 "align_stack");
4356 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4357 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4358 "align_stack");
4359
4360 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4361 }
4362
4363 uint64_t StackSize;
4364 if (AI.isDirect())
4365 StackSize = getContext().getTypeSize(Ty) / 8;
4366 else
4367 StackSize = 8;
4368
4369 // All stack slots are 8 bytes
4370 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4371
4372 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4373 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4374 "new_stack");
4375
4376 // Write the new value of __stack for the next call to va_arg
4377 CGF.Builder.CreateStore(NewStack, stack_p);
4378
Christian Pirkerf5164222014-03-14 11:51:06 +00004379 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4380 getContext().getTypeSize(Ty) < 64 ) {
4381 int Offset = 8 - getContext().getTypeSize(Ty)/8;
4382 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4383
4384 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4385 llvm::ConstantInt::get(CGF.Int64Ty,
4386 Offset),
4387 "align_be");
4388
4389 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4390 }
4391
Tim Northover9bb857a2013-01-31 12:13:10 +00004392 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4393
4394 CGF.EmitBranch(ContBlock);
4395
4396 //=======================================
4397 // Tidy up
4398 //=======================================
4399 CGF.EmitBlock(ContBlock);
4400
4401 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4402 ResAddr->addIncoming(RegAddr, InRegBlock);
4403 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4404
4405 if (AI.isDirect())
4406 return ResAddr;
4407
4408 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4409}
4410
4411//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004412// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004413//===----------------------------------------------------------------------===//
4414
4415namespace {
4416
Justin Holewinski83e96682012-05-24 17:43:12 +00004417class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004418public:
Justin Holewinski36837432013-03-30 14:38:24 +00004419 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004420
4421 ABIArgInfo classifyReturnType(QualType RetTy) const;
4422 ABIArgInfo classifyArgumentType(QualType Ty) const;
4423
Craig Topper4f12f102014-03-12 06:41:41 +00004424 void computeInfo(CGFunctionInfo &FI) const override;
4425 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4426 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004427};
4428
Justin Holewinski83e96682012-05-24 17:43:12 +00004429class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004430public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004431 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4432 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004433
4434 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4435 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00004436private:
4437 static void addKernelMetadata(llvm::Function *F);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004438};
4439
Justin Holewinski83e96682012-05-24 17:43:12 +00004440ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004441 if (RetTy->isVoidType())
4442 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004443
4444 // note: this is different from default ABI
4445 if (!RetTy->isScalarType())
4446 return ABIArgInfo::getDirect();
4447
4448 // Treat an enum type as its underlying type.
4449 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4450 RetTy = EnumTy->getDecl()->getIntegerType();
4451
4452 return (RetTy->isPromotableIntegerType() ?
4453 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004454}
4455
Justin Holewinski83e96682012-05-24 17:43:12 +00004456ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004457 // Treat an enum type as its underlying type.
4458 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4459 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004460
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004461 return (Ty->isPromotableIntegerType() ?
4462 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004463}
4464
Justin Holewinski83e96682012-05-24 17:43:12 +00004465void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004466 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4467 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4468 it != ie; ++it)
4469 it->info = classifyArgumentType(it->type);
4470
4471 // Always honor user-specified calling convention.
4472 if (FI.getCallingConvention() != llvm::CallingConv::C)
4473 return;
4474
John McCall882987f2013-02-28 19:01:20 +00004475 FI.setEffectiveCallingConvention(getRuntimeCC());
4476}
4477
Justin Holewinski83e96682012-05-24 17:43:12 +00004478llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4479 CodeGenFunction &CFG) const {
4480 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004481}
4482
Justin Holewinski83e96682012-05-24 17:43:12 +00004483void NVPTXTargetCodeGenInfo::
4484SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4485 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004486 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4487 if (!FD) return;
4488
4489 llvm::Function *F = cast<llvm::Function>(GV);
4490
4491 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004492 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004493 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004494 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004495 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004496 // OpenCL __kernel functions get kernel metadata
4497 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004498 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004499 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004500 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004501 }
Justin Holewinski38031972011-10-05 17:58:44 +00004502
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004503 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004504 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004505 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004506 // __global__ functions cannot be called from the device, we do not
4507 // need to set the noinline attribute.
Aaron Ballman9ead1242013-12-19 02:39:40 +00004508 if (FD->hasAttr<CUDAGlobalAttr>())
Justin Holewinski36837432013-03-30 14:38:24 +00004509 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004510 }
4511}
4512
Justin Holewinski36837432013-03-30 14:38:24 +00004513void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4514 llvm::Module *M = F->getParent();
4515 llvm::LLVMContext &Ctx = M->getContext();
4516
4517 // Get "nvvm.annotations" metadata node
4518 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4519
4520 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4521 llvm::SmallVector<llvm::Value *, 3> MDVals;
4522 MDVals.push_back(F);
4523 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4524 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4525
4526 // Append metadata to nvvm.annotations
4527 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4528}
4529
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004530}
4531
4532//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00004533// SystemZ ABI Implementation
4534//===----------------------------------------------------------------------===//
4535
4536namespace {
4537
4538class SystemZABIInfo : public ABIInfo {
4539public:
4540 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4541
4542 bool isPromotableIntegerType(QualType Ty) const;
4543 bool isCompoundType(QualType Ty) const;
4544 bool isFPArgumentType(QualType Ty) const;
4545
4546 ABIArgInfo classifyReturnType(QualType RetTy) const;
4547 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4548
Craig Topper4f12f102014-03-12 06:41:41 +00004549 void computeInfo(CGFunctionInfo &FI) const override {
Ulrich Weigand47445072013-05-06 16:26:41 +00004550 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4551 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4552 it != ie; ++it)
4553 it->info = classifyArgumentType(it->type);
4554 }
4555
Craig Topper4f12f102014-03-12 06:41:41 +00004556 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4557 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00004558};
4559
4560class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4561public:
4562 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4563 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4564};
4565
4566}
4567
4568bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4569 // Treat an enum type as its underlying type.
4570 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4571 Ty = EnumTy->getDecl()->getIntegerType();
4572
4573 // Promotable integer types are required to be promoted by the ABI.
4574 if (Ty->isPromotableIntegerType())
4575 return true;
4576
4577 // 32-bit values must also be promoted.
4578 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4579 switch (BT->getKind()) {
4580 case BuiltinType::Int:
4581 case BuiltinType::UInt:
4582 return true;
4583 default:
4584 return false;
4585 }
4586 return false;
4587}
4588
4589bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4590 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4591}
4592
4593bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4594 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4595 switch (BT->getKind()) {
4596 case BuiltinType::Float:
4597 case BuiltinType::Double:
4598 return true;
4599 default:
4600 return false;
4601 }
4602
4603 if (const RecordType *RT = Ty->getAsStructureType()) {
4604 const RecordDecl *RD = RT->getDecl();
4605 bool Found = false;
4606
4607 // If this is a C++ record, check the bases first.
4608 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00004609 for (const auto &I : CXXRD->bases()) {
4610 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00004611
4612 // Empty bases don't affect things either way.
4613 if (isEmptyRecord(getContext(), Base, true))
4614 continue;
4615
4616 if (Found)
4617 return false;
4618 Found = isFPArgumentType(Base);
4619 if (!Found)
4620 return false;
4621 }
4622
4623 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004624 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00004625 // Empty bitfields don't affect things either way.
4626 // Unlike isSingleElementStruct(), empty structure and array fields
4627 // do count. So do anonymous bitfields that aren't zero-sized.
4628 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4629 return true;
4630
4631 // Unlike isSingleElementStruct(), arrays do not count.
4632 // Nested isFPArgumentType structures still do though.
4633 if (Found)
4634 return false;
4635 Found = isFPArgumentType(FD->getType());
4636 if (!Found)
4637 return false;
4638 }
4639
4640 // Unlike isSingleElementStruct(), trailing padding is allowed.
4641 // An 8-byte aligned struct s { float f; } is passed as a double.
4642 return Found;
4643 }
4644
4645 return false;
4646}
4647
4648llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4649 CodeGenFunction &CGF) const {
4650 // Assume that va_list type is correct; should be pointer to LLVM type:
4651 // struct {
4652 // i64 __gpr;
4653 // i64 __fpr;
4654 // i8 *__overflow_arg_area;
4655 // i8 *__reg_save_area;
4656 // };
4657
4658 // Every argument occupies 8 bytes and is passed by preference in either
4659 // GPRs or FPRs.
4660 Ty = CGF.getContext().getCanonicalType(Ty);
4661 ABIArgInfo AI = classifyArgumentType(Ty);
4662 bool InFPRs = isFPArgumentType(Ty);
4663
4664 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4665 bool IsIndirect = AI.isIndirect();
4666 unsigned UnpaddedBitSize;
4667 if (IsIndirect) {
4668 APTy = llvm::PointerType::getUnqual(APTy);
4669 UnpaddedBitSize = 64;
4670 } else
4671 UnpaddedBitSize = getContext().getTypeSize(Ty);
4672 unsigned PaddedBitSize = 64;
4673 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4674
4675 unsigned PaddedSize = PaddedBitSize / 8;
4676 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4677
4678 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4679 if (InFPRs) {
4680 MaxRegs = 4; // Maximum of 4 FPR arguments
4681 RegCountField = 1; // __fpr
4682 RegSaveIndex = 16; // save offset for f0
4683 RegPadding = 0; // floats are passed in the high bits of an FPR
4684 } else {
4685 MaxRegs = 5; // Maximum of 5 GPR arguments
4686 RegCountField = 0; // __gpr
4687 RegSaveIndex = 2; // save offset for r2
4688 RegPadding = Padding; // values are passed in the low bits of a GPR
4689 }
4690
4691 llvm::Value *RegCountPtr =
4692 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4693 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4694 llvm::Type *IndexTy = RegCount->getType();
4695 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4696 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00004697 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00004698
4699 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4700 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4701 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4702 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4703
4704 // Emit code to load the value if it was passed in registers.
4705 CGF.EmitBlock(InRegBlock);
4706
4707 // Work out the address of an argument register.
4708 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4709 llvm::Value *ScaledRegCount =
4710 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4711 llvm::Value *RegBase =
4712 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4713 llvm::Value *RegOffset =
4714 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4715 llvm::Value *RegSaveAreaPtr =
4716 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4717 llvm::Value *RegSaveArea =
4718 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4719 llvm::Value *RawRegAddr =
4720 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4721 llvm::Value *RegAddr =
4722 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4723
4724 // Update the register count
4725 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4726 llvm::Value *NewRegCount =
4727 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4728 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4729 CGF.EmitBranch(ContBlock);
4730
4731 // Emit code to load the value if it was passed in memory.
4732 CGF.EmitBlock(InMemBlock);
4733
4734 // Work out the address of a stack argument.
4735 llvm::Value *OverflowArgAreaPtr =
4736 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4737 llvm::Value *OverflowArgArea =
4738 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4739 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4740 llvm::Value *RawMemAddr =
4741 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4742 llvm::Value *MemAddr =
4743 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4744
4745 // Update overflow_arg_area_ptr pointer
4746 llvm::Value *NewOverflowArgArea =
4747 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4748 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4749 CGF.EmitBranch(ContBlock);
4750
4751 // Return the appropriate result.
4752 CGF.EmitBlock(ContBlock);
4753 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4754 ResAddr->addIncoming(RegAddr, InRegBlock);
4755 ResAddr->addIncoming(MemAddr, InMemBlock);
4756
4757 if (IsIndirect)
4758 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4759
4760 return ResAddr;
4761}
4762
John McCall1fe2a8c2013-06-18 02:46:29 +00004763bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4764 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4765 assert(Triple.getArch() == llvm::Triple::x86);
4766
4767 switch (Opts.getStructReturnConvention()) {
4768 case CodeGenOptions::SRCK_Default:
4769 break;
4770 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4771 return false;
4772 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4773 return true;
4774 }
4775
4776 if (Triple.isOSDarwin())
4777 return true;
4778
4779 switch (Triple.getOS()) {
4780 case llvm::Triple::Cygwin:
4781 case llvm::Triple::MinGW32:
4782 case llvm::Triple::AuroraUX:
4783 case llvm::Triple::DragonFly:
4784 case llvm::Triple::FreeBSD:
4785 case llvm::Triple::OpenBSD:
4786 case llvm::Triple::Bitrig:
4787 case llvm::Triple::Win32:
4788 return true;
4789 default:
4790 return false;
4791 }
4792}
Ulrich Weigand47445072013-05-06 16:26:41 +00004793
4794ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4795 if (RetTy->isVoidType())
4796 return ABIArgInfo::getIgnore();
4797 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4798 return ABIArgInfo::getIndirect(0);
4799 return (isPromotableIntegerType(RetTy) ?
4800 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4801}
4802
4803ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4804 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00004805 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00004806 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4807
4808 // Integers and enums are extended to full register width.
4809 if (isPromotableIntegerType(Ty))
4810 return ABIArgInfo::getExtend();
4811
4812 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4813 uint64_t Size = getContext().getTypeSize(Ty);
4814 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00004815 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004816
4817 // Handle small structures.
4818 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4819 // Structures with flexible arrays have variable length, so really
4820 // fail the size test above.
4821 const RecordDecl *RD = RT->getDecl();
4822 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00004823 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004824
4825 // The structure is passed as an unextended integer, a float, or a double.
4826 llvm::Type *PassTy;
4827 if (isFPArgumentType(Ty)) {
4828 assert(Size == 32 || Size == 64);
4829 if (Size == 32)
4830 PassTy = llvm::Type::getFloatTy(getVMContext());
4831 else
4832 PassTy = llvm::Type::getDoubleTy(getVMContext());
4833 } else
4834 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4835 return ABIArgInfo::getDirect(PassTy);
4836 }
4837
4838 // Non-structure compounds are passed indirectly.
4839 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00004840 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004841
4842 return ABIArgInfo::getDirect(0);
4843}
4844
4845//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004846// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004847//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004848
4849namespace {
4850
4851class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4852public:
Chris Lattner2b037972010-07-29 02:01:43 +00004853 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4854 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004855 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004856 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004857};
4858
4859}
4860
4861void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4862 llvm::GlobalValue *GV,
4863 CodeGen::CodeGenModule &M) const {
4864 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4865 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4866 // Handle 'interrupt' attribute:
4867 llvm::Function *F = cast<llvm::Function>(GV);
4868
4869 // Step 1: Set ISR calling convention.
4870 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4871
4872 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00004873 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004874
4875 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004876 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004877 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004878 "__isr_" + Twine(Num),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004879 GV, &M.getModule());
4880 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004881 }
4882}
4883
Chris Lattner0cf24192010-06-28 20:05:43 +00004884//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00004885// MIPS ABI Implementation. This works for both little-endian and
4886// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00004887//===----------------------------------------------------------------------===//
4888
John McCall943fae92010-05-27 06:19:26 +00004889namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004890class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00004891 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004892 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4893 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004894 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004895 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004896 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004897 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004898public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004899 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004900 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004901 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00004902
4903 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004904 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00004905 void computeInfo(CGFunctionInfo &FI) const override;
4906 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4907 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004908};
4909
John McCall943fae92010-05-27 06:19:26 +00004910class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004911 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00004912public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004913 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
4914 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00004915 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00004916
Craig Topper4f12f102014-03-12 06:41:41 +00004917 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00004918 return 29;
4919 }
4920
Reed Kotler373feca2013-01-16 17:10:28 +00004921 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004922 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00004923 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4924 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00004925 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00004926 if (FD->hasAttr<Mips16Attr>()) {
4927 Fn->addFnAttr("mips16");
4928 }
4929 else if (FD->hasAttr<NoMips16Attr>()) {
4930 Fn->addFnAttr("nomips16");
4931 }
Reed Kotler373feca2013-01-16 17:10:28 +00004932 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00004933
John McCall943fae92010-05-27 06:19:26 +00004934 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004935 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00004936
Craig Topper4f12f102014-03-12 06:41:41 +00004937 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004938 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00004939 }
John McCall943fae92010-05-27 06:19:26 +00004940};
4941}
4942
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004943void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004944 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004945 llvm::IntegerType *IntTy =
4946 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004947
4948 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4949 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4950 ArgList.push_back(IntTy);
4951
4952 // If necessary, add one more integer type to ArgList.
4953 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4954
4955 if (R)
4956 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004957}
4958
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004959// In N32/64, an aligned double precision floating point field is passed in
4960// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004961llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004962 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4963
4964 if (IsO32) {
4965 CoerceToIntArgs(TySize, ArgList);
4966 return llvm::StructType::get(getVMContext(), ArgList);
4967 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004968
Akira Hatanaka02e13e52012-01-12 00:52:17 +00004969 if (Ty->isComplexType())
4970 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00004971
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004972 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004973
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004974 // Unions/vectors are passed in integer registers.
4975 if (!RT || !RT->isStructureOrClassType()) {
4976 CoerceToIntArgs(TySize, ArgList);
4977 return llvm::StructType::get(getVMContext(), ArgList);
4978 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004979
4980 const RecordDecl *RD = RT->getDecl();
4981 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004982 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004983
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004984 uint64_t LastOffset = 0;
4985 unsigned idx = 0;
4986 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4987
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004988 // Iterate over fields in the struct/class and check if there are any aligned
4989 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004990 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4991 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004992 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004993 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4994
4995 if (!BT || BT->getKind() != BuiltinType::Double)
4996 continue;
4997
4998 uint64_t Offset = Layout.getFieldOffset(idx);
4999 if (Offset % 64) // Ignore doubles that are not aligned.
5000 continue;
5001
5002 // Add ((Offset - LastOffset) / 64) args of type i64.
5003 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5004 ArgList.push_back(I64);
5005
5006 // Add double type.
5007 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5008 LastOffset = Offset + 64;
5009 }
5010
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005011 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5012 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005013
5014 return llvm::StructType::get(getVMContext(), ArgList);
5015}
5016
Akira Hatanakaddd66342013-10-29 18:41:15 +00005017llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5018 uint64_t Offset) const {
5019 if (OrigOffset + MinABIStackAlignInBytes > Offset)
5020 return 0;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005021
Akira Hatanakaddd66342013-10-29 18:41:15 +00005022 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005023}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005024
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005025ABIArgInfo
5026MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005027 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005028 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005029 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005030
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005031 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5032 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005033 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5034 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005035
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005036 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005037 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005038 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005039 return ABIArgInfo::getIgnore();
5040
Mark Lacey3825e832013-10-06 01:33:34 +00005041 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005042 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005043 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005044 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005045
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005046 // If we have reached here, aggregates are passed directly by coercing to
5047 // another structure type. Padding is inserted if the offset of the
5048 // aggregate is unaligned.
5049 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00005050 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005051 }
5052
5053 // Treat an enum type as its underlying type.
5054 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5055 Ty = EnumTy->getDecl()->getIntegerType();
5056
Akira Hatanaka1632af62012-01-09 19:31:25 +00005057 if (Ty->isPromotableIntegerType())
5058 return ABIArgInfo::getExtend();
5059
Akira Hatanakaddd66342013-10-29 18:41:15 +00005060 return ABIArgInfo::getDirect(
5061 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005062}
5063
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005064llvm::Type*
5065MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005066 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005067 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005068
Akira Hatanakab6f74432012-02-09 18:49:26 +00005069 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005070 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005071 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5072 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005073
Akira Hatanakab6f74432012-02-09 18:49:26 +00005074 // N32/64 returns struct/classes in floating point registers if the
5075 // following conditions are met:
5076 // 1. The size of the struct/class is no larger than 128-bit.
5077 // 2. The struct/class has one or two fields all of which are floating
5078 // point types.
5079 // 3. The offset of the first field is zero (this follows what gcc does).
5080 //
5081 // Any other composite results are returned in integer registers.
5082 //
5083 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5084 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5085 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005086 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005087
Akira Hatanakab6f74432012-02-09 18:49:26 +00005088 if (!BT || !BT->isFloatingPoint())
5089 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005090
David Blaikie2d7c57e2012-04-30 02:36:29 +00005091 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005092 }
5093
5094 if (b == e)
5095 return llvm::StructType::get(getVMContext(), RTList,
5096 RD->hasAttr<PackedAttr>());
5097
5098 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005099 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005100 }
5101
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005102 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005103 return llvm::StructType::get(getVMContext(), RTList);
5104}
5105
Akira Hatanakab579fe52011-06-02 00:09:17 +00005106ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005107 uint64_t Size = getContext().getTypeSize(RetTy);
5108
5109 if (RetTy->isVoidType() || Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005110 return ABIArgInfo::getIgnore();
5111
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005112 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey3825e832013-10-06 01:33:34 +00005113 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005114 return ABIArgInfo::getIndirect(0);
5115
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005116 if (Size <= 128) {
5117 if (RetTy->isAnyComplexType())
5118 return ABIArgInfo::getDirect();
5119
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005120 // O32 returns integer vectors in registers.
5121 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
5122 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5123
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005124 if (!IsO32)
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005125 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5126 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005127
5128 return ABIArgInfo::getIndirect(0);
5129 }
5130
5131 // Treat an enum type as its underlying type.
5132 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5133 RetTy = EnumTy->getDecl()->getIntegerType();
5134
5135 return (RetTy->isPromotableIntegerType() ?
5136 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5137}
5138
5139void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005140 ABIArgInfo &RetInfo = FI.getReturnInfo();
5141 RetInfo = classifyReturnType(FI.getReturnType());
5142
5143 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005144 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005145
Akira Hatanakab579fe52011-06-02 00:09:17 +00005146 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5147 it != ie; ++it)
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005148 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005149}
5150
5151llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5152 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00005153 llvm::Type *BP = CGF.Int8PtrTy;
5154 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005155
5156 CGBuilderTy &Builder = CGF.Builder;
5157 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5158 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka37715282012-01-23 23:59:52 +00005159 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005160 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5161 llvm::Value *AddrTyped;
John McCallc8e01702013-04-16 22:48:15 +00005162 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka37715282012-01-23 23:59:52 +00005163 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005164
5165 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka37715282012-01-23 23:59:52 +00005166 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5167 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5168 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5169 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005170 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5171 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5172 }
5173 else
5174 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5175
5176 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka37715282012-01-23 23:59:52 +00005177 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005178 uint64_t Offset =
5179 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5180 llvm::Value *NextAddr =
Akira Hatanaka37715282012-01-23 23:59:52 +00005181 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00005182 "ap.next");
5183 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5184
5185 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005186}
5187
John McCall943fae92010-05-27 06:19:26 +00005188bool
5189MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5190 llvm::Value *Address) const {
5191 // This information comes from gcc's implementation, which seems to
5192 // as canonical as it gets.
5193
John McCall943fae92010-05-27 06:19:26 +00005194 // Everything on MIPS is 4 bytes. Double-precision FP registers
5195 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005196 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005197
5198 // 0-31 are the general purpose registers, $0 - $31.
5199 // 32-63 are the floating-point registers, $f0 - $f31.
5200 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5201 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005202 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005203
5204 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5205 // They are one bit wide and ignored here.
5206
5207 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5208 // (coprocessor 1 is the FP unit)
5209 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5210 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5211 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005212 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005213 return false;
5214}
5215
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005216//===----------------------------------------------------------------------===//
5217// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5218// Currently subclassed only to implement custom OpenCL C function attribute
5219// handling.
5220//===----------------------------------------------------------------------===//
5221
5222namespace {
5223
5224class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5225public:
5226 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5227 : DefaultTargetCodeGenInfo(CGT) {}
5228
Craig Topper4f12f102014-03-12 06:41:41 +00005229 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5230 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005231};
5232
5233void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5234 llvm::GlobalValue *GV,
5235 CodeGen::CodeGenModule &M) const {
5236 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5237 if (!FD) return;
5238
5239 llvm::Function *F = cast<llvm::Function>(GV);
5240
David Blaikiebbafb8a2012-03-11 07:00:24 +00005241 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005242 if (FD->hasAttr<OpenCLKernelAttr>()) {
5243 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005244 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005245 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5246 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005247 // Convert the reqd_work_group_size() attributes to metadata.
5248 llvm::LLVMContext &Context = F->getContext();
5249 llvm::NamedMDNode *OpenCLMetadata =
5250 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5251
5252 SmallVector<llvm::Value*, 5> Operands;
5253 Operands.push_back(F);
5254
Chris Lattnerece04092012-02-07 00:39:47 +00005255 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005256 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005257 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005258 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005259 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005260 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005261
5262 // Add a boolean constant operand for "required" (true) or "hint" (false)
5263 // for implementing the work_group_size_hint attr later. Currently
5264 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005265 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005266 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5267 }
5268 }
5269 }
5270}
5271
5272}
John McCall943fae92010-05-27 06:19:26 +00005273
Tony Linthicum76329bf2011-12-12 21:14:55 +00005274//===----------------------------------------------------------------------===//
5275// Hexagon ABI Implementation
5276//===----------------------------------------------------------------------===//
5277
5278namespace {
5279
5280class HexagonABIInfo : public ABIInfo {
5281
5282
5283public:
5284 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5285
5286private:
5287
5288 ABIArgInfo classifyReturnType(QualType RetTy) const;
5289 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5290
Craig Topper4f12f102014-03-12 06:41:41 +00005291 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005292
Craig Topper4f12f102014-03-12 06:41:41 +00005293 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5294 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005295};
5296
5297class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5298public:
5299 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5300 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5301
Craig Topper4f12f102014-03-12 06:41:41 +00005302 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005303 return 29;
5304 }
5305};
5306
5307}
5308
5309void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5310 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5311 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5312 it != ie; ++it)
5313 it->info = classifyArgumentType(it->type);
5314}
5315
5316ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5317 if (!isAggregateTypeForABI(Ty)) {
5318 // Treat an enum type as its underlying type.
5319 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5320 Ty = EnumTy->getDecl()->getIntegerType();
5321
5322 return (Ty->isPromotableIntegerType() ?
5323 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5324 }
5325
5326 // Ignore empty records.
5327 if (isEmptyRecord(getContext(), Ty, true))
5328 return ABIArgInfo::getIgnore();
5329
Mark Lacey3825e832013-10-06 01:33:34 +00005330 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005331 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005332
5333 uint64_t Size = getContext().getTypeSize(Ty);
5334 if (Size > 64)
5335 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5336 // Pass in the smallest viable integer type.
5337 else if (Size > 32)
5338 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5339 else if (Size > 16)
5340 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5341 else if (Size > 8)
5342 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5343 else
5344 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5345}
5346
5347ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5348 if (RetTy->isVoidType())
5349 return ABIArgInfo::getIgnore();
5350
5351 // Large vector types should be returned via memory.
5352 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5353 return ABIArgInfo::getIndirect(0);
5354
5355 if (!isAggregateTypeForABI(RetTy)) {
5356 // Treat an enum type as its underlying type.
5357 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5358 RetTy = EnumTy->getDecl()->getIntegerType();
5359
5360 return (RetTy->isPromotableIntegerType() ?
5361 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5362 }
5363
5364 // Structures with either a non-trivial destructor or a non-trivial
5365 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00005366 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum76329bf2011-12-12 21:14:55 +00005367 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5368
5369 if (isEmptyRecord(getContext(), RetTy, true))
5370 return ABIArgInfo::getIgnore();
5371
5372 // Aggregates <= 8 bytes are returned in r0; other aggregates
5373 // are returned indirectly.
5374 uint64_t Size = getContext().getTypeSize(RetTy);
5375 if (Size <= 64) {
5376 // Return in the smallest viable integer type.
5377 if (Size <= 8)
5378 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5379 if (Size <= 16)
5380 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5381 if (Size <= 32)
5382 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5383 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5384 }
5385
5386 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5387}
5388
5389llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005390 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005391 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005392 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005393
5394 CGBuilderTy &Builder = CGF.Builder;
5395 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5396 "ap");
5397 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5398 llvm::Type *PTy =
5399 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5400 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5401
5402 uint64_t Offset =
5403 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5404 llvm::Value *NextAddr =
5405 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5406 "ap.next");
5407 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5408
5409 return AddrTyped;
5410}
5411
5412
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005413//===----------------------------------------------------------------------===//
5414// SPARC v9 ABI Implementation.
5415// Based on the SPARC Compliance Definition version 2.4.1.
5416//
5417// Function arguments a mapped to a nominal "parameter array" and promoted to
5418// registers depending on their type. Each argument occupies 8 or 16 bytes in
5419// the array, structs larger than 16 bytes are passed indirectly.
5420//
5421// One case requires special care:
5422//
5423// struct mixed {
5424// int i;
5425// float f;
5426// };
5427//
5428// When a struct mixed is passed by value, it only occupies 8 bytes in the
5429// parameter array, but the int is passed in an integer register, and the float
5430// is passed in a floating point register. This is represented as two arguments
5431// with the LLVM IR inreg attribute:
5432//
5433// declare void f(i32 inreg %i, float inreg %f)
5434//
5435// The code generator will only allocate 4 bytes from the parameter array for
5436// the inreg arguments. All other arguments are allocated a multiple of 8
5437// bytes.
5438//
5439namespace {
5440class SparcV9ABIInfo : public ABIInfo {
5441public:
5442 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5443
5444private:
5445 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005446 void computeInfo(CGFunctionInfo &FI) const override;
5447 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5448 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005449
5450 // Coercion type builder for structs passed in registers. The coercion type
5451 // serves two purposes:
5452 //
5453 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5454 // in registers.
5455 // 2. Expose aligned floating point elements as first-level elements, so the
5456 // code generator knows to pass them in floating point registers.
5457 //
5458 // We also compute the InReg flag which indicates that the struct contains
5459 // aligned 32-bit floats.
5460 //
5461 struct CoerceBuilder {
5462 llvm::LLVMContext &Context;
5463 const llvm::DataLayout &DL;
5464 SmallVector<llvm::Type*, 8> Elems;
5465 uint64_t Size;
5466 bool InReg;
5467
5468 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5469 : Context(c), DL(dl), Size(0), InReg(false) {}
5470
5471 // Pad Elems with integers until Size is ToSize.
5472 void pad(uint64_t ToSize) {
5473 assert(ToSize >= Size && "Cannot remove elements");
5474 if (ToSize == Size)
5475 return;
5476
5477 // Finish the current 64-bit word.
5478 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5479 if (Aligned > Size && Aligned <= ToSize) {
5480 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5481 Size = Aligned;
5482 }
5483
5484 // Add whole 64-bit words.
5485 while (Size + 64 <= ToSize) {
5486 Elems.push_back(llvm::Type::getInt64Ty(Context));
5487 Size += 64;
5488 }
5489
5490 // Final in-word padding.
5491 if (Size < ToSize) {
5492 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5493 Size = ToSize;
5494 }
5495 }
5496
5497 // Add a floating point element at Offset.
5498 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5499 // Unaligned floats are treated as integers.
5500 if (Offset % Bits)
5501 return;
5502 // The InReg flag is only required if there are any floats < 64 bits.
5503 if (Bits < 64)
5504 InReg = true;
5505 pad(Offset);
5506 Elems.push_back(Ty);
5507 Size = Offset + Bits;
5508 }
5509
5510 // Add a struct type to the coercion type, starting at Offset (in bits).
5511 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5512 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5513 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5514 llvm::Type *ElemTy = StrTy->getElementType(i);
5515 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5516 switch (ElemTy->getTypeID()) {
5517 case llvm::Type::StructTyID:
5518 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5519 break;
5520 case llvm::Type::FloatTyID:
5521 addFloat(ElemOffset, ElemTy, 32);
5522 break;
5523 case llvm::Type::DoubleTyID:
5524 addFloat(ElemOffset, ElemTy, 64);
5525 break;
5526 case llvm::Type::FP128TyID:
5527 addFloat(ElemOffset, ElemTy, 128);
5528 break;
5529 case llvm::Type::PointerTyID:
5530 if (ElemOffset % 64 == 0) {
5531 pad(ElemOffset);
5532 Elems.push_back(ElemTy);
5533 Size += 64;
5534 }
5535 break;
5536 default:
5537 break;
5538 }
5539 }
5540 }
5541
5542 // Check if Ty is a usable substitute for the coercion type.
5543 bool isUsableType(llvm::StructType *Ty) const {
5544 if (Ty->getNumElements() != Elems.size())
5545 return false;
5546 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5547 if (Elems[i] != Ty->getElementType(i))
5548 return false;
5549 return true;
5550 }
5551
5552 // Get the coercion type as a literal struct type.
5553 llvm::Type *getType() const {
5554 if (Elems.size() == 1)
5555 return Elems.front();
5556 else
5557 return llvm::StructType::get(Context, Elems);
5558 }
5559 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005560};
5561} // end anonymous namespace
5562
5563ABIArgInfo
5564SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5565 if (Ty->isVoidType())
5566 return ABIArgInfo::getIgnore();
5567
5568 uint64_t Size = getContext().getTypeSize(Ty);
5569
5570 // Anything too big to fit in registers is passed with an explicit indirect
5571 // pointer / sret pointer.
5572 if (Size > SizeLimit)
5573 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5574
5575 // Treat an enum type as its underlying type.
5576 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5577 Ty = EnumTy->getDecl()->getIntegerType();
5578
5579 // Integer types smaller than a register are extended.
5580 if (Size < 64 && Ty->isIntegerType())
5581 return ABIArgInfo::getExtend();
5582
5583 // Other non-aggregates go in registers.
5584 if (!isAggregateTypeForABI(Ty))
5585 return ABIArgInfo::getDirect();
5586
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00005587 // If a C++ object has either a non-trivial copy constructor or a non-trivial
5588 // destructor, it is passed with an explicit indirect pointer / sret pointer.
5589 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5590 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5591
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005592 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005593 // Build a coercion type from the LLVM struct type.
5594 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5595 if (!StrTy)
5596 return ABIArgInfo::getDirect();
5597
5598 CoerceBuilder CB(getVMContext(), getDataLayout());
5599 CB.addStruct(0, StrTy);
5600 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5601
5602 // Try to use the original type for coercion.
5603 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5604
5605 if (CB.InReg)
5606 return ABIArgInfo::getDirectInReg(CoerceTy);
5607 else
5608 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005609}
5610
5611llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5612 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005613 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5614 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5615 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5616 AI.setCoerceToType(ArgTy);
5617
5618 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5619 CGBuilderTy &Builder = CGF.Builder;
5620 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5621 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5622 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5623 llvm::Value *ArgAddr;
5624 unsigned Stride;
5625
5626 switch (AI.getKind()) {
5627 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00005628 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005629 llvm_unreachable("Unsupported ABI kind for va_arg");
5630
5631 case ABIArgInfo::Extend:
5632 Stride = 8;
5633 ArgAddr = Builder
5634 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5635 "extend");
5636 break;
5637
5638 case ABIArgInfo::Direct:
5639 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5640 ArgAddr = Addr;
5641 break;
5642
5643 case ABIArgInfo::Indirect:
5644 Stride = 8;
5645 ArgAddr = Builder.CreateBitCast(Addr,
5646 llvm::PointerType::getUnqual(ArgPtrTy),
5647 "indirect");
5648 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5649 break;
5650
5651 case ABIArgInfo::Ignore:
5652 return llvm::UndefValue::get(ArgPtrTy);
5653 }
5654
5655 // Update VAList.
5656 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5657 Builder.CreateStore(Addr, VAListAddrAsBPP);
5658
5659 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005660}
5661
5662void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5663 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5664 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5665 it != ie; ++it)
5666 it->info = classifyType(it->type, 16 * 8);
5667}
5668
5669namespace {
5670class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5671public:
5672 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5673 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00005674
Craig Topper4f12f102014-03-12 06:41:41 +00005675 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00005676 return 14;
5677 }
5678
5679 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005680 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005681};
5682} // end anonymous namespace
5683
Roman Divackyf02c9942014-02-24 18:46:27 +00005684bool
5685SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5686 llvm::Value *Address) const {
5687 // This is calculated from the LLVM and GCC tables and verified
5688 // against gcc output. AFAIK all ABIs use the same encoding.
5689
5690 CodeGen::CGBuilderTy &Builder = CGF.Builder;
5691
5692 llvm::IntegerType *i8 = CGF.Int8Ty;
5693 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
5694 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
5695
5696 // 0-31: the 8-byte general-purpose registers
5697 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
5698
5699 // 32-63: f0-31, the 4-byte floating-point registers
5700 AssignToArrayRange(Builder, Address, Four8, 32, 63);
5701
5702 // Y = 64
5703 // PSR = 65
5704 // WIM = 66
5705 // TBR = 67
5706 // PC = 68
5707 // NPC = 69
5708 // FSR = 70
5709 // CSR = 71
5710 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
5711
5712 // 72-87: d0-15, the 8-byte floating-point registers
5713 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
5714
5715 return false;
5716}
5717
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005718
Robert Lytton0e076492013-08-13 09:43:10 +00005719//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00005720// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00005721//===----------------------------------------------------------------------===//
5722namespace {
Robert Lytton7d1db152013-08-19 09:46:39 +00005723class XCoreABIInfo : public DefaultABIInfo {
5724public:
5725 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005726 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5727 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00005728};
5729
Robert Lyttond21e2d72014-03-03 13:45:29 +00005730class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton0e076492013-08-13 09:43:10 +00005731public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00005732 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00005733 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton0e076492013-08-13 09:43:10 +00005734};
Robert Lytton2d196952013-10-11 10:29:34 +00005735} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00005736
Robert Lytton7d1db152013-08-19 09:46:39 +00005737llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5738 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00005739 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00005740
Robert Lytton2d196952013-10-11 10:29:34 +00005741 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00005742 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5743 CGF.Int8PtrPtrTy);
5744 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00005745
Robert Lytton2d196952013-10-11 10:29:34 +00005746 // Handle the argument.
5747 ABIArgInfo AI = classifyArgumentType(Ty);
5748 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5749 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5750 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00005751 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00005752 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00005753 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00005754 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00005755 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00005756 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00005757 llvm_unreachable("Unsupported ABI kind for va_arg");
5758 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00005759 Val = llvm::UndefValue::get(ArgPtrTy);
5760 ArgSize = 0;
5761 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005762 case ABIArgInfo::Extend:
5763 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00005764 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5765 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5766 if (ArgSize < 4)
5767 ArgSize = 4;
5768 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005769 case ABIArgInfo::Indirect:
5770 llvm::Value *ArgAddr;
5771 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5772 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00005773 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5774 ArgSize = 4;
5775 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005776 }
Robert Lytton2d196952013-10-11 10:29:34 +00005777
5778 // Increment the VAList.
5779 if (ArgSize) {
5780 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
5781 Builder.CreateStore(APN, VAListAddrAsBPP);
5782 }
5783 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00005784}
Robert Lytton0e076492013-08-13 09:43:10 +00005785
5786//===----------------------------------------------------------------------===//
5787// Driver code
5788//===----------------------------------------------------------------------===//
5789
Chris Lattner2b037972010-07-29 02:01:43 +00005790const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005791 if (TheTargetCodeGenInfo)
5792 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005793
John McCallc8e01702013-04-16 22:48:15 +00005794 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00005795 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00005796 default:
Chris Lattner2b037972010-07-29 02:01:43 +00005797 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00005798
Derek Schuff09338a22012-09-06 17:37:28 +00005799 case llvm::Triple::le32:
5800 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00005801 case llvm::Triple::mips:
5802 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005803 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
5804
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00005805 case llvm::Triple::mips64:
5806 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005807 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
5808
Tim Northover9bb857a2013-01-31 12:13:10 +00005809 case llvm::Triple::aarch64:
Christian Pirker9b019ae2014-02-25 13:51:00 +00005810 case llvm::Triple::aarch64_be:
Tim Northover9bb857a2013-01-31 12:13:10 +00005811 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5812
Daniel Dunbard59655c2009-09-12 00:59:49 +00005813 case llvm::Triple::arm:
5814 case llvm::Triple::thumb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005815 {
5816 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCallc8e01702013-04-16 22:48:15 +00005817 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005818 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00005819 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00005820 (CodeGenOpts.FloatABI != "soft" &&
5821 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005822 Kind = ARMABIInfo::AAPCS_VFP;
5823
Derek Schuffa2020962012-10-16 22:30:41 +00005824 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00005825 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00005826 return *(TheTargetCodeGenInfo =
5827 new NaClARMTargetCodeGenInfo(Types, Kind));
5828 default:
5829 return *(TheTargetCodeGenInfo =
5830 new ARMTargetCodeGenInfo(Types, Kind));
5831 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005832 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00005833
John McCallea8d8bb2010-03-11 00:10:12 +00005834 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00005835 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00005836 case llvm::Triple::ppc64:
Bill Schmidt25cb3492012-10-03 19:18:57 +00005837 if (Triple.isOSBinFormatELF())
5838 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5839 else
5840 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidt778d3872013-07-26 01:36:11 +00005841 case llvm::Triple::ppc64le:
5842 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5843 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallea8d8bb2010-03-11 00:10:12 +00005844
Peter Collingbournec947aae2012-05-20 23:28:41 +00005845 case llvm::Triple::nvptx:
5846 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00005847 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005848
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005849 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00005850 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00005851
Ulrich Weigand47445072013-05-06 16:26:41 +00005852 case llvm::Triple::systemz:
5853 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5854
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005855 case llvm::Triple::tce:
5856 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5857
Eli Friedman33465822011-07-08 23:31:17 +00005858 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00005859 bool IsDarwinVectorABI = Triple.isOSDarwin();
5860 bool IsSmallStructInRegABI =
5861 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5862 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005863
John McCall1fe2a8c2013-06-18 02:46:29 +00005864 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00005865 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005866 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00005867 IsDarwinVectorABI, IsSmallStructInRegABI,
5868 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005869 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00005870 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005871 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00005872 new X86_32TargetCodeGenInfo(Types,
5873 IsDarwinVectorABI, IsSmallStructInRegABI,
5874 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00005875 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005876 }
Eli Friedman33465822011-07-08 23:31:17 +00005877 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005878
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005879 case llvm::Triple::x86_64: {
John McCallc8e01702013-04-16 22:48:15 +00005880 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005881
Chris Lattner04dc9572010-08-31 16:44:54 +00005882 switch (Triple.getOS()) {
5883 case llvm::Triple::Win32:
NAKAMURA Takumi31ea2f12011-02-17 08:51:38 +00005884 case llvm::Triple::MinGW32:
Chris Lattner04dc9572010-08-31 16:44:54 +00005885 case llvm::Triple::Cygwin:
5886 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00005887 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00005888 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5889 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005890 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005891 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5892 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005893 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00005894 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00005895 case llvm::Triple::hexagon:
5896 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005897 case llvm::Triple::sparcv9:
5898 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00005899 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00005900 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00005901
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005902 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005903}