blob: da627756c80dbc271e7bf2d254cb8bb48b6e60db [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;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000117 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000118 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000119 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000120 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000121 break;
122 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000123 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000124 break;
125 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000126 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000127}
128
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000129TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
130
John McCall3480ef22011-08-30 01:42:09 +0000131// If someone can figure out a general rule for this, that would be great.
132// It's probably just doomed to be platform-dependent, though.
133unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
134 // Verified for:
135 // x86-64 FreeBSD, Linux, Darwin
136 // x86-32 FreeBSD, Linux, Darwin
137 // PowerPC Linux, Darwin
138 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000139 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000140 return 32;
141}
142
John McCalla729c622012-02-17 03:33:10 +0000143bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
144 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000145 // The following conventions are known to require this to be false:
146 // x86_stdcall
147 // MIPS
148 // For everything else, we just prefer false unless we opt out.
149 return false;
150}
151
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000152void
153TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
154 llvm::SmallString<24> &Opt) const {
155 // This assumes the user is passing a library name like "rt" instead of a
156 // filename like "librt.a/so", and that they don't care whether it's static or
157 // dynamic.
158 Opt = "-l";
159 Opt += Lib;
160}
161
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000162static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000163
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000164/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000165/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000166static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
167 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000168 if (FD->isUnnamedBitfield())
169 return true;
170
171 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000172
Eli Friedman0b3f2012011-11-18 03:47:20 +0000173 // Constant arrays of empty records count as empty, strip them off.
174 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000175 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000176 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
177 if (AT->getSize() == 0)
178 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000179 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000180 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000181
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000182 const RecordType *RT = FT->getAs<RecordType>();
183 if (!RT)
184 return false;
185
186 // C++ record fields are never empty, at least in the Itanium ABI.
187 //
188 // FIXME: We should use a predicate for whether this behavior is true in the
189 // current ABI.
190 if (isa<CXXRecordDecl>(RT->getDecl()))
191 return false;
192
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000193 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000194}
195
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000196/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000197/// fields. Note that a structure with a flexible array member is not
198/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000199static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000200 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000201 if (!RT)
202 return 0;
203 const RecordDecl *RD = RT->getDecl();
204 if (RD->hasFlexibleArrayMember())
205 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000206
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000207 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000208 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000209 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
210 e = CXXRD->bases_end(); i != e; ++i)
211 if (!isEmptyRecord(Context, i->getType(), true))
212 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000213
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000214 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
215 i != e; ++i)
David Blaikie40ed2972012-06-06 20:45:41 +0000216 if (!isEmptyField(Context, *i, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000217 return false;
218 return true;
219}
220
221/// isSingleElementStruct - Determine if a structure is a "single
222/// element struct", i.e. it has exactly one non-empty field or
223/// exactly one field which is itself a single element
224/// struct. Structures with flexible array members are never
225/// considered single element structs.
226///
227/// \return The field declaration for the single non-empty field, if
228/// it exists.
229static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
230 const RecordType *RT = T->getAsStructureType();
231 if (!RT)
232 return 0;
233
234 const RecordDecl *RD = RT->getDecl();
235 if (RD->hasFlexibleArrayMember())
236 return 0;
237
238 const Type *Found = 0;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000239
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000240 // If this is a C++ record, check the bases first.
241 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
242 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
243 e = CXXRD->bases_end(); i != e; ++i) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000244 // Ignore empty records.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +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.
254 Found = isSingleElementStruct(i->getType(), Context);
255 if (!Found)
256 return 0;
257 }
258 }
259
260 // Check for single element.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000261 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
262 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000263 const FieldDecl *FD = *i;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000264 QualType FT = FD->getType();
265
266 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000267 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000268 continue;
269
270 // If we already found an element then this isn't a single-element
271 // struct.
272 if (Found)
273 return 0;
274
275 // Treat single element arrays as the element.
276 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
277 if (AT->getSize().getZExtValue() != 1)
278 break;
279 FT = AT->getElementType();
280 }
281
John McCalla1dee5302010-08-22 10:59:02 +0000282 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000283 Found = FT.getTypePtr();
284 } else {
285 Found = isSingleElementStruct(FT, Context);
286 if (!Found)
287 return 0;
288 }
289 }
290
Eli Friedmanee945342011-11-18 01:25:50 +0000291 // We don't consider a struct a single-element struct if it has
292 // padding beyond the element type.
293 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
294 return 0;
295
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000296 return Found;
297}
298
299static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000300 // Treat complex types as the element type.
301 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
302 Ty = CTy->getElementType();
303
304 // Check for a type which we know has a simple scalar argument-passing
305 // convention without any padding. (We're specifically looking for 32
306 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000307 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000308 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000309 return false;
310
311 uint64_t Size = Context.getTypeSize(Ty);
312 return Size == 32 || Size == 64;
313}
314
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000315/// canExpandIndirectArgument - Test whether an argument type which is to be
316/// passed indirectly (on the stack) would have the equivalent layout if it was
317/// expanded into separate arguments. If so, we prefer to do the latter to avoid
318/// inhibiting optimizations.
319///
320// FIXME: This predicate is missing many cases, currently it just follows
321// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
322// should probably make this smarter, or better yet make the LLVM backend
323// capable of handling it.
324static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
325 // We can only expand structure types.
326 const RecordType *RT = Ty->getAs<RecordType>();
327 if (!RT)
328 return false;
329
330 // We can only expand (C) structures.
331 //
332 // FIXME: This needs to be generalized to handle classes as well.
333 const RecordDecl *RD = RT->getDecl();
334 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
335 return false;
336
Eli Friedmane5c85622011-11-18 01:32:26 +0000337 uint64_t Size = 0;
338
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000339 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
340 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000341 const FieldDecl *FD = *i;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000342
343 if (!is32Or64BitBasicType(FD->getType(), Context))
344 return false;
345
346 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
347 // how to expand them yet, and the predicate for telling if a bitfield still
348 // counts as "basic" is more complicated than what we were doing previously.
349 if (FD->isBitField())
350 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000351
352 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000353 }
354
Eli Friedmane5c85622011-11-18 01:32:26 +0000355 // Make sure there are not any holes in the struct.
356 if (Size != Context.getTypeSize(Ty))
357 return false;
358
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000359 return true;
360}
361
362namespace {
363/// DefaultABIInfo - The default implementation for ABI specific
364/// details. This implementation provides information which results in
365/// self-consistent and sensible LLVM IR generation, but does not
366/// conform to any particular ABI.
367class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000368public:
369 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000370
Chris Lattner458b2aa2010-07-29 02:16:43 +0000371 ABIArgInfo classifyReturnType(QualType RetTy) const;
372 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000373
Chris Lattner22326a12010-07-29 02:31:05 +0000374 virtual void computeInfo(CGFunctionInfo &FI) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000375 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000376 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
377 it != ie; ++it)
Chris Lattner458b2aa2010-07-29 02:16:43 +0000378 it->info = classifyArgumentType(it->type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000379 }
380
381 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
382 CodeGenFunction &CGF) const;
383};
384
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000385class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
386public:
Chris Lattner2b037972010-07-29 02:01:43 +0000387 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
388 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000389};
390
391llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
392 CodeGenFunction &CGF) const {
393 return 0;
394}
395
Chris Lattner458b2aa2010-07-29 02:16:43 +0000396ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Jan Wen Voung180319f2011-11-03 00:59:44 +0000397 if (isAggregateTypeForABI(Ty)) {
Alp Tokerd4733632013-12-05 04:47:09 +0000398 // Records with non-trivial destructors/constructors should not be passed
Jan Wen Voung180319f2011-11-03 00:59:44 +0000399 // by value.
Mark Lacey3825e832013-10-06 01:33:34 +0000400 if (isRecordReturnIndirect(Ty, getCXXABI()))
Jan Wen Voung180319f2011-11-03 00:59:44 +0000401 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
402
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000403 return ABIArgInfo::getIndirect(0);
Jan Wen Voung180319f2011-11-03 00:59:44 +0000404 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000405
Chris Lattner9723d6c2010-03-11 18:19:55 +0000406 // Treat an enum type as its underlying type.
407 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
408 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000409
Chris Lattner9723d6c2010-03-11 18:19:55 +0000410 return (Ty->isPromotableIntegerType() ?
411 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000412}
413
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000414ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
415 if (RetTy->isVoidType())
416 return ABIArgInfo::getIgnore();
417
418 if (isAggregateTypeForABI(RetTy))
419 return ABIArgInfo::getIndirect(0);
420
421 // Treat an enum type as its underlying type.
422 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
423 RetTy = EnumTy->getDecl()->getIntegerType();
424
425 return (RetTy->isPromotableIntegerType() ?
426 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
427}
428
Derek Schuff09338a22012-09-06 17:37:28 +0000429//===----------------------------------------------------------------------===//
430// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000431//
432// This is a simplified version of the x86_32 ABI. Arguments and return values
433// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000434//===----------------------------------------------------------------------===//
435
436class PNaClABIInfo : public ABIInfo {
437 public:
438 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
439
440 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000441 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000442
443 virtual void computeInfo(CGFunctionInfo &FI) const;
444 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
445 CodeGenFunction &CGF) const;
446};
447
448class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
449 public:
450 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
451 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
452};
453
454void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
455 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
456
Derek Schuff09338a22012-09-06 17:37:28 +0000457 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
458 it != ie; ++it)
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000459 it->info = classifyArgumentType(it->type);
Derek Schuff09338a22012-09-06 17:37:28 +0000460 }
461
462llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
463 CodeGenFunction &CGF) const {
464 return 0;
465}
466
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000467/// \brief Classify argument of given type \p Ty.
468ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000469 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000470 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000471 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000472 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000473 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
474 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000475 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000476 } else if (Ty->isFloatingType()) {
477 // Floating-point types don't go inreg.
478 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000479 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000480
481 return (Ty->isPromotableIntegerType() ?
482 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000483}
484
485ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
486 if (RetTy->isVoidType())
487 return ABIArgInfo::getIgnore();
488
Eli Benderskye20dad62013-04-04 22:49:35 +0000489 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000490 if (isAggregateTypeForABI(RetTy))
491 return ABIArgInfo::getIndirect(0);
492
493 // Treat an enum type as its underlying type.
494 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
495 RetTy = EnumTy->getDecl()->getIntegerType();
496
497 return (RetTy->isPromotableIntegerType() ?
498 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
499}
500
Chad Rosier651c1832013-03-25 21:00:27 +0000501/// IsX86_MMXType - Return true if this is an MMX type.
502bool IsX86_MMXType(llvm::Type *IRType) {
503 // 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 +0000504 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
505 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
506 IRType->getScalarSizeInBits() != 64;
507}
508
Jay Foad7c57be32011-07-11 09:56:20 +0000509static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000510 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000511 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000512 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
513 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
514 // Invalid MMX constraint
515 return 0;
516 }
517
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000518 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000519 }
520
521 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000522 return Ty;
523}
524
Chris Lattner0cf24192010-06-28 20:05:43 +0000525//===----------------------------------------------------------------------===//
526// X86-32 ABI Implementation
527//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000528
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000529/// X86_32ABIInfo - The X86-32 ABI information.
530class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000531 enum Class {
532 Integer,
533 Float
534 };
535
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000536 static const unsigned MinABIStackAlignInBytes = 4;
537
David Chisnallde3a0692009-08-17 23:08:21 +0000538 bool IsDarwinVectorABI;
539 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000540 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000541 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000542
543 static bool isRegisterSize(unsigned Size) {
544 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
545 }
546
Aaron Ballman3c424412012-02-22 03:04:13 +0000547 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
548 unsigned callingConvention);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000549
Daniel Dunbar557893d2010-04-21 19:10:51 +0000550 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
551 /// such that the argument will be passed in memory.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000552 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal,
553 unsigned &FreeRegs) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000554
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000555 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000556 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000557
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000558 Class classify(QualType Ty) const;
Rafael Espindola75419dc2012-07-23 23:30:29 +0000559 ABIArgInfo classifyReturnType(QualType RetTy,
Aaron Ballman3c424412012-02-22 03:04:13 +0000560 unsigned callingConvention) const;
Rafael Espindola077dd592012-10-24 01:58:58 +0000561 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs,
562 bool IsFastCall) const;
563 bool shouldUseInReg(QualType Ty, unsigned &FreeRegs,
Rafael Espindolafad28de2012-10-24 01:59:00 +0000564 bool IsFastCall, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000565
Rafael Espindola75419dc2012-07-23 23:30:29 +0000566public:
567
Rafael Espindolaa6472962012-07-24 00:01:07 +0000568 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000569 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
570 CodeGenFunction &CGF) const;
571
Chad Rosier651c1832013-03-25 21:00:27 +0000572 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000573 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000574 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000575 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000576};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000577
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000578class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
579public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000580 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000581 bool d, bool p, bool w, unsigned r)
582 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000583
John McCall1fe2a8c2013-06-18 02:46:29 +0000584 static bool isStructReturnInRegABI(
585 const llvm::Triple &Triple, const CodeGenOptions &Opts);
586
Charles Davis4ea31ab2010-02-13 15:54:06 +0000587 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
588 CodeGen::CodeGenModule &CGM) const;
John McCallbeec5a02010-03-06 00:35:14 +0000589
590 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
591 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000592 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000593 return 4;
594 }
595
596 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
597 llvm::Value *Address) const;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000598
Jay Foad7c57be32011-07-11 09:56:20 +0000599 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000600 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000601 llvm::Type* Ty) const {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000602 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
603 }
604
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000605 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
606 unsigned Sig = (0xeb << 0) | // jmp rel8
607 (0x06 << 8) | // .+0x08
608 ('F' << 16) |
609 ('T' << 24);
610 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
611 }
612
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000613};
614
615}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000616
617/// shouldReturnTypeInRegister - Determine if the given type should be
618/// passed in a register (for the Darwin ABI).
619bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
Aaron Ballman3c424412012-02-22 03:04:13 +0000620 ASTContext &Context,
621 unsigned callingConvention) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000622 uint64_t Size = Context.getTypeSize(Ty);
623
624 // Type must be register sized.
625 if (!isRegisterSize(Size))
626 return false;
627
628 if (Ty->isVectorType()) {
629 // 64- and 128- bit vectors inside structures are not returned in
630 // registers.
631 if (Size == 64 || Size == 128)
632 return false;
633
634 return true;
635 }
636
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000637 // If this is a builtin, pointer, enum, complex type, member pointer, or
638 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000639 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000640 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000641 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000642 return true;
643
644 // Arrays are treated like records.
645 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman3c424412012-02-22 03:04:13 +0000646 return shouldReturnTypeInRegister(AT->getElementType(), Context,
647 callingConvention);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000648
649 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000650 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000651 if (!RT) return false;
652
Anders Carlsson40446e82010-01-27 03:25:19 +0000653 // FIXME: Traverse bases here too.
654
Aaron Ballman3c424412012-02-22 03:04:13 +0000655 // For thiscall conventions, structures will never be returned in
656 // a register. This is for compatibility with the MSVC ABI
657 if (callingConvention == llvm::CallingConv::X86_ThisCall &&
658 RT->isStructureType()) {
659 return false;
660 }
661
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000662 // Structure types are passed in register if all fields would be
663 // passed in a register.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000664 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
665 e = RT->getDecl()->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000666 const FieldDecl *FD = *i;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000667
668 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000669 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000670 continue;
671
672 // Check fields recursively.
Aaron Ballman3c424412012-02-22 03:04:13 +0000673 if (!shouldReturnTypeInRegister(FD->getType(), Context,
674 callingConvention))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000675 return false;
676 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000677 return true;
678}
679
Aaron Ballman3c424412012-02-22 03:04:13 +0000680ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
681 unsigned callingConvention) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000682 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000683 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000684
Chris Lattner458b2aa2010-07-29 02:16:43 +0000685 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000686 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000687 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000688 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000689
690 // 128-bit vectors are a special case; they are returned in
691 // registers and we need to make sure to pick a type the LLVM
692 // backend will like.
693 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000694 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000695 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000696
697 // Always return in register if it fits in a general purpose
698 // register, or if it is 64 bits and has a single element.
699 if ((Size == 8 || Size == 16 || Size == 32) ||
700 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000701 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000702 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000703
704 return ABIArgInfo::getIndirect(0);
705 }
706
707 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000708 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000709
John McCalla1dee5302010-08-22 10:59:02 +0000710 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000711 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Mark Lacey3825e832013-10-06 01:33:34 +0000712 if (isRecordReturnIndirect(RT, getCXXABI()))
Anders Carlsson5789c492009-10-20 22:07:59 +0000713 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000714
Anders Carlsson5789c492009-10-20 22:07:59 +0000715 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000716 if (RT->getDecl()->hasFlexibleArrayMember())
717 return ABIArgInfo::getIndirect(0);
Anders Carlsson5789c492009-10-20 22:07:59 +0000718 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000719
David Chisnallde3a0692009-08-17 23:08:21 +0000720 // If specified, structs and unions are always indirect.
721 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000722 return ABIArgInfo::getIndirect(0);
723
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000724 // Small structures which are register sized are generally returned
725 // in a register.
Aaron Ballman3c424412012-02-22 03:04:13 +0000726 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(),
727 callingConvention)) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000728 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000729
730 // As a special-case, if the struct is a "single-element" struct, and
731 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000732 // floating-point register. (MSVC does not apply this special case.)
733 // We apply a similar transformation for pointer types to improve the
734 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000735 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000736 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000737 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000738 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
739
740 // FIXME: We should be able to narrow this integer in cases with dead
741 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000742 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000743 }
744
745 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000746 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000747
Chris Lattner458b2aa2010-07-29 02:16:43 +0000748 // Treat an enum type as its underlying type.
749 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
750 RetTy = EnumTy->getDecl()->getIntegerType();
751
752 return (RetTy->isPromotableIntegerType() ?
753 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000754}
755
Eli Friedman7919bea2012-06-05 19:40:46 +0000756static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
757 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
758}
759
Daniel Dunbared23de32010-09-16 20:42:00 +0000760static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
761 const RecordType *RT = Ty->getAs<RecordType>();
762 if (!RT)
763 return 0;
764 const RecordDecl *RD = RT->getDecl();
765
766 // If this is a C++ record, check the bases first.
767 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
768 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
769 e = CXXRD->bases_end(); i != e; ++i)
770 if (!isRecordWithSSEVectorType(Context, i->getType()))
771 return false;
772
773 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
774 i != e; ++i) {
775 QualType FT = i->getType();
776
Eli Friedman7919bea2012-06-05 19:40:46 +0000777 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000778 return true;
779
780 if (isRecordWithSSEVectorType(Context, FT))
781 return true;
782 }
783
784 return false;
785}
786
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000787unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
788 unsigned Align) const {
789 // Otherwise, if the alignment is less than or equal to the minimum ABI
790 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000791 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000792 return 0; // Use default alignment.
793
794 // On non-Darwin, the stack type alignment is always 4.
795 if (!IsDarwinVectorABI) {
796 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000797 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000798 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000799
Daniel Dunbared23de32010-09-16 20:42:00 +0000800 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000801 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
802 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000803 return 16;
804
805 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000806}
807
Rafael Espindola703c47f2012-10-19 05:04:37 +0000808ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
809 unsigned &FreeRegs) const {
810 if (!ByVal) {
811 if (FreeRegs) {
Alp Tokerd4733632013-12-05 04:47:09 +0000812 --FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000813 return ABIArgInfo::getIndirectInReg(0, false);
814 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000815 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000816 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000817
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000818 // Compute the byval alignment.
819 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
820 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
821 if (StackAlign == 0)
Chris Lattnere76b95a2011-05-22 23:35:00 +0000822 return ABIArgInfo::getIndirect(4);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000823
824 // If the stack alignment is less than the type alignment, realign the
825 // argument.
826 if (StackAlign < TypeAlign)
827 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
828 /*Realign=*/true);
829
830 return ABIArgInfo::getIndirect(StackAlign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000831}
832
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000833X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
834 const Type *T = isSingleElementStruct(Ty, getContext());
835 if (!T)
836 T = Ty.getTypePtr();
837
838 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
839 BuiltinType::Kind K = BT->getKind();
840 if (K == BuiltinType::Float || K == BuiltinType::Double)
841 return Float;
842 }
843 return Integer;
844}
845
Rafael Espindola077dd592012-10-24 01:58:58 +0000846bool X86_32ABIInfo::shouldUseInReg(QualType Ty, unsigned &FreeRegs,
Rafael Espindolafad28de2012-10-24 01:59:00 +0000847 bool IsFastCall, bool &NeedsPadding) const {
848 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000849 Class C = classify(Ty);
850 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000851 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000852
Rafael Espindola077dd592012-10-24 01:58:58 +0000853 unsigned Size = getContext().getTypeSize(Ty);
854 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000855
856 if (SizeInRegs == 0)
857 return false;
858
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000859 if (SizeInRegs > FreeRegs) {
860 FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000861 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000862 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000863
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000864 FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000865
866 if (IsFastCall) {
867 if (Size > 32)
868 return false;
869
870 if (Ty->isIntegralOrEnumerationType())
871 return true;
872
873 if (Ty->isPointerType())
874 return true;
875
876 if (Ty->isReferenceType())
877 return true;
878
Rafael Espindolafad28de2012-10-24 01:59:00 +0000879 if (FreeRegs)
880 NeedsPadding = true;
881
Rafael Espindola077dd592012-10-24 01:58:58 +0000882 return false;
883 }
884
Rafael Espindola703c47f2012-10-19 05:04:37 +0000885 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000886}
887
Rafael Espindola703c47f2012-10-19 05:04:37 +0000888ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Rafael Espindola077dd592012-10-24 01:58:58 +0000889 unsigned &FreeRegs,
890 bool IsFastCall) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000891 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000892 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000893 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000894 if (IsWin32StructABI)
895 return getIndirectResult(Ty, true, FreeRegs);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000896
Mark Lacey3825e832013-10-06 01:33:34 +0000897 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000898 return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory, FreeRegs);
899
900 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000901 if (RT->getDecl()->hasFlexibleArrayMember())
Rafael Espindola703c47f2012-10-19 05:04:37 +0000902 return getIndirectResult(Ty, true, FreeRegs);
Anders Carlsson40446e82010-01-27 03:25:19 +0000903 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000904
Eli Friedman9f061a32011-11-18 00:28:11 +0000905 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000906 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000907 return ABIArgInfo::getIgnore();
908
Rafael Espindolafad28de2012-10-24 01:59:00 +0000909 llvm::LLVMContext &LLVMContext = getVMContext();
910 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
911 bool NeedsPadding;
912 if (shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000913 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000914 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000915 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
916 return ABIArgInfo::getDirectInReg(Result);
917 }
Rafael Espindolafad28de2012-10-24 01:59:00 +0000918 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000919
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000920 // Expand small (<= 128-bit) record types when we know that the stack layout
921 // of those arguments will match the struct. This is important because the
922 // LLVM backend isn't smart enough to remove byval, which inhibits many
923 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +0000924 if (getContext().getTypeSize(Ty) <= 4*32 &&
925 canExpandIndirectArgument(Ty, getContext()))
Rafael Espindolafad28de2012-10-24 01:59:00 +0000926 return ABIArgInfo::getExpandWithPadding(IsFastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000927
Rafael Espindola703c47f2012-10-19 05:04:37 +0000928 return getIndirectResult(Ty, true, FreeRegs);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000929 }
930
Chris Lattnerd774ae92010-08-26 20:05:13 +0000931 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +0000932 // On Darwin, some vectors are passed in memory, we handle this by passing
933 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +0000934 if (IsDarwinVectorABI) {
935 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +0000936 if ((Size == 8 || Size == 16 || Size == 32) ||
937 (Size == 64 && VT->getNumElements() == 1))
938 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
939 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +0000940 }
Bill Wendling5cd41c42010-10-18 03:41:31 +0000941
Chad Rosier651c1832013-03-25 21:00:27 +0000942 if (IsX86_MMXType(CGT.ConvertType(Ty)))
943 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000944
Chris Lattnerd774ae92010-08-26 20:05:13 +0000945 return ABIArgInfo::getDirect();
946 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000947
948
Chris Lattner458b2aa2010-07-29 02:16:43 +0000949 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
950 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000951
Rafael Espindolafad28de2012-10-24 01:59:00 +0000952 bool NeedsPadding;
953 bool InReg = shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000954
955 if (Ty->isPromotableIntegerType()) {
956 if (InReg)
957 return ABIArgInfo::getExtendInReg();
958 return ABIArgInfo::getExtend();
959 }
960 if (InReg)
961 return ABIArgInfo::getDirectInReg();
962 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000963}
964
Rafael Espindolaa6472962012-07-24 00:01:07 +0000965void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
966 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
967 FI.getCallingConvention());
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000968
Rafael Espindola077dd592012-10-24 01:58:58 +0000969 unsigned CC = FI.getCallingConvention();
970 bool IsFastCall = CC == llvm::CallingConv::X86_FastCall;
971 unsigned FreeRegs;
972 if (IsFastCall)
973 FreeRegs = 2;
974 else if (FI.getHasRegParm())
975 FreeRegs = FI.getRegParm();
976 else
977 FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000978
979 // If the return value is indirect, then the hidden argument is consuming one
980 // integer register.
981 if (FI.getReturnInfo().isIndirect() && FreeRegs) {
982 --FreeRegs;
983 ABIArgInfo &Old = FI.getReturnInfo();
984 Old = ABIArgInfo::getIndirectInReg(Old.getIndirectAlign(),
985 Old.getIndirectByVal(),
986 Old.getIndirectRealign());
987 }
988
Rafael Espindolaa6472962012-07-24 00:01:07 +0000989 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
990 it != ie; ++it)
Rafael Espindola077dd592012-10-24 01:58:58 +0000991 it->info = classifyArgumentType(it->type, FreeRegs, IsFastCall);
Rafael Espindolaa6472962012-07-24 00:01:07 +0000992}
993
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000994llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
995 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +0000996 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000997
998 CGBuilderTy &Builder = CGF.Builder;
999 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1000 "ap");
1001 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001002
1003 // Compute if the address needs to be aligned
1004 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1005 Align = getTypeStackAlignInBytes(Ty, Align);
1006 Align = std::max(Align, 4U);
1007 if (Align > 4) {
1008 // addr = (addr + align - 1) & -align;
1009 llvm::Value *Offset =
1010 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1011 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1012 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1013 CGF.Int32Ty);
1014 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1015 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1016 Addr->getType(),
1017 "ap.cur.aligned");
1018 }
1019
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001020 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001021 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001022 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1023
1024 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001025 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001026 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001027 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001028 "ap.next");
1029 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1030
1031 return AddrTyped;
1032}
1033
Charles Davis4ea31ab2010-02-13 15:54:06 +00001034void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1035 llvm::GlobalValue *GV,
1036 CodeGen::CodeGenModule &CGM) const {
1037 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1038 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1039 // Get the LLVM function.
1040 llvm::Function *Fn = cast<llvm::Function>(GV);
1041
1042 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001043 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001044 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001045 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1046 llvm::AttributeSet::get(CGM.getLLVMContext(),
1047 llvm::AttributeSet::FunctionIndex,
1048 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001049 }
1050 }
1051}
1052
John McCallbeec5a02010-03-06 00:35:14 +00001053bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1054 CodeGen::CodeGenFunction &CGF,
1055 llvm::Value *Address) const {
1056 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001057
Chris Lattnerece04092012-02-07 00:39:47 +00001058 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001059
John McCallbeec5a02010-03-06 00:35:14 +00001060 // 0-7 are the eight integer registers; the order is different
1061 // on Darwin (for EH), but the range is the same.
1062 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001063 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001064
John McCallc8e01702013-04-16 22:48:15 +00001065 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001066 // 12-16 are st(0..4). Not sure why we stop at 4.
1067 // These have size 16, which is sizeof(long double) on
1068 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001069 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001070 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001071
John McCallbeec5a02010-03-06 00:35:14 +00001072 } else {
1073 // 9 is %eflags, which doesn't get a size on Darwin for some
1074 // reason.
1075 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1076
1077 // 11-16 are st(0..5). Not sure why we stop at 5.
1078 // These have size 12, which is sizeof(long double) on
1079 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001080 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001081 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1082 }
John McCallbeec5a02010-03-06 00:35:14 +00001083
1084 return false;
1085}
1086
Chris Lattner0cf24192010-06-28 20:05:43 +00001087//===----------------------------------------------------------------------===//
1088// X86-64 ABI Implementation
1089//===----------------------------------------------------------------------===//
1090
1091
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001092namespace {
1093/// X86_64ABIInfo - The X86_64 ABI information.
1094class X86_64ABIInfo : public ABIInfo {
1095 enum Class {
1096 Integer = 0,
1097 SSE,
1098 SSEUp,
1099 X87,
1100 X87Up,
1101 ComplexX87,
1102 NoClass,
1103 Memory
1104 };
1105
1106 /// merge - Implement the X86_64 ABI merging algorithm.
1107 ///
1108 /// Merge an accumulating classification \arg Accum with a field
1109 /// classification \arg Field.
1110 ///
1111 /// \param Accum - The accumulating classification. This should
1112 /// always be either NoClass or the result of a previous merge
1113 /// call. In addition, this should never be Memory (the caller
1114 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001115 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001116
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001117 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1118 ///
1119 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1120 /// final MEMORY or SSE classes when necessary.
1121 ///
1122 /// \param AggregateSize - The size of the current aggregate in
1123 /// the classification process.
1124 ///
1125 /// \param Lo - The classification for the parts of the type
1126 /// residing in the low word of the containing object.
1127 ///
1128 /// \param Hi - The classification for the parts of the type
1129 /// residing in the higher words of the containing object.
1130 ///
1131 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1132
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001133 /// classify - Determine the x86_64 register classes in which the
1134 /// given type T should be passed.
1135 ///
1136 /// \param Lo - The classification for the parts of the type
1137 /// residing in the low word of the containing object.
1138 ///
1139 /// \param Hi - The classification for the parts of the type
1140 /// residing in the high word of the containing object.
1141 ///
1142 /// \param OffsetBase - The bit offset of this type in the
1143 /// containing object. Some parameters are classified different
1144 /// depending on whether they straddle an eightbyte boundary.
1145 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001146 /// \param isNamedArg - Whether the argument in question is a "named"
1147 /// argument, as used in AMD64-ABI 3.5.7.
1148 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001149 /// If a word is unused its result will be NoClass; if a type should
1150 /// be passed in Memory then at least the classification of \arg Lo
1151 /// will be Memory.
1152 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001153 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001154 ///
1155 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1156 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001157 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1158 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001159
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001160 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001161 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1162 unsigned IROffset, QualType SourceTy,
1163 unsigned SourceOffset) const;
1164 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1165 unsigned IROffset, QualType SourceTy,
1166 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001167
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001168 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001169 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001170 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001171
1172 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001173 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001174 ///
1175 /// \param freeIntRegs - The number of free integer registers remaining
1176 /// available.
1177 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001178
Chris Lattner458b2aa2010-07-29 02:16:43 +00001179 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001180
Bill Wendling5cd41c42010-10-18 03:41:31 +00001181 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001182 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001183 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001184 unsigned &neededSSE,
1185 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001186
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001187 bool IsIllegalVectorType(QualType Ty) const;
1188
John McCalle0fda732011-04-21 01:20:55 +00001189 /// The 0.98 ABI revision clarified a lot of ambiguities,
1190 /// unfortunately in ways that were not always consistent with
1191 /// certain previous compilers. In particular, platforms which
1192 /// required strict binary compatibility with older versions of GCC
1193 /// may need to exempt themselves.
1194 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001195 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001196 }
1197
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001198 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001199 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1200 // 64-bit hardware.
1201 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001202
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001203public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001204 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001205 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001206 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001207 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001208
John McCalla729c622012-02-17 03:33:10 +00001209 bool isPassedUsingAVXType(QualType type) const {
1210 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001211 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001212 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1213 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001214 if (info.isDirect()) {
1215 llvm::Type *ty = info.getCoerceToType();
1216 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1217 return (vectorTy->getBitWidth() > 128);
1218 }
1219 return false;
1220 }
1221
Chris Lattner22326a12010-07-29 02:31:05 +00001222 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001223
1224 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1225 CodeGenFunction &CGF) const;
1226};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001227
Chris Lattner04dc9572010-08-31 16:44:54 +00001228/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001229class WinX86_64ABIInfo : public ABIInfo {
1230
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001231 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001232
Chris Lattner04dc9572010-08-31 16:44:54 +00001233public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001234 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1235
1236 virtual void computeInfo(CGFunctionInfo &FI) const;
Chris Lattner04dc9572010-08-31 16:44:54 +00001237
1238 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1239 CodeGenFunction &CGF) const;
1240};
1241
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001242class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1243public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001244 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffc7dd7222012-10-11 15:52:22 +00001245 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001246
John McCalla729c622012-02-17 03:33:10 +00001247 const X86_64ABIInfo &getABIInfo() const {
1248 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1249 }
1250
John McCallbeec5a02010-03-06 00:35:14 +00001251 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1252 return 7;
1253 }
1254
1255 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1256 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001257 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001258
John McCall943fae92010-05-27 06:19:26 +00001259 // 0-15 are the 16 integer registers.
1260 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001261 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001262 return false;
1263 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001264
Jay Foad7c57be32011-07-11 09:56:20 +00001265 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001266 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +00001267 llvm::Type* Ty) const {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001268 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1269 }
1270
John McCalla729c622012-02-17 03:33:10 +00001271 bool isNoProtoCallVariadic(const CallArgList &args,
1272 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +00001273 // The default CC on x86-64 sets %al to the number of SSA
1274 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001275 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001276 // that when AVX types are involved: the ABI explicitly states it is
1277 // undefined, and it doesn't work in practice because of how the ABI
1278 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001279 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001280 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001281 for (CallArgList::const_iterator
1282 it = args.begin(), ie = args.end(); it != ie; ++it) {
1283 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1284 HasAVXType = true;
1285 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001286 }
1287 }
John McCalla729c622012-02-17 03:33:10 +00001288
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001289 if (!HasAVXType)
1290 return true;
1291 }
John McCallcbc038a2011-09-21 08:08:30 +00001292
John McCalla729c622012-02-17 03:33:10 +00001293 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001294 }
1295
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001296 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
1297 unsigned Sig = (0xeb << 0) | // jmp rel8
1298 (0x0a << 8) | // .+0x0c
1299 ('F' << 16) |
1300 ('T' << 24);
1301 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1302 }
1303
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001304};
1305
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001306static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1307 // If the argument does not end in .lib, automatically add the suffix. This
1308 // matches the behavior of MSVC.
1309 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001310 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001311 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001312 return ArgStr;
1313}
1314
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001315class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1316public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001317 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1318 bool d, bool p, bool w, unsigned RegParms)
1319 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001320
1321 void getDependentLibraryOption(llvm::StringRef Lib,
1322 llvm::SmallString<24> &Opt) const {
1323 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001324 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001325 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001326
1327 void getDetectMismatchOption(llvm::StringRef Name,
1328 llvm::StringRef Value,
1329 llvm::SmallString<32> &Opt) const {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001330 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001331 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001332};
1333
Chris Lattner04dc9572010-08-31 16:44:54 +00001334class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1335public:
1336 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1337 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1338
1339 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1340 return 7;
1341 }
1342
1343 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1344 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001345 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001346
Chris Lattner04dc9572010-08-31 16:44:54 +00001347 // 0-15 are the 16 integer registers.
1348 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001349 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001350 return false;
1351 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001352
1353 void getDependentLibraryOption(llvm::StringRef Lib,
1354 llvm::SmallString<24> &Opt) const {
1355 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001356 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001357 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001358
1359 void getDetectMismatchOption(llvm::StringRef Name,
1360 llvm::StringRef Value,
1361 llvm::SmallString<32> &Opt) const {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001362 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001363 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001364};
1365
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001366}
1367
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001368void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1369 Class &Hi) const {
1370 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1371 //
1372 // (a) If one of the classes is Memory, the whole argument is passed in
1373 // memory.
1374 //
1375 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1376 // memory.
1377 //
1378 // (c) If the size of the aggregate exceeds two eightbytes and the first
1379 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1380 // argument is passed in memory. NOTE: This is necessary to keep the
1381 // ABI working for processors that don't support the __m256 type.
1382 //
1383 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1384 //
1385 // Some of these are enforced by the merging logic. Others can arise
1386 // only with unions; for example:
1387 // union { _Complex double; unsigned; }
1388 //
1389 // Note that clauses (b) and (c) were added in 0.98.
1390 //
1391 if (Hi == Memory)
1392 Lo = Memory;
1393 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1394 Lo = Memory;
1395 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1396 Lo = Memory;
1397 if (Hi == SSEUp && Lo != SSE)
1398 Hi = SSE;
1399}
1400
Chris Lattnerd776fb12010-06-28 21:43:59 +00001401X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001402 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1403 // classified recursively so that always two fields are
1404 // considered. The resulting class is calculated according to
1405 // the classes of the fields in the eightbyte:
1406 //
1407 // (a) If both classes are equal, this is the resulting class.
1408 //
1409 // (b) If one of the classes is NO_CLASS, the resulting class is
1410 // the other class.
1411 //
1412 // (c) If one of the classes is MEMORY, the result is the MEMORY
1413 // class.
1414 //
1415 // (d) If one of the classes is INTEGER, the result is the
1416 // INTEGER.
1417 //
1418 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1419 // MEMORY is used as class.
1420 //
1421 // (f) Otherwise class SSE is used.
1422
1423 // Accum should never be memory (we should have returned) or
1424 // ComplexX87 (because this cannot be passed in a structure).
1425 assert((Accum != Memory && Accum != ComplexX87) &&
1426 "Invalid accumulated classification during merge.");
1427 if (Accum == Field || Field == NoClass)
1428 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001429 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001430 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001431 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001432 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001433 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001434 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001435 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1436 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001437 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001438 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001439}
1440
Chris Lattner5c740f12010-06-30 19:14:05 +00001441void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001442 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001443 // FIXME: This code can be simplified by introducing a simple value class for
1444 // Class pairs with appropriate constructor methods for the various
1445 // situations.
1446
1447 // FIXME: Some of the split computations are wrong; unaligned vectors
1448 // shouldn't be passed in registers for example, so there is no chance they
1449 // can straddle an eightbyte. Verify & simplify.
1450
1451 Lo = Hi = NoClass;
1452
1453 Class &Current = OffsetBase < 64 ? Lo : Hi;
1454 Current = Memory;
1455
John McCall9dd450b2009-09-21 23:43:11 +00001456 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001457 BuiltinType::Kind k = BT->getKind();
1458
1459 if (k == BuiltinType::Void) {
1460 Current = NoClass;
1461 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1462 Lo = Integer;
1463 Hi = Integer;
1464 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1465 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001466 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1467 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001468 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001469 Current = SSE;
1470 } else if (k == BuiltinType::LongDouble) {
1471 Lo = X87;
1472 Hi = X87Up;
1473 }
1474 // FIXME: _Decimal32 and _Decimal64 are SSE.
1475 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001476 return;
1477 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001478
Chris Lattnerd776fb12010-06-28 21:43:59 +00001479 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001480 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001481 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001482 return;
1483 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001484
Chris Lattnerd776fb12010-06-28 21:43:59 +00001485 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001486 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001487 return;
1488 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001489
Chris Lattnerd776fb12010-06-28 21:43:59 +00001490 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001491 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001492 Lo = Hi = Integer;
1493 else
1494 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001495 return;
1496 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001497
Chris Lattnerd776fb12010-06-28 21:43:59 +00001498 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001499 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001500 if (Size == 32) {
1501 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1502 // float> as integer.
1503 Current = Integer;
1504
1505 // If this type crosses an eightbyte boundary, it should be
1506 // split.
1507 uint64_t EB_Real = (OffsetBase) / 64;
1508 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1509 if (EB_Real != EB_Imag)
1510 Hi = Lo;
1511 } else if (Size == 64) {
1512 // gcc passes <1 x double> in memory. :(
1513 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1514 return;
1515
1516 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001517 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001518 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1519 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1520 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001521 Current = Integer;
1522 else
1523 Current = SSE;
1524
1525 // If this type crosses an eightbyte boundary, it should be
1526 // split.
1527 if (OffsetBase && OffsetBase != 64)
1528 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001529 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001530 // Arguments of 256-bits are split into four eightbyte chunks. The
1531 // least significant one belongs to class SSE and all the others to class
1532 // SSEUP. The original Lo and Hi design considers that types can't be
1533 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1534 // This design isn't correct for 256-bits, but since there're no cases
1535 // where the upper parts would need to be inspected, avoid adding
1536 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001537 //
1538 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1539 // registers if they are "named", i.e. not part of the "..." of a
1540 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001541 Lo = SSE;
1542 Hi = SSEUp;
1543 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001544 return;
1545 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001546
Chris Lattnerd776fb12010-06-28 21:43:59 +00001547 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001548 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001549
Chris Lattner2b037972010-07-29 02:01:43 +00001550 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001551 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001552 if (Size <= 64)
1553 Current = Integer;
1554 else if (Size <= 128)
1555 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001556 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001557 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001558 else if (ET == getContext().DoubleTy ||
1559 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001560 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001561 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001562 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001563 Current = ComplexX87;
1564
1565 // If this complex type crosses an eightbyte boundary then it
1566 // should be split.
1567 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001568 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001569 if (Hi == NoClass && EB_Real != EB_Imag)
1570 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001571
Chris Lattnerd776fb12010-06-28 21:43:59 +00001572 return;
1573 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001574
Chris Lattner2b037972010-07-29 02:01:43 +00001575 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001576 // Arrays are treated like structures.
1577
Chris Lattner2b037972010-07-29 02:01:43 +00001578 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001579
1580 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001581 // than four eightbytes, ..., it has class MEMORY.
1582 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001583 return;
1584
1585 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1586 // fields, it has class MEMORY.
1587 //
1588 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001589 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001590 return;
1591
1592 // Otherwise implement simplified merge. We could be smarter about
1593 // this, but it isn't worth it and would be harder to verify.
1594 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001595 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001596 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001597
1598 // The only case a 256-bit wide vector could be used is when the array
1599 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1600 // to work for sizes wider than 128, early check and fallback to memory.
1601 if (Size > 128 && EltSize != 256)
1602 return;
1603
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001604 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1605 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001606 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001607 Lo = merge(Lo, FieldLo);
1608 Hi = merge(Hi, FieldHi);
1609 if (Lo == Memory || Hi == Memory)
1610 break;
1611 }
1612
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001613 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001614 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001615 return;
1616 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001617
Chris Lattnerd776fb12010-06-28 21:43:59 +00001618 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001619 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001620
1621 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001622 // than four eightbytes, ..., it has class MEMORY.
1623 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001624 return;
1625
Anders Carlsson20759ad2009-09-16 15:53:40 +00001626 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1627 // copy constructor or a non-trivial destructor, it is passed by invisible
1628 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001629 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001630 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001631
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001632 const RecordDecl *RD = RT->getDecl();
1633
1634 // Assume variable sized types are passed in memory.
1635 if (RD->hasFlexibleArrayMember())
1636 return;
1637
Chris Lattner2b037972010-07-29 02:01:43 +00001638 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001639
1640 // Reset Lo class, this will be recomputed.
1641 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001642
1643 // If this is a C++ record, classify the bases first.
1644 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1645 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1646 e = CXXRD->bases_end(); i != e; ++i) {
1647 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1648 "Unexpected base class!");
1649 const CXXRecordDecl *Base =
1650 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1651
1652 // Classify this field.
1653 //
1654 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1655 // single eightbyte, each is classified separately. Each eightbyte gets
1656 // initialized to class NO_CLASS.
1657 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001658 uint64_t Offset =
1659 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Eli Friedman96fd2642013-06-12 00:13:45 +00001660 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001661 Lo = merge(Lo, FieldLo);
1662 Hi = merge(Hi, FieldHi);
1663 if (Lo == Memory || Hi == Memory)
1664 break;
1665 }
1666 }
1667
1668 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001669 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001670 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001671 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001672 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1673 bool BitField = i->isBitField();
1674
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001675 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1676 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001677 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001678 // The only case a 256-bit wide vector could be used is when the struct
1679 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1680 // to work for sizes wider than 128, early check and fallback to memory.
1681 //
1682 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1683 Lo = Memory;
1684 return;
1685 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001686 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001687 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001688 Lo = Memory;
1689 return;
1690 }
1691
1692 // Classify this field.
1693 //
1694 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1695 // exceeds a single eightbyte, each is classified
1696 // separately. Each eightbyte gets initialized to class
1697 // NO_CLASS.
1698 Class FieldLo, FieldHi;
1699
1700 // Bit-fields require special handling, they do not force the
1701 // structure to be passed in memory even if unaligned, and
1702 // therefore they can straddle an eightbyte.
1703 if (BitField) {
1704 // Ignore padding bit-fields.
1705 if (i->isUnnamedBitfield())
1706 continue;
1707
1708 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001709 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001710
1711 uint64_t EB_Lo = Offset / 64;
1712 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001713
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001714 if (EB_Lo) {
1715 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1716 FieldLo = NoClass;
1717 FieldHi = Integer;
1718 } else {
1719 FieldLo = Integer;
1720 FieldHi = EB_Hi ? Integer : NoClass;
1721 }
1722 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001723 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001724 Lo = merge(Lo, FieldLo);
1725 Hi = merge(Hi, FieldHi);
1726 if (Lo == Memory || Hi == Memory)
1727 break;
1728 }
1729
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001730 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001731 }
1732}
1733
Chris Lattner22a931e2010-06-29 06:01:59 +00001734ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001735 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1736 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001737 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001738 // Treat an enum type as its underlying type.
1739 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1740 Ty = EnumTy->getDecl()->getIntegerType();
1741
1742 return (Ty->isPromotableIntegerType() ?
1743 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1744 }
1745
1746 return ABIArgInfo::getIndirect(0);
1747}
1748
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001749bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1750 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1751 uint64_t Size = getContext().getTypeSize(VecTy);
1752 unsigned LargestVector = HasAVX ? 256 : 128;
1753 if (Size <= 64 || Size > LargestVector)
1754 return true;
1755 }
1756
1757 return false;
1758}
1759
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001760ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1761 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001762 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1763 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001764 //
1765 // This assumption is optimistic, as there could be free registers available
1766 // when we need to pass this argument in memory, and LLVM could try to pass
1767 // the argument in the free register. This does not seem to happen currently,
1768 // but this code would be much safer if we could mark the argument with
1769 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001770 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001771 // Treat an enum type as its underlying type.
1772 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1773 Ty = EnumTy->getDecl()->getIntegerType();
1774
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001775 return (Ty->isPromotableIntegerType() ?
1776 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001777 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001778
Mark Lacey3825e832013-10-06 01:33:34 +00001779 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001780 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001781
Chris Lattner44c2b902011-05-22 23:21:23 +00001782 // Compute the byval alignment. We specify the alignment of the byval in all
1783 // cases so that the mid-level optimizer knows the alignment of the byval.
1784 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001785
1786 // Attempt to avoid passing indirect results using byval when possible. This
1787 // is important for good codegen.
1788 //
1789 // We do this by coercing the value into a scalar type which the backend can
1790 // handle naturally (i.e., without using byval).
1791 //
1792 // For simplicity, we currently only do this when we have exhausted all of the
1793 // free integer registers. Doing this when there are free integer registers
1794 // would require more care, as we would have to ensure that the coerced value
1795 // did not claim the unused register. That would require either reording the
1796 // arguments to the function (so that any subsequent inreg values came first),
1797 // or only doing this optimization when there were no following arguments that
1798 // might be inreg.
1799 //
1800 // We currently expect it to be rare (particularly in well written code) for
1801 // arguments to be passed on the stack when there are still free integer
1802 // registers available (this would typically imply large structs being passed
1803 // by value), so this seems like a fair tradeoff for now.
1804 //
1805 // We can revisit this if the backend grows support for 'onstack' parameter
1806 // attributes. See PR12193.
1807 if (freeIntRegs == 0) {
1808 uint64_t Size = getContext().getTypeSize(Ty);
1809
1810 // If this type fits in an eightbyte, coerce it into the matching integral
1811 // type, which will end up on the stack (with alignment 8).
1812 if (Align == 8 && Size <= 64)
1813 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1814 Size));
1815 }
1816
Chris Lattner44c2b902011-05-22 23:21:23 +00001817 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001818}
1819
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001820/// GetByteVectorType - The ABI specifies that a value should be passed in an
1821/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00001822/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001823llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001824 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001825
Chris Lattner9fa15c32010-07-29 05:02:29 +00001826 // Wrapper structs that just contain vectors are passed just like vectors,
1827 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001828 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00001829 while (STy && STy->getNumElements() == 1) {
1830 IRType = STy->getElementType(0);
1831 STy = dyn_cast<llvm::StructType>(IRType);
1832 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001833
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00001834 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001835 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1836 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001837 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00001838 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00001839 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1840 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1841 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1842 EltTy->isIntegerTy(128)))
1843 return VT;
1844 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001845
Chris Lattner4200fe42010-07-29 04:56:46 +00001846 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1847}
1848
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001849/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1850/// is known to either be off the end of the specified type or being in
1851/// alignment padding. The user type specified is known to be at most 128 bits
1852/// in size, and have passed through X86_64ABIInfo::classify with a successful
1853/// classification that put one of the two halves in the INTEGER class.
1854///
1855/// It is conservatively correct to return false.
1856static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1857 unsigned EndBit, ASTContext &Context) {
1858 // If the bytes being queried are off the end of the type, there is no user
1859 // data hiding here. This handles analysis of builtins, vectors and other
1860 // types that don't contain interesting padding.
1861 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1862 if (TySize <= StartBit)
1863 return true;
1864
Chris Lattner98076a22010-07-29 07:43:55 +00001865 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1866 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1867 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1868
1869 // Check each element to see if the element overlaps with the queried range.
1870 for (unsigned i = 0; i != NumElts; ++i) {
1871 // If the element is after the span we care about, then we're done..
1872 unsigned EltOffset = i*EltSize;
1873 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001874
Chris Lattner98076a22010-07-29 07:43:55 +00001875 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1876 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1877 EndBit-EltOffset, Context))
1878 return false;
1879 }
1880 // If it overlaps no elements, then it is safe to process as padding.
1881 return true;
1882 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001883
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001884 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1885 const RecordDecl *RD = RT->getDecl();
1886 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001887
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001888 // If this is a C++ record, check the bases first.
1889 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1890 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1891 e = CXXRD->bases_end(); i != e; ++i) {
1892 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1893 "Unexpected base class!");
1894 const CXXRecordDecl *Base =
1895 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001896
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001897 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001898 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001899 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001900
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001901 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1902 if (!BitsContainNoUserData(i->getType(), BaseStart,
1903 EndBit-BaseOffset, Context))
1904 return false;
1905 }
1906 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001907
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001908 // Verify that no field has data that overlaps the region of interest. Yes
1909 // this could be sped up a lot by being smarter about queried fields,
1910 // however we're only looking at structs up to 16 bytes, so we don't care
1911 // much.
1912 unsigned idx = 0;
1913 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1914 i != e; ++i, ++idx) {
1915 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001916
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001917 // If we found a field after the region we care about, then we're done.
1918 if (FieldOffset >= EndBit) break;
1919
1920 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1921 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1922 Context))
1923 return false;
1924 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001925
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001926 // If nothing in this record overlapped the area of interest, then we're
1927 // clean.
1928 return true;
1929 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001930
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001931 return false;
1932}
1933
Chris Lattnere556a712010-07-29 18:39:32 +00001934/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1935/// float member at the specified offset. For example, {int,{float}} has a
1936/// float at offset 4. It is conservatively correct for this routine to return
1937/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00001938static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001939 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00001940 // Base case if we find a float.
1941 if (IROffset == 0 && IRType->isFloatTy())
1942 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001943
Chris Lattnere556a712010-07-29 18:39:32 +00001944 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00001945 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00001946 const llvm::StructLayout *SL = TD.getStructLayout(STy);
1947 unsigned Elt = SL->getElementContainingOffset(IROffset);
1948 IROffset -= SL->getElementOffset(Elt);
1949 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1950 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001951
Chris Lattnere556a712010-07-29 18:39:32 +00001952 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00001953 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1954 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00001955 unsigned EltSize = TD.getTypeAllocSize(EltTy);
1956 IROffset -= IROffset/EltSize*EltSize;
1957 return ContainsFloatAtOffset(EltTy, IROffset, TD);
1958 }
1959
1960 return false;
1961}
1962
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001963
1964/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1965/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001966llvm::Type *X86_64ABIInfo::
1967GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001968 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00001969 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001970 // pass as float if the last 4 bytes is just padding. This happens for
1971 // structs that contain 3 floats.
1972 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1973 SourceOffset*8+64, getContext()))
1974 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001975
Chris Lattnere556a712010-07-29 18:39:32 +00001976 // We want to pass as <2 x float> if the LLVM IR type contains a float at
1977 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
1978 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00001979 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
1980 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00001981 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001982
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001983 return llvm::Type::getDoubleTy(getVMContext());
1984}
1985
1986
Chris Lattner1c56d9a2010-07-29 17:40:35 +00001987/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1988/// an 8-byte GPR. This means that we either have a scalar or we are talking
1989/// about the high or low part of an up-to-16-byte struct. This routine picks
1990/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00001991/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1992/// etc).
1993///
1994/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1995/// the source type. IROffset is an offset in bytes into the LLVM IR type that
1996/// the 8-byte value references. PrefType may be null.
1997///
1998/// SourceTy is the source level type for the entire argument. SourceOffset is
1999/// an offset into this that we're processing (which is always either 0 or 8).
2000///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002001llvm::Type *X86_64ABIInfo::
2002GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002003 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002004 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2005 // returning an 8-byte unit starting with it. See if we can safely use it.
2006 if (IROffset == 0) {
2007 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002008 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2009 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002010 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002011
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002012 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2013 // goodness in the source type is just tail padding. This is allowed to
2014 // kick in for struct {double,int} on the int, but not on
2015 // struct{double,int,int} because we wouldn't return the second int. We
2016 // have to do this analysis on the source type because we can't depend on
2017 // unions being lowered a specific way etc.
2018 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002019 IRType->isIntegerTy(32) ||
2020 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2021 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2022 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002023
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002024 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2025 SourceOffset*8+64, getContext()))
2026 return IRType;
2027 }
2028 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002029
Chris Lattner2192fe52011-07-18 04:24:23 +00002030 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002031 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002032 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002033 if (IROffset < SL->getSizeInBytes()) {
2034 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2035 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002036
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002037 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2038 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002039 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002040 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002041
Chris Lattner2192fe52011-07-18 04:24:23 +00002042 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002043 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002044 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002045 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002046 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2047 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002048 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002049
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002050 // Okay, we don't have any better idea of what to pass, so we pass this in an
2051 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002052 unsigned TySizeInBytes =
2053 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002054
Chris Lattner3f763422010-07-29 17:34:39 +00002055 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002056
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002057 // It is always safe to classify this as an integer type up to i64 that
2058 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002059 return llvm::IntegerType::get(getVMContext(),
2060 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002061}
2062
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002063
2064/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2065/// be used as elements of a two register pair to pass or return, return a
2066/// first class aggregate to represent them. For example, if the low part of
2067/// a by-value argument should be passed as i32* and the high part as float,
2068/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002069static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002070GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002071 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002072 // In order to correctly satisfy the ABI, we need to the high part to start
2073 // at offset 8. If the high and low parts we inferred are both 4-byte types
2074 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2075 // the second element at offset 8. Check for this:
2076 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2077 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002078 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002079 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002080
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002081 // To handle this, we have to increase the size of the low part so that the
2082 // second element will start at an 8 byte offset. We can't increase the size
2083 // of the second element because it might make us access off the end of the
2084 // struct.
2085 if (HiStart != 8) {
2086 // There are only two sorts of types the ABI generation code can produce for
2087 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2088 // Promote these to a larger type.
2089 if (Lo->isFloatTy())
2090 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2091 else {
2092 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2093 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2094 }
2095 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002096
Chris Lattnera5f58b02011-07-09 17:41:47 +00002097 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002098
2099
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002100 // Verify that the second element is at an 8-byte offset.
2101 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2102 "Invalid x86-64 argument pair!");
2103 return Result;
2104}
2105
Chris Lattner31faff52010-07-28 23:06:14 +00002106ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002107classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002108 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2109 // classification algorithm.
2110 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002111 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002112
2113 // Check some invariants.
2114 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002115 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2116
Chris Lattnera5f58b02011-07-09 17:41:47 +00002117 llvm::Type *ResType = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002118 switch (Lo) {
2119 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002120 if (Hi == NoClass)
2121 return ABIArgInfo::getIgnore();
2122 // If the low part is just padding, it takes no register, leave ResType
2123 // null.
2124 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2125 "Unknown missing lo part");
2126 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002127
2128 case SSEUp:
2129 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002130 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002131
2132 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2133 // hidden argument.
2134 case Memory:
2135 return getIndirectReturnResult(RetTy);
2136
2137 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2138 // available register of the sequence %rax, %rdx is used.
2139 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002140 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002141
Chris Lattner1f3a0632010-07-29 21:42:50 +00002142 // If we have a sign or zero extended integer, make sure to return Extend
2143 // so that the parameter gets the right LLVM IR attributes.
2144 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2145 // Treat an enum type as its underlying type.
2146 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2147 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002148
Chris Lattner1f3a0632010-07-29 21:42:50 +00002149 if (RetTy->isIntegralOrEnumerationType() &&
2150 RetTy->isPromotableIntegerType())
2151 return ABIArgInfo::getExtend();
2152 }
Chris Lattner31faff52010-07-28 23:06:14 +00002153 break;
2154
2155 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2156 // available SSE register of the sequence %xmm0, %xmm1 is used.
2157 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002158 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002159 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002160
2161 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2162 // returned on the X87 stack in %st0 as 80-bit x87 number.
2163 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002164 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002165 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002166
2167 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2168 // part of the value is returned in %st0 and the imaginary part in
2169 // %st1.
2170 case ComplexX87:
2171 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002172 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002173 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002174 NULL);
2175 break;
2176 }
2177
Chris Lattnera5f58b02011-07-09 17:41:47 +00002178 llvm::Type *HighPart = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002179 switch (Hi) {
2180 // Memory was handled previously and X87 should
2181 // never occur as a hi class.
2182 case Memory:
2183 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002184 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002185
2186 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002187 case NoClass:
2188 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002189
Chris Lattner52b3c132010-09-01 00:20:33 +00002190 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002191 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002192 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2193 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002194 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002195 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002196 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002197 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2198 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002199 break;
2200
2201 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002202 // is passed in the next available eightbyte chunk if the last used
2203 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002204 //
Chris Lattner57540c52011-04-15 05:22:18 +00002205 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002206 case SSEUp:
2207 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002208 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002209 break;
2210
2211 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2212 // returned together with the previous X87 value in %st0.
2213 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002214 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002215 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002216 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002217 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002218 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002219 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002220 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2221 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002222 }
Chris Lattner31faff52010-07-28 23:06:14 +00002223 break;
2224 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002225
Chris Lattner52b3c132010-09-01 00:20:33 +00002226 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002227 // known to pass in the high eightbyte of the result. We do this by forming a
2228 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002229 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002230 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002231
Chris Lattner1f3a0632010-07-29 21:42:50 +00002232 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002233}
2234
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002235ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002236 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2237 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002238 const
2239{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002240 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002241 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002242
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002243 // Check some invariants.
2244 // FIXME: Enforce these by construction.
2245 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002246 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2247
2248 neededInt = 0;
2249 neededSSE = 0;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002250 llvm::Type *ResType = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002251 switch (Lo) {
2252 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002253 if (Hi == NoClass)
2254 return ABIArgInfo::getIgnore();
2255 // If the low part is just padding, it takes no register, leave ResType
2256 // null.
2257 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2258 "Unknown missing lo part");
2259 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002260
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002261 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2262 // on the stack.
2263 case Memory:
2264
2265 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2266 // COMPLEX_X87, it is passed in memory.
2267 case X87:
2268 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002269 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002270 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002271 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002272
2273 case SSEUp:
2274 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002275 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002276
2277 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2278 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2279 // and %r9 is used.
2280 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002281 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002282
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002283 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002284 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002285
2286 // If we have a sign or zero extended integer, make sure to return Extend
2287 // so that the parameter gets the right LLVM IR attributes.
2288 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2289 // Treat an enum type as its underlying type.
2290 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2291 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002292
Chris Lattner1f3a0632010-07-29 21:42:50 +00002293 if (Ty->isIntegralOrEnumerationType() &&
2294 Ty->isPromotableIntegerType())
2295 return ABIArgInfo::getExtend();
2296 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002297
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002298 break;
2299
2300 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2301 // available SSE register is used, the registers are taken in the
2302 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002303 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002304 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002305 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002306 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002307 break;
2308 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002309 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002310
Chris Lattnera5f58b02011-07-09 17:41:47 +00002311 llvm::Type *HighPart = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002312 switch (Hi) {
2313 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002314 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002315 // which is passed in memory.
2316 case Memory:
2317 case X87:
2318 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002319 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002320
2321 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002322
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002323 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002324 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002325 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002326 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002327
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002328 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2329 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002330 break;
2331
2332 // X87Up generally doesn't occur here (long double is passed in
2333 // memory), except in situations involving unions.
2334 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002335 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002336 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002337
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002338 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2339 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002340
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002341 ++neededSSE;
2342 break;
2343
2344 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2345 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002346 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002347 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002348 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002349 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002350 break;
2351 }
2352
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002353 // If a high part was specified, merge it together with the low part. It is
2354 // known to pass in the high eightbyte of the result. We do this by forming a
2355 // first class struct aggregate with the high and low part: {low, high}
2356 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002357 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002358
Chris Lattner1f3a0632010-07-29 21:42:50 +00002359 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002360}
2361
Chris Lattner22326a12010-07-29 02:31:05 +00002362void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002363
Chris Lattner458b2aa2010-07-29 02:16:43 +00002364 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002365
2366 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002367 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002368
2369 // If the return value is indirect, then the hidden argument is consuming one
2370 // integer register.
2371 if (FI.getReturnInfo().isIndirect())
2372 --freeIntRegs;
2373
Eli Friedman96fd2642013-06-12 00:13:45 +00002374 bool isVariadic = FI.isVariadic();
2375 unsigned numRequiredArgs = 0;
2376 if (isVariadic)
2377 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2378
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002379 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2380 // get assigned (in left-to-right order) for passing as follows...
2381 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2382 it != ie; ++it) {
Eli Friedman96fd2642013-06-12 00:13:45 +00002383 bool isNamedArg = true;
2384 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002385 isNamedArg = (it - FI.arg_begin()) <
2386 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002387
Bill Wendling9987c0e2010-10-18 23:51:38 +00002388 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002389 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002390 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002391
2392 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2393 // eightbyte of an argument, the whole argument is passed on the
2394 // stack. If registers have already been assigned for some
2395 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002396 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002397 freeIntRegs -= neededInt;
2398 freeSSERegs -= neededSSE;
2399 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002400 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002401 }
2402 }
2403}
2404
2405static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2406 QualType Ty,
2407 CodeGenFunction &CGF) {
2408 llvm::Value *overflow_arg_area_p =
2409 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2410 llvm::Value *overflow_arg_area =
2411 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2412
2413 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2414 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002415 // It isn't stated explicitly in the standard, but in practice we use
2416 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002417 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2418 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002419 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002420 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002421 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002422 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2423 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002424 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002425 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002426 overflow_arg_area =
2427 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2428 overflow_arg_area->getType(),
2429 "overflow_arg_area.align");
2430 }
2431
2432 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002433 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002434 llvm::Value *Res =
2435 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002436 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002437
2438 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2439 // l->overflow_arg_area + sizeof(type).
2440 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2441 // an 8 byte boundary.
2442
2443 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002444 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002445 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002446 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2447 "overflow_arg_area.next");
2448 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2449
2450 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2451 return Res;
2452}
2453
2454llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2455 CodeGenFunction &CGF) const {
2456 // Assume that va_list type is correct; should be pointer to LLVM type:
2457 // struct {
2458 // i32 gp_offset;
2459 // i32 fp_offset;
2460 // i8* overflow_arg_area;
2461 // i8* reg_save_area;
2462 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002463 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002464
Chris Lattner9723d6c2010-03-11 18:19:55 +00002465 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002466 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2467 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002468
2469 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2470 // in the registers. If not go to step 7.
2471 if (!neededInt && !neededSSE)
2472 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2473
2474 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2475 // general purpose registers needed to pass type and num_fp to hold
2476 // the number of floating point registers needed.
2477
2478 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2479 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2480 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2481 //
2482 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2483 // register save space).
2484
2485 llvm::Value *InRegs = 0;
2486 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2487 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2488 if (neededInt) {
2489 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2490 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002491 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2492 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002493 }
2494
2495 if (neededSSE) {
2496 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2497 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2498 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002499 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2500 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002501 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2502 }
2503
2504 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2505 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2506 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2507 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2508
2509 // Emit code to load the value if it was passed in registers.
2510
2511 CGF.EmitBlock(InRegBlock);
2512
2513 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2514 // an offset of l->gp_offset and/or l->fp_offset. This may require
2515 // copying to a temporary location in case the parameter is passed
2516 // in different register classes or requires an alignment greater
2517 // than 8 for general purpose registers and 16 for XMM registers.
2518 //
2519 // FIXME: This really results in shameful code when we end up needing to
2520 // collect arguments from different places; often what should result in a
2521 // simple assembling of a structure from scattered addresses has many more
2522 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002523 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002524 llvm::Value *RegAddr =
2525 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2526 "reg_save_area");
2527 if (neededInt && neededSSE) {
2528 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002529 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002530 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002531 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2532 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002533 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002534 llvm::Type *TyLo = ST->getElementType(0);
2535 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002536 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002537 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002538 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2539 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002540 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2541 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sands998f9d92010-02-15 16:14:01 +00002542 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2543 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002544 llvm::Value *V =
2545 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2546 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2547 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2548 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2549
Owen Anderson170229f2009-07-14 23:10:40 +00002550 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002551 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002552 } else if (neededInt) {
2553 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2554 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002555 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002556
2557 // Copy to a temporary if necessary to ensure the appropriate alignment.
2558 std::pair<CharUnits, CharUnits> SizeAlign =
2559 CGF.getContext().getTypeInfoInChars(Ty);
2560 uint64_t TySize = SizeAlign.first.getQuantity();
2561 unsigned TyAlign = SizeAlign.second.getQuantity();
2562 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002563 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2564 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2565 RegAddr = Tmp;
2566 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002567 } else if (neededSSE == 1) {
2568 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2569 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2570 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002571 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002572 assert(neededSSE == 2 && "Invalid number of needed registers!");
2573 // SSE registers are spaced 16 bytes apart in the register save
2574 // area, we need to collect the two eightbytes together.
2575 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002576 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002577 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002578 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002579 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002580 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2581 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2582 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002583 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2584 DblPtrTy));
2585 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2586 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2587 DblPtrTy));
2588 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2589 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2590 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002591 }
2592
2593 // AMD64-ABI 3.5.7p5: Step 5. Set:
2594 // l->gp_offset = l->gp_offset + num_gp * 8
2595 // l->fp_offset = l->fp_offset + num_fp * 16.
2596 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002597 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002598 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2599 gp_offset_p);
2600 }
2601 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002602 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002603 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2604 fp_offset_p);
2605 }
2606 CGF.EmitBranch(ContBlock);
2607
2608 // Emit code to load the value if it was passed in memory.
2609
2610 CGF.EmitBlock(InMemBlock);
2611 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2612
2613 // Return the appropriate result.
2614
2615 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002616 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002617 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002618 ResAddr->addIncoming(RegAddr, InRegBlock);
2619 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002620 return ResAddr;
2621}
2622
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002623ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002624
2625 if (Ty->isVoidType())
2626 return ABIArgInfo::getIgnore();
2627
2628 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2629 Ty = EnumTy->getDecl()->getIntegerType();
2630
2631 uint64_t Size = getContext().getTypeSize(Ty);
2632
2633 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002634 if (IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002635 if (isRecordReturnIndirect(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002636 return ABIArgInfo::getIndirect(0, false);
2637 } else {
Mark Lacey3825e832013-10-06 01:33:34 +00002638 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002639 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2640 }
2641
2642 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002643 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2644
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002645 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCallc8e01702013-04-16 22:48:15 +00002646 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002647 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2648 Size));
2649
2650 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2651 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2652 if (Size <= 64 &&
NAKAMURA Takumie03c6032011-01-19 00:11:33 +00002653 (Size & (Size - 1)) == 0)
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002654 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2655 Size));
2656
2657 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2658 }
2659
2660 if (Ty->isPromotableIntegerType())
2661 return ABIArgInfo::getExtend();
2662
2663 return ABIArgInfo::getDirect();
2664}
2665
2666void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2667
2668 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002669 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002670
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002671 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2672 it != ie; ++it)
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002673 it->info = classify(it->type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002674}
2675
Chris Lattner04dc9572010-08-31 16:44:54 +00002676llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2677 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002678 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002679
Chris Lattner04dc9572010-08-31 16:44:54 +00002680 CGBuilderTy &Builder = CGF.Builder;
2681 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2682 "ap");
2683 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2684 llvm::Type *PTy =
2685 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2686 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2687
2688 uint64_t Offset =
2689 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2690 llvm::Value *NextAddr =
2691 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2692 "ap.next");
2693 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2694
2695 return AddrTyped;
2696}
Chris Lattner0cf24192010-06-28 20:05:43 +00002697
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002698namespace {
2699
Derek Schuffa2020962012-10-16 22:30:41 +00002700class NaClX86_64ABIInfo : public ABIInfo {
2701 public:
2702 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2703 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2704 virtual void computeInfo(CGFunctionInfo &FI) const;
2705 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2706 CodeGenFunction &CGF) const;
2707 private:
2708 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2709 X86_64ABIInfo NInfo; // Used for everything else.
2710};
2711
2712class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2713 public:
2714 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2715 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2716};
2717
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002718}
2719
Derek Schuffa2020962012-10-16 22:30:41 +00002720void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2721 if (FI.getASTCallingConvention() == CC_PnaclCall)
2722 PInfo.computeInfo(FI);
2723 else
2724 NInfo.computeInfo(FI);
2725}
2726
2727llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2728 CodeGenFunction &CGF) const {
2729 // Always use the native convention; calling pnacl-style varargs functions
2730 // is unuspported.
2731 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2732}
2733
2734
John McCallea8d8bb2010-03-11 00:10:12 +00002735// PowerPC-32
2736
2737namespace {
2738class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2739public:
Chris Lattner2b037972010-07-29 02:01:43 +00002740 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002741
John McCallea8d8bb2010-03-11 00:10:12 +00002742 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2743 // This is recovered from gcc output.
2744 return 1; // r1 is the dedicated stack pointer
2745 }
2746
2747 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002748 llvm::Value *Address) const;
John McCallea8d8bb2010-03-11 00:10:12 +00002749};
2750
2751}
2752
2753bool
2754PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2755 llvm::Value *Address) const {
2756 // This is calculated from the LLVM and GCC tables and verified
2757 // against gcc output. AFAIK all ABIs use the same encoding.
2758
2759 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002760
Chris Lattnerece04092012-02-07 00:39:47 +00002761 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002762 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2763 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2764 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2765
2766 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002767 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002768
2769 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002770 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00002771
2772 // 64-76 are various 4-byte special-purpose registers:
2773 // 64: mq
2774 // 65: lr
2775 // 66: ctr
2776 // 67: ap
2777 // 68-75 cr0-7
2778 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00002779 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002780
2781 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002782 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002783
2784 // 109: vrsave
2785 // 110: vscr
2786 // 111: spe_acc
2787 // 112: spefscr
2788 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002789 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002790
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002791 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002792}
2793
Roman Divackyd966e722012-05-09 18:22:46 +00002794// PowerPC-64
2795
2796namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002797/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2798class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2799
2800public:
2801 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2802
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002803 bool isPromotableTypeForABI(QualType Ty) const;
2804
2805 ABIArgInfo classifyReturnType(QualType RetTy) const;
2806 ABIArgInfo classifyArgumentType(QualType Ty) const;
2807
Bill Schmidt84d37792012-10-12 19:26:17 +00002808 // TODO: We can add more logic to computeInfo to improve performance.
2809 // Example: For aggregate arguments that fit in a register, we could
2810 // use getDirectInReg (as is done below for structs containing a single
2811 // floating-point value) to avoid pushing them to memory on function
2812 // entry. This would require changing the logic in PPCISelLowering
2813 // when lowering the parameters in the caller and args in the callee.
2814 virtual void computeInfo(CGFunctionInfo &FI) const {
2815 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2816 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2817 it != ie; ++it) {
2818 // We rely on the default argument classification for the most part.
2819 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00002820 // or vector item must be passed in a register if one is available.
Bill Schmidt84d37792012-10-12 19:26:17 +00002821 const Type *T = isSingleElementStruct(it->type, getContext());
2822 if (T) {
2823 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidt179afae2013-07-23 22:15:57 +00002824 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002825 QualType QT(T, 0);
2826 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2827 continue;
2828 }
2829 }
2830 it->info = classifyArgumentType(it->type);
2831 }
2832 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00002833
2834 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2835 QualType Ty,
2836 CodeGenFunction &CGF) const;
2837};
2838
2839class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2840public:
2841 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2842 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2843
2844 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2845 // This is recovered from gcc output.
2846 return 1; // r1 is the dedicated stack pointer
2847 }
2848
2849 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2850 llvm::Value *Address) const;
2851};
2852
Roman Divackyd966e722012-05-09 18:22:46 +00002853class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2854public:
2855 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2856
2857 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2858 // This is recovered from gcc output.
2859 return 1; // r1 is the dedicated stack pointer
2860 }
2861
2862 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2863 llvm::Value *Address) const;
2864};
2865
2866}
2867
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002868// Return true if the ABI requires Ty to be passed sign- or zero-
2869// extended to 64 bits.
2870bool
2871PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2872 // Treat an enum type as its underlying type.
2873 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2874 Ty = EnumTy->getDecl()->getIntegerType();
2875
2876 // Promotable integer types are required to be promoted by the ABI.
2877 if (Ty->isPromotableIntegerType())
2878 return true;
2879
2880 // In addition to the usual promotable integer types, we also need to
2881 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2882 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2883 switch (BT->getKind()) {
2884 case BuiltinType::Int:
2885 case BuiltinType::UInt:
2886 return true;
2887 default:
2888 break;
2889 }
2890
2891 return false;
2892}
2893
2894ABIArgInfo
2895PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00002896 if (Ty->isAnyComplexType())
2897 return ABIArgInfo::getDirect();
2898
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002899 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00002900 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002901 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002902
2903 return ABIArgInfo::getIndirect(0);
2904 }
2905
2906 return (isPromotableTypeForABI(Ty) ?
2907 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2908}
2909
2910ABIArgInfo
2911PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
2912 if (RetTy->isVoidType())
2913 return ABIArgInfo::getIgnore();
2914
Bill Schmidta3d121c2012-12-17 04:20:17 +00002915 if (RetTy->isAnyComplexType())
2916 return ABIArgInfo::getDirect();
2917
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002918 if (isAggregateTypeForABI(RetTy))
2919 return ABIArgInfo::getIndirect(0);
2920
2921 return (isPromotableTypeForABI(RetTy) ?
2922 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2923}
2924
Bill Schmidt25cb3492012-10-03 19:18:57 +00002925// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
2926llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2927 QualType Ty,
2928 CodeGenFunction &CGF) const {
2929 llvm::Type *BP = CGF.Int8PtrTy;
2930 llvm::Type *BPP = CGF.Int8PtrPtrTy;
2931
2932 CGBuilderTy &Builder = CGF.Builder;
2933 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2934 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2935
Bill Schmidt924c4782013-01-14 17:45:36 +00002936 // Update the va_list pointer. The pointer should be bumped by the
2937 // size of the object. We can trust getTypeSize() except for a complex
2938 // type whose base type is smaller than a doubleword. For these, the
2939 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00002940 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00002941 QualType BaseTy;
2942 unsigned CplxBaseSize = 0;
2943
2944 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
2945 BaseTy = CTy->getElementType();
2946 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
2947 if (CplxBaseSize < 8)
2948 SizeInBytes = 16;
2949 }
2950
Bill Schmidt25cb3492012-10-03 19:18:57 +00002951 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
2952 llvm::Value *NextAddr =
2953 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
2954 "ap.next");
2955 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2956
Bill Schmidt924c4782013-01-14 17:45:36 +00002957 // If we have a complex type and the base type is smaller than 8 bytes,
2958 // the ABI calls for the real and imaginary parts to be right-adjusted
2959 // in separate doublewords. However, Clang expects us to produce a
2960 // pointer to a structure with the two parts packed tightly. So generate
2961 // loads of the real and imaginary parts relative to the va_list pointer,
2962 // and store them to a temporary structure.
2963 if (CplxBaseSize && CplxBaseSize < 8) {
2964 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2965 llvm::Value *ImagAddr = RealAddr;
2966 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
2967 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
2968 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
2969 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
2970 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
2971 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
2972 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
2973 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
2974 "vacplx");
2975 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
2976 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
2977 Builder.CreateStore(Real, RealPtr, false);
2978 Builder.CreateStore(Imag, ImagPtr, false);
2979 return Ptr;
2980 }
2981
Bill Schmidt25cb3492012-10-03 19:18:57 +00002982 // If the argument is smaller than 8 bytes, it is right-adjusted in
2983 // its doubleword slot. Adjust the pointer to pick it up from the
2984 // correct offset.
2985 if (SizeInBytes < 8) {
2986 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2987 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
2988 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2989 }
2990
2991 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2992 return Builder.CreateBitCast(Addr, PTy);
2993}
2994
2995static bool
2996PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2997 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00002998 // This is calculated from the LLVM and GCC tables and verified
2999 // against gcc output. AFAIK all ABIs use the same encoding.
3000
3001 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3002
3003 llvm::IntegerType *i8 = CGF.Int8Ty;
3004 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3005 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3006 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3007
3008 // 0-31: r0-31, the 8-byte general-purpose registers
3009 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3010
3011 // 32-63: fp0-31, the 8-byte floating-point registers
3012 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3013
3014 // 64-76 are various 4-byte special-purpose registers:
3015 // 64: mq
3016 // 65: lr
3017 // 66: ctr
3018 // 67: ap
3019 // 68-75 cr0-7
3020 // 76: xer
3021 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3022
3023 // 77-108: v0-31, the 16-byte vector registers
3024 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3025
3026 // 109: vrsave
3027 // 110: vscr
3028 // 111: spe_acc
3029 // 112: spefscr
3030 // 113: sfp
3031 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3032
3033 return false;
3034}
John McCallea8d8bb2010-03-11 00:10:12 +00003035
Bill Schmidt25cb3492012-10-03 19:18:57 +00003036bool
3037PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3038 CodeGen::CodeGenFunction &CGF,
3039 llvm::Value *Address) const {
3040
3041 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3042}
3043
3044bool
3045PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3046 llvm::Value *Address) const {
3047
3048 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3049}
3050
Chris Lattner0cf24192010-06-28 20:05:43 +00003051//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003052// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00003053//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003054
3055namespace {
3056
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003057class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003058public:
3059 enum ABIKind {
3060 APCS = 0,
3061 AAPCS = 1,
3062 AAPCS_VFP
3063 };
3064
3065private:
3066 ABIKind Kind;
3067
3068public:
John McCall882987f2013-02-28 19:01:20 +00003069 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
3070 setRuntimeCC();
3071 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003072
John McCall3480ef22011-08-30 01:42:09 +00003073 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003074 switch (getTarget().getTriple().getEnvironment()) {
3075 case llvm::Triple::Android:
3076 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003077 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003078 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00003079 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00003080 return true;
3081 default:
3082 return false;
3083 }
John McCall3480ef22011-08-30 01:42:09 +00003084 }
3085
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003086 bool isEABIHF() const {
3087 switch (getTarget().getTriple().getEnvironment()) {
3088 case llvm::Triple::EABIHF:
3089 case llvm::Triple::GNUEABIHF:
3090 return true;
3091 default:
3092 return false;
3093 }
3094 }
3095
Daniel Dunbar020daa92009-09-12 01:00:39 +00003096 ABIKind getABIKind() const { return Kind; }
3097
Tim Northovera484bc02013-10-01 14:34:25 +00003098private:
Chris Lattner458b2aa2010-07-29 02:16:43 +00003099 ABIArgInfo classifyReturnType(QualType RetTy) const;
Manman Renb505d332012-10-31 19:02:26 +00003100 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs,
3101 unsigned &AllocatedVFP,
Manman Ren2a523d82012-10-30 23:21:41 +00003102 bool &IsHA) const;
Manman Renfef9e312012-10-16 19:18:39 +00003103 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003104
Chris Lattner22326a12010-07-29 02:31:05 +00003105 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003106
3107 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3108 CodeGenFunction &CGF) const;
John McCall882987f2013-02-28 19:01:20 +00003109
3110 llvm::CallingConv::ID getLLVMDefaultCC() const;
3111 llvm::CallingConv::ID getABIDefaultCC() const;
3112 void setRuntimeCC();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003113};
3114
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003115class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3116public:
Chris Lattner2b037972010-07-29 02:01:43 +00003117 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3118 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00003119
John McCall3480ef22011-08-30 01:42:09 +00003120 const ARMABIInfo &getABIInfo() const {
3121 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3122 }
3123
John McCallbeec5a02010-03-06 00:35:14 +00003124 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3125 return 13;
3126 }
Roman Divackyc1617352011-05-18 19:36:54 +00003127
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003128 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
John McCall31168b02011-06-15 23:02:42 +00003129 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3130 }
3131
Roman Divackyc1617352011-05-18 19:36:54 +00003132 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3133 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003134 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00003135
3136 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00003137 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00003138 return false;
3139 }
John McCall3480ef22011-08-30 01:42:09 +00003140
3141 unsigned getSizeOfUnwindException() const {
3142 if (getABIInfo().isEABI()) return 88;
3143 return TargetCodeGenInfo::getSizeOfUnwindException();
3144 }
Tim Northovera484bc02013-10-01 14:34:25 +00003145
3146 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3147 CodeGen::CodeGenModule &CGM) const {
3148 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3149 if (!FD)
3150 return;
3151
3152 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3153 if (!Attr)
3154 return;
3155
3156 const char *Kind;
3157 switch (Attr->getInterrupt()) {
3158 case ARMInterruptAttr::Generic: Kind = ""; break;
3159 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3160 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3161 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3162 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3163 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3164 }
3165
3166 llvm::Function *Fn = cast<llvm::Function>(GV);
3167
3168 Fn->addFnAttr("interrupt", Kind);
3169
3170 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3171 return;
3172
3173 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3174 // however this is not necessarily true on taking any interrupt. Instruct
3175 // the backend to perform a realignment as part of the function prologue.
3176 llvm::AttrBuilder B;
3177 B.addStackAlignmentAttr(8);
3178 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3179 llvm::AttributeSet::get(CGM.getLLVMContext(),
3180 llvm::AttributeSet::FunctionIndex,
3181 B));
3182 }
3183
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003184};
3185
Daniel Dunbard59655c2009-09-12 00:59:49 +00003186}
3187
Chris Lattner22326a12010-07-29 02:31:05 +00003188void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003189 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00003190 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00003191 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3192 // VFP registers of the appropriate type unallocated then the argument is
3193 // allocated to the lowest-numbered sequence of such registers.
3194 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3195 // unallocated are marked as unavailable.
3196 unsigned AllocatedVFP = 0;
Manman Renb505d332012-10-31 19:02:26 +00003197 int VFPRegs[16] = { 0 };
Chris Lattner458b2aa2010-07-29 02:16:43 +00003198 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003199 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Manman Ren2a523d82012-10-30 23:21:41 +00003200 it != ie; ++it) {
3201 unsigned PreAllocation = AllocatedVFP;
3202 bool IsHA = false;
3203 // 6.1.2.3 There is one VFP co-processor register class using registers
3204 // s0-s15 (d0-d7) for passing arguments.
3205 const unsigned NumVFPs = 16;
Manman Renb505d332012-10-31 19:02:26 +00003206 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA);
Manman Ren2a523d82012-10-30 23:21:41 +00003207 // If we do not have enough VFP registers for the HA, any VFP registers
3208 // that are unallocated are marked as unavailable. To achieve this, we add
3209 // padding of (NumVFPs - PreAllocation) floats.
3210 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3211 llvm::Type *PaddingTy = llvm::ArrayType::get(
3212 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3213 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3214 }
3215 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003216
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003217 // Always honor user-specified calling convention.
3218 if (FI.getCallingConvention() != llvm::CallingConv::C)
3219 return;
3220
John McCall882987f2013-02-28 19:01:20 +00003221 llvm::CallingConv::ID cc = getRuntimeCC();
3222 if (cc != llvm::CallingConv::C)
3223 FI.setEffectiveCallingConvention(cc);
3224}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00003225
John McCall882987f2013-02-28 19:01:20 +00003226/// Return the default calling convention that LLVM will use.
3227llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3228 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00003229 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00003230 return llvm::CallingConv::ARM_AAPCS_VFP;
3231 else if (isEABI())
3232 return llvm::CallingConv::ARM_AAPCS;
3233 else
3234 return llvm::CallingConv::ARM_APCS;
3235}
3236
3237/// Return the calling convention that our ABI would like us to use
3238/// as the C calling convention.
3239llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003240 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00003241 case APCS: return llvm::CallingConv::ARM_APCS;
3242 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3243 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003244 }
John McCall882987f2013-02-28 19:01:20 +00003245 llvm_unreachable("bad ABI kind");
3246}
3247
3248void ARMABIInfo::setRuntimeCC() {
3249 assert(getRuntimeCC() == llvm::CallingConv::C);
3250
3251 // Don't muddy up the IR with a ton of explicit annotations if
3252 // they'd just match what LLVM will infer from the triple.
3253 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3254 if (abiCC != getLLVMDefaultCC())
3255 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003256}
3257
Bob Wilsone826a2a2011-08-03 05:58:22 +00003258/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3259/// aggregate. If HAMembers is non-null, the number of base elements
3260/// contained in the type is returned through it; this is used for the
3261/// recursive calls that check aggregate component types.
3262static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3263 ASTContext &Context,
3264 uint64_t *HAMembers = 0) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003265 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003266 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3267 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3268 return false;
3269 Members *= AT->getSize().getZExtValue();
3270 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3271 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003272 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00003273 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003274
Bob Wilsone826a2a2011-08-03 05:58:22 +00003275 Members = 0;
3276 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3277 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003278 const FieldDecl *FD = *i;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003279 uint64_t FldMembers;
3280 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3281 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003282
3283 Members = (RD->isUnion() ?
3284 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003285 }
3286 } else {
3287 Members = 1;
3288 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3289 Members = 2;
3290 Ty = CT->getElementType();
3291 }
3292
3293 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3294 // double, or 64-bit or 128-bit vectors.
3295 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3296 if (BT->getKind() != BuiltinType::Float &&
Tim Northovereb752d42012-07-20 22:29:29 +00003297 BT->getKind() != BuiltinType::Double &&
3298 BT->getKind() != BuiltinType::LongDouble)
Bob Wilsone826a2a2011-08-03 05:58:22 +00003299 return false;
3300 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3301 unsigned VecSize = Context.getTypeSize(VT);
3302 if (VecSize != 64 && VecSize != 128)
3303 return false;
3304 } else {
3305 return false;
3306 }
3307
3308 // The base type must be the same for all members. Vector types of the
3309 // same total size are treated as being equivalent here.
3310 const Type *TyPtr = Ty.getTypePtr();
3311 if (!Base)
3312 Base = TyPtr;
3313 if (Base != TyPtr &&
3314 (!Base->isVectorType() || !TyPtr->isVectorType() ||
3315 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
3316 return false;
3317 }
3318
3319 // Homogeneous Aggregates can have at most 4 members of the base type.
3320 if (HAMembers)
3321 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003322
3323 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003324}
3325
Manman Renb505d332012-10-31 19:02:26 +00003326/// markAllocatedVFPs - update VFPRegs according to the alignment and
3327/// number of VFP registers (unit is S register) requested.
3328static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP,
3329 unsigned Alignment,
3330 unsigned NumRequired) {
3331 // Early Exit.
3332 if (AllocatedVFP >= 16)
3333 return;
3334 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3335 // VFP registers of the appropriate type unallocated then the argument is
3336 // allocated to the lowest-numbered sequence of such registers.
3337 for (unsigned I = 0; I < 16; I += Alignment) {
3338 bool FoundSlot = true;
3339 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3340 if (J >= 16 || VFPRegs[J]) {
3341 FoundSlot = false;
3342 break;
3343 }
3344 if (FoundSlot) {
3345 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3346 VFPRegs[J] = 1;
3347 AllocatedVFP += NumRequired;
3348 return;
3349 }
3350 }
3351 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3352 // unallocated are marked as unavailable.
3353 for (unsigned I = 0; I < 16; I++)
3354 VFPRegs[I] = 1;
3355 AllocatedVFP = 17; // We do not have enough VFP registers.
3356}
3357
3358ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
3359 unsigned &AllocatedVFP,
Manman Ren2a523d82012-10-30 23:21:41 +00003360 bool &IsHA) const {
3361 // We update number of allocated VFPs according to
3362 // 6.1.2.1 The following argument types are VFP CPRCs:
3363 // A single-precision floating-point type (including promoted
3364 // half-precision types); A double-precision floating-point type;
3365 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3366 // with a Base Type of a single- or double-precision floating-point type,
3367 // 64-bit containerized vectors or 128-bit containerized vectors with one
3368 // to four Elements.
3369
Manman Renfef9e312012-10-16 19:18:39 +00003370 // Handle illegal vector types here.
3371 if (isIllegalVectorType(Ty)) {
3372 uint64_t Size = getContext().getTypeSize(Ty);
3373 if (Size <= 32) {
3374 llvm::Type *ResType =
3375 llvm::Type::getInt32Ty(getVMContext());
3376 return ABIArgInfo::getDirect(ResType);
3377 }
3378 if (Size == 64) {
3379 llvm::Type *ResType = llvm::VectorType::get(
3380 llvm::Type::getInt32Ty(getVMContext()), 2);
Manman Renb505d332012-10-31 19:02:26 +00003381 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Renfef9e312012-10-16 19:18:39 +00003382 return ABIArgInfo::getDirect(ResType);
3383 }
3384 if (Size == 128) {
3385 llvm::Type *ResType = llvm::VectorType::get(
3386 llvm::Type::getInt32Ty(getVMContext()), 4);
Manman Renb505d332012-10-31 19:02:26 +00003387 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4);
Manman Renfef9e312012-10-16 19:18:39 +00003388 return ABIArgInfo::getDirect(ResType);
3389 }
3390 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3391 }
Manman Renb505d332012-10-31 19:02:26 +00003392 // Update VFPRegs for legal vector types.
Manman Ren2a523d82012-10-30 23:21:41 +00003393 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3394 uint64_t Size = getContext().getTypeSize(VT);
3395 // Size of a legal vector should be power of 2 and above 64.
Manman Renb505d332012-10-31 19:02:26 +00003396 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32);
Manman Ren2a523d82012-10-30 23:21:41 +00003397 }
Manman Renb505d332012-10-31 19:02:26 +00003398 // Update VFPRegs for floating point types.
Manman Ren2a523d82012-10-30 23:21:41 +00003399 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3400 if (BT->getKind() == BuiltinType::Half ||
3401 BT->getKind() == BuiltinType::Float)
Manman Renb505d332012-10-31 19:02:26 +00003402 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1);
Manman Ren2a523d82012-10-30 23:21:41 +00003403 if (BT->getKind() == BuiltinType::Double ||
Manman Renb505d332012-10-31 19:02:26 +00003404 BT->getKind() == BuiltinType::LongDouble)
3405 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003406 }
Manman Renfef9e312012-10-16 19:18:39 +00003407
John McCalla1dee5302010-08-22 10:59:02 +00003408 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003409 // Treat an enum type as its underlying type.
3410 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3411 Ty = EnumTy->getDecl()->getIntegerType();
3412
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003413 return (Ty->isPromotableIntegerType() ?
3414 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003415 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003416
Mark Lacey3825e832013-10-06 01:33:34 +00003417 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Tim Northover1060eae2013-06-21 22:49:34 +00003418 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3419
Daniel Dunbar09d33622009-09-14 21:54:03 +00003420 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003421 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00003422 return ABIArgInfo::getIgnore();
3423
Bob Wilsone826a2a2011-08-03 05:58:22 +00003424 if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00003425 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3426 // into VFP registers.
Bob Wilsone826a2a2011-08-03 05:58:22 +00003427 const Type *Base = 0;
Manman Ren2a523d82012-10-30 23:21:41 +00003428 uint64_t Members = 0;
3429 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003430 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00003431 // Base can be a floating-point or a vector.
3432 if (Base->isVectorType()) {
3433 // ElementSize is in number of floats.
3434 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Manman Ren77b02382012-11-06 19:05:29 +00003435 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize,
3436 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00003437 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Manman Renb505d332012-10-31 19:02:26 +00003438 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00003439 else {
3440 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3441 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Manman Renb505d332012-10-31 19:02:26 +00003442 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003443 }
3444 IsHA = true;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003445 return ABIArgInfo::getExpand();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003446 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003447 }
3448
Manman Ren6c30e132012-08-13 21:23:55 +00003449 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00003450 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3451 // most 8-byte. We realign the indirect argument if type alignment is bigger
3452 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00003453 uint64_t ABIAlign = 4;
3454 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3455 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3456 getABIKind() == ARMABIInfo::AAPCS)
3457 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00003458 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
3459 return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00003460 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00003461 }
3462
Daniel Dunbarb34b0802010-09-23 01:54:28 +00003463 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00003464 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003465 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00003466 // FIXME: Try to match the types of the arguments more accurately where
3467 // we can.
3468 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00003469 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3470 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00003471 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00003472 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3473 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00003474 }
Stuart Hastings4b214952011-04-28 18:16:06 +00003475
Chris Lattnera5f58b02011-07-09 17:41:47 +00003476 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00003477 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastings4b214952011-04-28 18:16:06 +00003478 return ABIArgInfo::getDirect(STy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003479}
3480
Chris Lattner458b2aa2010-07-29 02:16:43 +00003481static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003482 llvm::LLVMContext &VMContext) {
3483 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3484 // is called integer-like if its size is less than or equal to one word, and
3485 // the offset of each of its addressable sub-fields is zero.
3486
3487 uint64_t Size = Context.getTypeSize(Ty);
3488
3489 // Check that the type fits in a word.
3490 if (Size > 32)
3491 return false;
3492
3493 // FIXME: Handle vector types!
3494 if (Ty->isVectorType())
3495 return false;
3496
Daniel Dunbard53bac72009-09-14 02:20:34 +00003497 // Float types are never treated as "integer like".
3498 if (Ty->isRealFloatingType())
3499 return false;
3500
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003501 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00003502 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003503 return true;
3504
Daniel Dunbar96ebba52010-02-01 23:31:26 +00003505 // Small complex integer types are "integer like".
3506 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3507 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003508
3509 // Single element and zero sized arrays should be allowed, by the definition
3510 // above, but they are not.
3511
3512 // Otherwise, it must be a record type.
3513 const RecordType *RT = Ty->getAs<RecordType>();
3514 if (!RT) return false;
3515
3516 // Ignore records with flexible arrays.
3517 const RecordDecl *RD = RT->getDecl();
3518 if (RD->hasFlexibleArrayMember())
3519 return false;
3520
3521 // Check that all sub-fields are at offset 0, and are themselves "integer
3522 // like".
3523 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3524
3525 bool HadField = false;
3526 unsigned idx = 0;
3527 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3528 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00003529 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003530
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003531 // Bit-fields are not addressable, we only need to verify they are "integer
3532 // like". We still have to disallow a subsequent non-bitfield, for example:
3533 // struct { int : 0; int x }
3534 // is non-integer like according to gcc.
3535 if (FD->isBitField()) {
3536 if (!RD->isUnion())
3537 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003538
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003539 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3540 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003541
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003542 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003543 }
3544
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003545 // Check if this field is at offset 0.
3546 if (Layout.getFieldOffset(idx) != 0)
3547 return false;
3548
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003549 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3550 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003551
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003552 // Only allow at most one field in a structure. This doesn't match the
3553 // wording above, but follows gcc in situations with a field following an
3554 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003555 if (!RD->isUnion()) {
3556 if (HadField)
3557 return false;
3558
3559 HadField = true;
3560 }
3561 }
3562
3563 return true;
3564}
3565
Chris Lattner458b2aa2010-07-29 02:16:43 +00003566ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003567 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003568 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003569
Daniel Dunbar19964db2010-09-23 01:54:32 +00003570 // Large vector types should be returned via memory.
3571 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3572 return ABIArgInfo::getIndirect(0);
3573
John McCalla1dee5302010-08-22 10:59:02 +00003574 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003575 // Treat an enum type as its underlying type.
3576 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3577 RetTy = EnumTy->getDecl()->getIntegerType();
3578
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003579 return (RetTy->isPromotableIntegerType() ?
3580 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003581 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003582
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003583 // Structures with either a non-trivial destructor or a non-trivial
3584 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00003585 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003586 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3587
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003588 // Are we following APCS?
3589 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00003590 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003591 return ABIArgInfo::getIgnore();
3592
Daniel Dunbareedf1512010-02-01 23:31:19 +00003593 // Complex types are all returned as packed integers.
3594 //
3595 // FIXME: Consider using 2 x vector types if the back end handles them
3596 // correctly.
3597 if (RetTy->isAnyComplexType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003598 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00003599 getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00003600
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003601 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003602 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003603 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003604 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003605 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003606 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003607 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003608 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3609 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003610 }
3611
3612 // Otherwise return in memory.
3613 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003614 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003615
3616 // Otherwise this is an AAPCS variant.
3617
Chris Lattner458b2aa2010-07-29 02:16:43 +00003618 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003619 return ABIArgInfo::getIgnore();
3620
Bob Wilson1d9269a2011-11-02 04:51:36 +00003621 // Check for homogeneous aggregates with AAPCS-VFP.
3622 if (getABIKind() == AAPCS_VFP) {
3623 const Type *Base = 0;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003624 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3625 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00003626 // Homogeneous Aggregates are returned directly.
3627 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003628 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00003629 }
3630
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003631 // Aggregates <= 4 bytes are returned in r0; other aggregates
3632 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003633 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003634 if (Size <= 32) {
3635 // Return in the smallest viable integer type.
3636 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003637 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003638 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003639 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3640 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003641 }
3642
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003643 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003644}
3645
Manman Renfef9e312012-10-16 19:18:39 +00003646/// isIllegalVector - check whether Ty is an illegal vector type.
3647bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3648 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3649 // Check whether VT is legal.
3650 unsigned NumElements = VT->getNumElements();
3651 uint64_t Size = getContext().getTypeSize(VT);
3652 // NumElements should be power of 2.
3653 if ((NumElements & (NumElements - 1)) != 0)
3654 return true;
3655 // Size should be greater than 32 bits.
3656 return Size <= 32;
3657 }
3658 return false;
3659}
3660
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003661llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003662 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003663 llvm::Type *BP = CGF.Int8PtrTy;
3664 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003665
3666 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00003667 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003668 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00003669
Tim Northover1711cc92013-06-21 23:05:33 +00003670 if (isEmptyRecord(getContext(), Ty, true)) {
3671 // These are ignored for parameter passing purposes.
3672 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3673 return Builder.CreateBitCast(Addr, PTy);
3674 }
3675
Manman Rencca54d02012-10-16 19:01:37 +00003676 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00003677 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00003678 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00003679
3680 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3681 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00003682 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3683 getABIKind() == ARMABIInfo::AAPCS)
3684 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3685 else
3686 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00003687 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3688 if (isIllegalVectorType(Ty) && Size > 16) {
3689 IsIndirect = true;
3690 Size = 4;
3691 TyAlign = 4;
3692 }
Manman Rencca54d02012-10-16 19:01:37 +00003693
3694 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00003695 if (TyAlign > 4) {
3696 assert((TyAlign & (TyAlign - 1)) == 0 &&
3697 "Alignment is not power of 2!");
3698 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3699 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3700 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00003701 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00003702 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003703
3704 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00003705 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003706 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003707 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003708 "ap.next");
3709 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3710
Manman Renfef9e312012-10-16 19:18:39 +00003711 if (IsIndirect)
3712 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00003713 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00003714 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3715 // may not be correctly aligned for the vector type. We create an aligned
3716 // temporary space and copy the content over from ap.cur to the temporary
3717 // space. This is necessary if the natural alignment of the type is greater
3718 // than the ABI alignment.
3719 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3720 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3721 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3722 "var.align");
3723 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3724 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3725 Builder.CreateMemCpy(Dst, Src,
3726 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3727 TyAlign, false);
3728 Addr = AlignedTemp; //The content is in aligned location.
3729 }
3730 llvm::Type *PTy =
3731 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3732 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3733
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003734 return AddrTyped;
3735}
3736
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003737namespace {
3738
Derek Schuffa2020962012-10-16 22:30:41 +00003739class NaClARMABIInfo : public ABIInfo {
3740 public:
3741 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3742 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3743 virtual void computeInfo(CGFunctionInfo &FI) const;
3744 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3745 CodeGenFunction &CGF) const;
3746 private:
3747 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3748 ARMABIInfo NInfo; // Used for everything else.
3749};
3750
3751class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3752 public:
3753 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3754 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3755};
3756
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003757}
3758
Derek Schuffa2020962012-10-16 22:30:41 +00003759void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3760 if (FI.getASTCallingConvention() == CC_PnaclCall)
3761 PInfo.computeInfo(FI);
3762 else
3763 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3764}
3765
3766llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3767 CodeGenFunction &CGF) const {
3768 // Always use the native convention; calling pnacl-style varargs functions
3769 // is unsupported.
3770 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3771}
3772
Chris Lattner0cf24192010-06-28 20:05:43 +00003773//===----------------------------------------------------------------------===//
Tim Northover9bb857a2013-01-31 12:13:10 +00003774// AArch64 ABI Implementation
3775//===----------------------------------------------------------------------===//
3776
3777namespace {
3778
3779class AArch64ABIInfo : public ABIInfo {
3780public:
3781 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3782
3783private:
3784 // The AArch64 PCS is explicit about return types and argument types being
3785 // handled identically, so we don't need to draw a distinction between
3786 // Argument and Return classification.
3787 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3788 int &FreeVFPRegs) const;
3789
3790 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3791 llvm::Type *DirectTy = 0) const;
3792
3793 virtual void computeInfo(CGFunctionInfo &FI) const;
3794
3795 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3796 CodeGenFunction &CGF) const;
3797};
3798
3799class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3800public:
3801 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3802 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3803
3804 const AArch64ABIInfo &getABIInfo() const {
3805 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3806 }
3807
3808 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3809 return 31;
3810 }
3811
3812 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3813 llvm::Value *Address) const {
3814 // 0-31 are x0-x30 and sp: 8 bytes each
3815 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
3816 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
3817
3818 // 64-95 are v0-v31: 16 bytes each
3819 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
3820 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
3821
3822 return false;
3823 }
3824
3825};
3826
3827}
3828
3829void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3830 int FreeIntRegs = 8, FreeVFPRegs = 8;
3831
3832 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
3833 FreeIntRegs, FreeVFPRegs);
3834
3835 FreeIntRegs = FreeVFPRegs = 8;
3836 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3837 it != ie; ++it) {
3838 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
3839
3840 }
3841}
3842
3843ABIArgInfo
3844AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
3845 bool IsInt, llvm::Type *DirectTy) const {
3846 if (FreeRegs >= RegsNeeded) {
3847 FreeRegs -= RegsNeeded;
3848 return ABIArgInfo::getDirect(DirectTy);
3849 }
3850
3851 llvm::Type *Padding = 0;
3852
3853 // We need padding so that later arguments don't get filled in anyway. That
3854 // wouldn't happen if only ByVal arguments followed in the same category, but
3855 // a large structure will simply seem to be a pointer as far as LLVM is
3856 // concerned.
3857 if (FreeRegs > 0) {
3858 if (IsInt)
3859 Padding = llvm::Type::getInt64Ty(getVMContext());
3860 else
3861 Padding = llvm::Type::getFloatTy(getVMContext());
3862
3863 // Either [N x i64] or [N x float].
3864 Padding = llvm::ArrayType::get(Padding, FreeRegs);
3865 FreeRegs = 0;
3866 }
3867
3868 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
3869 /*IsByVal=*/ true, /*Realign=*/ false,
3870 Padding);
3871}
3872
3873
3874ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
3875 int &FreeIntRegs,
3876 int &FreeVFPRegs) const {
3877 // Can only occurs for return, but harmless otherwise.
3878 if (Ty->isVoidType())
3879 return ABIArgInfo::getIgnore();
3880
3881 // Large vector types should be returned via memory. There's no such concept
3882 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
3883 // classified they'd go into memory (see B.3).
3884 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
3885 if (FreeIntRegs > 0)
3886 --FreeIntRegs;
3887 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3888 }
3889
3890 // All non-aggregate LLVM types have a concrete ABI representation so they can
3891 // be passed directly. After this block we're guaranteed to be in a
3892 // complicated case.
3893 if (!isAggregateTypeForABI(Ty)) {
3894 // Treat an enum type as its underlying type.
3895 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3896 Ty = EnumTy->getDecl()->getIntegerType();
3897
3898 if (Ty->isFloatingType() || Ty->isVectorType())
3899 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
3900
3901 assert(getContext().getTypeSize(Ty) <= 128 &&
3902 "unexpectedly large scalar type");
3903
3904 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3905
3906 // If the type may need padding registers to ensure "alignment", we must be
3907 // careful when this is accounted for. Increasing the effective size covers
3908 // all cases.
3909 if (getContext().getTypeAlign(Ty) == 128)
3910 RegsNeeded += FreeIntRegs % 2 != 0;
3911
3912 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
3913 }
3914
Mark Lacey3825e832013-10-06 01:33:34 +00003915 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003916 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northover9bb857a2013-01-31 12:13:10 +00003917 --FreeIntRegs;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003918 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northover9bb857a2013-01-31 12:13:10 +00003919 }
3920
3921 if (isEmptyRecord(getContext(), Ty, true)) {
3922 if (!getContext().getLangOpts().CPlusPlus) {
3923 // Empty structs outside C++ mode are a GNU extension, so no ABI can
3924 // possibly tell us what to do. It turns out (I believe) that GCC ignores
3925 // the object for parameter-passsing purposes.
3926 return ABIArgInfo::getIgnore();
3927 }
3928
3929 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
3930 // description of va_arg in the PCS require that an empty struct does
3931 // actually occupy space for parameter-passing. I'm hoping for a
3932 // clarification giving an explicit paragraph to point to in future.
3933 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
3934 llvm::Type::getInt8Ty(getVMContext()));
3935 }
3936
3937 // Homogeneous vector aggregates get passed in registers or on the stack.
3938 const Type *Base = 0;
3939 uint64_t NumMembers = 0;
3940 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
3941 assert(Base && "Base class should be set for homogeneous aggregate");
3942 // Homogeneous aggregates are passed and returned directly.
3943 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
3944 /*IsInt=*/ false);
3945 }
3946
3947 uint64_t Size = getContext().getTypeSize(Ty);
3948 if (Size <= 128) {
3949 // Small structs can use the same direct type whether they're in registers
3950 // or on the stack.
3951 llvm::Type *BaseTy;
3952 unsigned NumBases;
3953 int SizeInRegs = (Size + 63) / 64;
3954
3955 if (getContext().getTypeAlign(Ty) == 128) {
3956 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
3957 NumBases = 1;
3958
3959 // If the type may need padding registers to ensure "alignment", we must
3960 // be careful when this is accounted for. Increasing the effective size
3961 // covers all cases.
3962 SizeInRegs += FreeIntRegs % 2 != 0;
3963 } else {
3964 BaseTy = llvm::Type::getInt64Ty(getVMContext());
3965 NumBases = SizeInRegs;
3966 }
3967 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
3968
3969 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
3970 /*IsInt=*/ true, DirectTy);
3971 }
3972
3973 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
3974 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
3975 --FreeIntRegs;
3976 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
3977}
3978
3979llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3980 CodeGenFunction &CGF) const {
3981 // The AArch64 va_list type and handling is specified in the Procedure Call
3982 // Standard, section B.4:
3983 //
3984 // struct {
3985 // void *__stack;
3986 // void *__gr_top;
3987 // void *__vr_top;
3988 // int __gr_offs;
3989 // int __vr_offs;
3990 // };
3991
3992 assert(!CGF.CGM.getDataLayout().isBigEndian()
3993 && "va_arg not implemented for big-endian AArch64");
3994
3995 int FreeIntRegs = 8, FreeVFPRegs = 8;
3996 Ty = CGF.getContext().getCanonicalType(Ty);
3997 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
3998
3999 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4000 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4001 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4002 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4003
4004 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
4005 int reg_top_index;
4006 int RegSize;
4007 if (FreeIntRegs < 8) {
4008 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
4009 // 3 is the field number of __gr_offs
4010 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4011 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4012 reg_top_index = 1; // field number for __gr_top
4013 RegSize = 8 * (8 - FreeIntRegs);
4014 } else {
4015 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
4016 // 4 is the field number of __vr_offs.
4017 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4018 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4019 reg_top_index = 2; // field number for __vr_top
4020 RegSize = 16 * (8 - FreeVFPRegs);
4021 }
4022
4023 //=======================================
4024 // Find out where argument was passed
4025 //=======================================
4026
4027 // If reg_offs >= 0 we're already using the stack for this type of
4028 // argument. We don't want to keep updating reg_offs (in case it overflows,
4029 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4030 // whatever they get).
4031 llvm::Value *UsingStack = 0;
4032 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
4033 llvm::ConstantInt::get(CGF.Int32Ty, 0));
4034
4035 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4036
4037 // Otherwise, at least some kind of argument could go in these registers, the
4038 // quesiton is whether this particular type is too big.
4039 CGF.EmitBlock(MaybeRegBlock);
4040
4041 // Integer arguments may need to correct register alignment (for example a
4042 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4043 // align __gr_offs to calculate the potential address.
4044 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4045 int Align = getContext().getTypeAlign(Ty) / 8;
4046
4047 reg_offs = CGF.Builder.CreateAdd(reg_offs,
4048 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4049 "align_regoffs");
4050 reg_offs = CGF.Builder.CreateAnd(reg_offs,
4051 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4052 "aligned_regoffs");
4053 }
4054
4055 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4056 llvm::Value *NewOffset = 0;
4057 NewOffset = CGF.Builder.CreateAdd(reg_offs,
4058 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4059 "new_reg_offs");
4060 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4061
4062 // Now we're in a position to decide whether this argument really was in
4063 // registers or not.
4064 llvm::Value *InRegs = 0;
4065 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4066 llvm::ConstantInt::get(CGF.Int32Ty, 0),
4067 "inreg");
4068
4069 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4070
4071 //=======================================
4072 // Argument was in registers
4073 //=======================================
4074
4075 // Now we emit the code for if the argument was originally passed in
4076 // registers. First start the appropriate block:
4077 CGF.EmitBlock(InRegBlock);
4078
4079 llvm::Value *reg_top_p = 0, *reg_top = 0;
4080 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4081 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4082 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4083 llvm::Value *RegAddr = 0;
4084 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4085
4086 if (!AI.isDirect()) {
4087 // If it's been passed indirectly (actually a struct), whatever we find from
4088 // stored registers or on the stack will actually be a struct **.
4089 MemTy = llvm::PointerType::getUnqual(MemTy);
4090 }
4091
4092 const Type *Base = 0;
4093 uint64_t NumMembers;
4094 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4095 && NumMembers > 1) {
4096 // Homogeneous aggregates passed in registers will have their elements split
4097 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4098 // qN+1, ...). We reload and store into a temporary local variable
4099 // contiguously.
4100 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4101 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4102 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4103 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4104
4105 for (unsigned i = 0; i < NumMembers; ++i) {
4106 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
4107 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4108 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4109 llvm::PointerType::getUnqual(BaseTy));
4110 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4111
4112 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4113 CGF.Builder.CreateStore(Elem, StoreAddr);
4114 }
4115
4116 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4117 } else {
4118 // Otherwise the object is contiguous in memory
4119 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4120 }
4121
4122 CGF.EmitBranch(ContBlock);
4123
4124 //=======================================
4125 // Argument was on the stack
4126 //=======================================
4127 CGF.EmitBlock(OnStackBlock);
4128
4129 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4130 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4131 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4132
4133 // Again, stack arguments may need realigmnent. In this case both integer and
4134 // floating-point ones might be affected.
4135 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4136 int Align = getContext().getTypeAlign(Ty) / 8;
4137
4138 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4139
4140 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4141 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4142 "align_stack");
4143 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4144 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4145 "align_stack");
4146
4147 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4148 }
4149
4150 uint64_t StackSize;
4151 if (AI.isDirect())
4152 StackSize = getContext().getTypeSize(Ty) / 8;
4153 else
4154 StackSize = 8;
4155
4156 // All stack slots are 8 bytes
4157 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4158
4159 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4160 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4161 "new_stack");
4162
4163 // Write the new value of __stack for the next call to va_arg
4164 CGF.Builder.CreateStore(NewStack, stack_p);
4165
4166 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4167
4168 CGF.EmitBranch(ContBlock);
4169
4170 //=======================================
4171 // Tidy up
4172 //=======================================
4173 CGF.EmitBlock(ContBlock);
4174
4175 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4176 ResAddr->addIncoming(RegAddr, InRegBlock);
4177 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4178
4179 if (AI.isDirect())
4180 return ResAddr;
4181
4182 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4183}
4184
4185//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004186// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004187//===----------------------------------------------------------------------===//
4188
4189namespace {
4190
Justin Holewinski83e96682012-05-24 17:43:12 +00004191class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004192public:
Justin Holewinski36837432013-03-30 14:38:24 +00004193 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004194
4195 ABIArgInfo classifyReturnType(QualType RetTy) const;
4196 ABIArgInfo classifyArgumentType(QualType Ty) const;
4197
4198 virtual void computeInfo(CGFunctionInfo &FI) const;
4199 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4200 CodeGenFunction &CFG) const;
4201};
4202
Justin Holewinski83e96682012-05-24 17:43:12 +00004203class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004204public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004205 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4206 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Justin Holewinski38031972011-10-05 17:58:44 +00004207
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004208 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4209 CodeGen::CodeGenModule &M) const;
Justin Holewinski36837432013-03-30 14:38:24 +00004210private:
4211 static void addKernelMetadata(llvm::Function *F);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004212};
4213
Justin Holewinski83e96682012-05-24 17:43:12 +00004214ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004215 if (RetTy->isVoidType())
4216 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004217
4218 // note: this is different from default ABI
4219 if (!RetTy->isScalarType())
4220 return ABIArgInfo::getDirect();
4221
4222 // Treat an enum type as its underlying type.
4223 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4224 RetTy = EnumTy->getDecl()->getIntegerType();
4225
4226 return (RetTy->isPromotableIntegerType() ?
4227 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004228}
4229
Justin Holewinski83e96682012-05-24 17:43:12 +00004230ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004231 // Treat an enum type as its underlying type.
4232 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4233 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004234
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004235 return (Ty->isPromotableIntegerType() ?
4236 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004237}
4238
Justin Holewinski83e96682012-05-24 17:43:12 +00004239void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004240 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4241 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4242 it != ie; ++it)
4243 it->info = classifyArgumentType(it->type);
4244
4245 // Always honor user-specified calling convention.
4246 if (FI.getCallingConvention() != llvm::CallingConv::C)
4247 return;
4248
John McCall882987f2013-02-28 19:01:20 +00004249 FI.setEffectiveCallingConvention(getRuntimeCC());
4250}
4251
Justin Holewinski83e96682012-05-24 17:43:12 +00004252llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4253 CodeGenFunction &CFG) const {
4254 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004255}
4256
Justin Holewinski83e96682012-05-24 17:43:12 +00004257void NVPTXTargetCodeGenInfo::
4258SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4259 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004260 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4261 if (!FD) return;
4262
4263 llvm::Function *F = cast<llvm::Function>(GV);
4264
4265 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004266 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004267 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004268 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004269 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004270 // OpenCL __kernel functions get kernel metadata
4271 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004272 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004273 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004274 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004275 }
Justin Holewinski38031972011-10-05 17:58:44 +00004276
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004277 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004278 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004279 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004280 // __global__ functions cannot be called from the device, we do not
4281 // need to set the noinline attribute.
Aaron Ballman9ead1242013-12-19 02:39:40 +00004282 if (FD->hasAttr<CUDAGlobalAttr>())
Justin Holewinski36837432013-03-30 14:38:24 +00004283 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004284 }
4285}
4286
Justin Holewinski36837432013-03-30 14:38:24 +00004287void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4288 llvm::Module *M = F->getParent();
4289 llvm::LLVMContext &Ctx = M->getContext();
4290
4291 // Get "nvvm.annotations" metadata node
4292 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4293
4294 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4295 llvm::SmallVector<llvm::Value *, 3> MDVals;
4296 MDVals.push_back(F);
4297 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4298 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4299
4300 // Append metadata to nvvm.annotations
4301 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4302}
4303
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004304}
4305
4306//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00004307// SystemZ ABI Implementation
4308//===----------------------------------------------------------------------===//
4309
4310namespace {
4311
4312class SystemZABIInfo : public ABIInfo {
4313public:
4314 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4315
4316 bool isPromotableIntegerType(QualType Ty) const;
4317 bool isCompoundType(QualType Ty) const;
4318 bool isFPArgumentType(QualType Ty) const;
4319
4320 ABIArgInfo classifyReturnType(QualType RetTy) const;
4321 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4322
4323 virtual void computeInfo(CGFunctionInfo &FI) const {
4324 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4325 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4326 it != ie; ++it)
4327 it->info = classifyArgumentType(it->type);
4328 }
4329
4330 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4331 CodeGenFunction &CGF) const;
4332};
4333
4334class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4335public:
4336 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4337 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4338};
4339
4340}
4341
4342bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4343 // Treat an enum type as its underlying type.
4344 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4345 Ty = EnumTy->getDecl()->getIntegerType();
4346
4347 // Promotable integer types are required to be promoted by the ABI.
4348 if (Ty->isPromotableIntegerType())
4349 return true;
4350
4351 // 32-bit values must also be promoted.
4352 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4353 switch (BT->getKind()) {
4354 case BuiltinType::Int:
4355 case BuiltinType::UInt:
4356 return true;
4357 default:
4358 return false;
4359 }
4360 return false;
4361}
4362
4363bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4364 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4365}
4366
4367bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4368 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4369 switch (BT->getKind()) {
4370 case BuiltinType::Float:
4371 case BuiltinType::Double:
4372 return true;
4373 default:
4374 return false;
4375 }
4376
4377 if (const RecordType *RT = Ty->getAsStructureType()) {
4378 const RecordDecl *RD = RT->getDecl();
4379 bool Found = false;
4380
4381 // If this is a C++ record, check the bases first.
4382 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4383 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4384 E = CXXRD->bases_end(); I != E; ++I) {
4385 QualType Base = I->getType();
4386
4387 // Empty bases don't affect things either way.
4388 if (isEmptyRecord(getContext(), Base, true))
4389 continue;
4390
4391 if (Found)
4392 return false;
4393 Found = isFPArgumentType(Base);
4394 if (!Found)
4395 return false;
4396 }
4397
4398 // Check the fields.
4399 for (RecordDecl::field_iterator I = RD->field_begin(),
4400 E = RD->field_end(); I != E; ++I) {
4401 const FieldDecl *FD = *I;
4402
4403 // Empty bitfields don't affect things either way.
4404 // Unlike isSingleElementStruct(), empty structure and array fields
4405 // do count. So do anonymous bitfields that aren't zero-sized.
4406 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4407 return true;
4408
4409 // Unlike isSingleElementStruct(), arrays do not count.
4410 // Nested isFPArgumentType structures still do though.
4411 if (Found)
4412 return false;
4413 Found = isFPArgumentType(FD->getType());
4414 if (!Found)
4415 return false;
4416 }
4417
4418 // Unlike isSingleElementStruct(), trailing padding is allowed.
4419 // An 8-byte aligned struct s { float f; } is passed as a double.
4420 return Found;
4421 }
4422
4423 return false;
4424}
4425
4426llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4427 CodeGenFunction &CGF) const {
4428 // Assume that va_list type is correct; should be pointer to LLVM type:
4429 // struct {
4430 // i64 __gpr;
4431 // i64 __fpr;
4432 // i8 *__overflow_arg_area;
4433 // i8 *__reg_save_area;
4434 // };
4435
4436 // Every argument occupies 8 bytes and is passed by preference in either
4437 // GPRs or FPRs.
4438 Ty = CGF.getContext().getCanonicalType(Ty);
4439 ABIArgInfo AI = classifyArgumentType(Ty);
4440 bool InFPRs = isFPArgumentType(Ty);
4441
4442 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4443 bool IsIndirect = AI.isIndirect();
4444 unsigned UnpaddedBitSize;
4445 if (IsIndirect) {
4446 APTy = llvm::PointerType::getUnqual(APTy);
4447 UnpaddedBitSize = 64;
4448 } else
4449 UnpaddedBitSize = getContext().getTypeSize(Ty);
4450 unsigned PaddedBitSize = 64;
4451 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4452
4453 unsigned PaddedSize = PaddedBitSize / 8;
4454 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4455
4456 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4457 if (InFPRs) {
4458 MaxRegs = 4; // Maximum of 4 FPR arguments
4459 RegCountField = 1; // __fpr
4460 RegSaveIndex = 16; // save offset for f0
4461 RegPadding = 0; // floats are passed in the high bits of an FPR
4462 } else {
4463 MaxRegs = 5; // Maximum of 5 GPR arguments
4464 RegCountField = 0; // __gpr
4465 RegSaveIndex = 2; // save offset for r2
4466 RegPadding = Padding; // values are passed in the low bits of a GPR
4467 }
4468
4469 llvm::Value *RegCountPtr =
4470 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4471 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4472 llvm::Type *IndexTy = RegCount->getType();
4473 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4474 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
4475 "fits_in_regs");
4476
4477 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4478 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4479 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4480 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4481
4482 // Emit code to load the value if it was passed in registers.
4483 CGF.EmitBlock(InRegBlock);
4484
4485 // Work out the address of an argument register.
4486 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4487 llvm::Value *ScaledRegCount =
4488 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4489 llvm::Value *RegBase =
4490 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4491 llvm::Value *RegOffset =
4492 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4493 llvm::Value *RegSaveAreaPtr =
4494 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4495 llvm::Value *RegSaveArea =
4496 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4497 llvm::Value *RawRegAddr =
4498 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4499 llvm::Value *RegAddr =
4500 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4501
4502 // Update the register count
4503 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4504 llvm::Value *NewRegCount =
4505 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4506 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4507 CGF.EmitBranch(ContBlock);
4508
4509 // Emit code to load the value if it was passed in memory.
4510 CGF.EmitBlock(InMemBlock);
4511
4512 // Work out the address of a stack argument.
4513 llvm::Value *OverflowArgAreaPtr =
4514 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4515 llvm::Value *OverflowArgArea =
4516 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4517 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4518 llvm::Value *RawMemAddr =
4519 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4520 llvm::Value *MemAddr =
4521 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4522
4523 // Update overflow_arg_area_ptr pointer
4524 llvm::Value *NewOverflowArgArea =
4525 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4526 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4527 CGF.EmitBranch(ContBlock);
4528
4529 // Return the appropriate result.
4530 CGF.EmitBlock(ContBlock);
4531 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4532 ResAddr->addIncoming(RegAddr, InRegBlock);
4533 ResAddr->addIncoming(MemAddr, InMemBlock);
4534
4535 if (IsIndirect)
4536 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4537
4538 return ResAddr;
4539}
4540
John McCall1fe2a8c2013-06-18 02:46:29 +00004541bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4542 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4543 assert(Triple.getArch() == llvm::Triple::x86);
4544
4545 switch (Opts.getStructReturnConvention()) {
4546 case CodeGenOptions::SRCK_Default:
4547 break;
4548 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4549 return false;
4550 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4551 return true;
4552 }
4553
4554 if (Triple.isOSDarwin())
4555 return true;
4556
4557 switch (Triple.getOS()) {
4558 case llvm::Triple::Cygwin:
4559 case llvm::Triple::MinGW32:
4560 case llvm::Triple::AuroraUX:
4561 case llvm::Triple::DragonFly:
4562 case llvm::Triple::FreeBSD:
4563 case llvm::Triple::OpenBSD:
4564 case llvm::Triple::Bitrig:
4565 case llvm::Triple::Win32:
4566 return true;
4567 default:
4568 return false;
4569 }
4570}
Ulrich Weigand47445072013-05-06 16:26:41 +00004571
4572ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4573 if (RetTy->isVoidType())
4574 return ABIArgInfo::getIgnore();
4575 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4576 return ABIArgInfo::getIndirect(0);
4577 return (isPromotableIntegerType(RetTy) ?
4578 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4579}
4580
4581ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4582 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00004583 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00004584 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4585
4586 // Integers and enums are extended to full register width.
4587 if (isPromotableIntegerType(Ty))
4588 return ABIArgInfo::getExtend();
4589
4590 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4591 uint64_t Size = getContext().getTypeSize(Ty);
4592 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00004593 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004594
4595 // Handle small structures.
4596 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4597 // Structures with flexible arrays have variable length, so really
4598 // fail the size test above.
4599 const RecordDecl *RD = RT->getDecl();
4600 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00004601 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004602
4603 // The structure is passed as an unextended integer, a float, or a double.
4604 llvm::Type *PassTy;
4605 if (isFPArgumentType(Ty)) {
4606 assert(Size == 32 || Size == 64);
4607 if (Size == 32)
4608 PassTy = llvm::Type::getFloatTy(getVMContext());
4609 else
4610 PassTy = llvm::Type::getDoubleTy(getVMContext());
4611 } else
4612 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4613 return ABIArgInfo::getDirect(PassTy);
4614 }
4615
4616 // Non-structure compounds are passed indirectly.
4617 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00004618 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00004619
4620 return ABIArgInfo::getDirect(0);
4621}
4622
4623//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004624// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004625//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004626
4627namespace {
4628
4629class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4630public:
Chris Lattner2b037972010-07-29 02:01:43 +00004631 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4632 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004633 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4634 CodeGen::CodeGenModule &M) const;
4635};
4636
4637}
4638
4639void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4640 llvm::GlobalValue *GV,
4641 CodeGen::CodeGenModule &M) const {
4642 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4643 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4644 // Handle 'interrupt' attribute:
4645 llvm::Function *F = cast<llvm::Function>(GV);
4646
4647 // Step 1: Set ISR calling convention.
4648 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4649
4650 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00004651 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004652
4653 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004654 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004655 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004656 "__isr_" + Twine(Num),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004657 GV, &M.getModule());
4658 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004659 }
4660}
4661
Chris Lattner0cf24192010-06-28 20:05:43 +00004662//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00004663// MIPS ABI Implementation. This works for both little-endian and
4664// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00004665//===----------------------------------------------------------------------===//
4666
John McCall943fae92010-05-27 06:19:26 +00004667namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004668class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00004669 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004670 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4671 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004672 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004673 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004674 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004675 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004676public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004677 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004678 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004679 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00004680
4681 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004682 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004683 virtual void computeInfo(CGFunctionInfo &FI) const;
4684 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4685 CodeGenFunction &CGF) const;
4686};
4687
John McCall943fae92010-05-27 06:19:26 +00004688class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004689 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00004690public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00004691 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
4692 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00004693 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00004694
4695 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4696 return 29;
4697 }
4698
Reed Kotler373feca2013-01-16 17:10:28 +00004699 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4700 CodeGen::CodeGenModule &CGM) const {
Reed Kotler3d5966f2013-03-13 20:40:30 +00004701 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4702 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00004703 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00004704 if (FD->hasAttr<Mips16Attr>()) {
4705 Fn->addFnAttr("mips16");
4706 }
4707 else if (FD->hasAttr<NoMips16Attr>()) {
4708 Fn->addFnAttr("nomips16");
4709 }
Reed Kotler373feca2013-01-16 17:10:28 +00004710 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00004711
John McCall943fae92010-05-27 06:19:26 +00004712 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004713 llvm::Value *Address) const;
John McCall3480ef22011-08-30 01:42:09 +00004714
4715 unsigned getSizeOfUnwindException() const {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004716 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00004717 }
John McCall943fae92010-05-27 06:19:26 +00004718};
4719}
4720
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004721void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004722 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004723 llvm::IntegerType *IntTy =
4724 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004725
4726 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4727 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4728 ArgList.push_back(IntTy);
4729
4730 // If necessary, add one more integer type to ArgList.
4731 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4732
4733 if (R)
4734 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004735}
4736
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004737// In N32/64, an aligned double precision floating point field is passed in
4738// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004739llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004740 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4741
4742 if (IsO32) {
4743 CoerceToIntArgs(TySize, ArgList);
4744 return llvm::StructType::get(getVMContext(), ArgList);
4745 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004746
Akira Hatanaka02e13e52012-01-12 00:52:17 +00004747 if (Ty->isComplexType())
4748 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00004749
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004750 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004751
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004752 // Unions/vectors are passed in integer registers.
4753 if (!RT || !RT->isStructureOrClassType()) {
4754 CoerceToIntArgs(TySize, ArgList);
4755 return llvm::StructType::get(getVMContext(), ArgList);
4756 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004757
4758 const RecordDecl *RD = RT->getDecl();
4759 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004760 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004761
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004762 uint64_t LastOffset = 0;
4763 unsigned idx = 0;
4764 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4765
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004766 // Iterate over fields in the struct/class and check if there are any aligned
4767 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004768 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4769 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004770 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004771 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4772
4773 if (!BT || BT->getKind() != BuiltinType::Double)
4774 continue;
4775
4776 uint64_t Offset = Layout.getFieldOffset(idx);
4777 if (Offset % 64) // Ignore doubles that are not aligned.
4778 continue;
4779
4780 // Add ((Offset - LastOffset) / 64) args of type i64.
4781 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4782 ArgList.push_back(I64);
4783
4784 // Add double type.
4785 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4786 LastOffset = Offset + 64;
4787 }
4788
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004789 CoerceToIntArgs(TySize - LastOffset, IntArgList);
4790 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004791
4792 return llvm::StructType::get(getVMContext(), ArgList);
4793}
4794
Akira Hatanakaddd66342013-10-29 18:41:15 +00004795llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
4796 uint64_t Offset) const {
4797 if (OrigOffset + MinABIStackAlignInBytes > Offset)
4798 return 0;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004799
Akira Hatanakaddd66342013-10-29 18:41:15 +00004800 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00004801}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00004802
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004803ABIArgInfo
4804MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00004805 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004806 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00004807 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004808
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004809 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
4810 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00004811 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
4812 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004813
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004814 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004815 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004816 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00004817 return ABIArgInfo::getIgnore();
4818
Mark Lacey3825e832013-10-06 01:33:34 +00004819 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004820 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004821 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004822 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00004823
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004824 // If we have reached here, aggregates are passed directly by coercing to
4825 // another structure type. Padding is inserted if the offset of the
4826 // aggregate is unaligned.
4827 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00004828 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00004829 }
4830
4831 // Treat an enum type as its underlying type.
4832 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4833 Ty = EnumTy->getDecl()->getIntegerType();
4834
Akira Hatanaka1632af62012-01-09 19:31:25 +00004835 if (Ty->isPromotableIntegerType())
4836 return ABIArgInfo::getExtend();
4837
Akira Hatanakaddd66342013-10-29 18:41:15 +00004838 return ABIArgInfo::getDirect(
4839 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00004840}
4841
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004842llvm::Type*
4843MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00004844 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004845 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004846
Akira Hatanakab6f74432012-02-09 18:49:26 +00004847 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004848 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00004849 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4850 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004851
Akira Hatanakab6f74432012-02-09 18:49:26 +00004852 // N32/64 returns struct/classes in floating point registers if the
4853 // following conditions are met:
4854 // 1. The size of the struct/class is no larger than 128-bit.
4855 // 2. The struct/class has one or two fields all of which are floating
4856 // point types.
4857 // 3. The offset of the first field is zero (this follows what gcc does).
4858 //
4859 // Any other composite results are returned in integer registers.
4860 //
4861 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
4862 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
4863 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004864 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004865
Akira Hatanakab6f74432012-02-09 18:49:26 +00004866 if (!BT || !BT->isFloatingPoint())
4867 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004868
David Blaikie2d7c57e2012-04-30 02:36:29 +00004869 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00004870 }
4871
4872 if (b == e)
4873 return llvm::StructType::get(getVMContext(), RTList,
4874 RD->hasAttr<PackedAttr>());
4875
4876 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004877 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004878 }
4879
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004880 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004881 return llvm::StructType::get(getVMContext(), RTList);
4882}
4883
Akira Hatanakab579fe52011-06-02 00:09:17 +00004884ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00004885 uint64_t Size = getContext().getTypeSize(RetTy);
4886
4887 if (RetTy->isVoidType() || Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00004888 return ABIArgInfo::getIgnore();
4889
Akira Hatanakac37eddf2012-05-11 21:01:17 +00004890 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey3825e832013-10-06 01:33:34 +00004891 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004892 return ABIArgInfo::getIndirect(0);
4893
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004894 if (Size <= 128) {
4895 if (RetTy->isAnyComplexType())
4896 return ABIArgInfo::getDirect();
4897
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004898 // O32 returns integer vectors in registers.
4899 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
4900 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4901
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004902 if (!IsO32)
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004903 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4904 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00004905
4906 return ABIArgInfo::getIndirect(0);
4907 }
4908
4909 // Treat an enum type as its underlying type.
4910 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4911 RetTy = EnumTy->getDecl()->getIntegerType();
4912
4913 return (RetTy->isPromotableIntegerType() ?
4914 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4915}
4916
4917void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00004918 ABIArgInfo &RetInfo = FI.getReturnInfo();
4919 RetInfo = classifyReturnType(FI.getReturnType());
4920
4921 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004922 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00004923
Akira Hatanakab579fe52011-06-02 00:09:17 +00004924 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4925 it != ie; ++it)
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004926 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00004927}
4928
4929llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4930 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004931 llvm::Type *BP = CGF.Int8PtrTy;
4932 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004933
4934 CGBuilderTy &Builder = CGF.Builder;
4935 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4936 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka37715282012-01-23 23:59:52 +00004937 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004938 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4939 llvm::Value *AddrTyped;
John McCallc8e01702013-04-16 22:48:15 +00004940 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka37715282012-01-23 23:59:52 +00004941 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004942
4943 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka37715282012-01-23 23:59:52 +00004944 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
4945 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
4946 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
4947 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004948 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
4949 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
4950 }
4951 else
4952 AddrTyped = Builder.CreateBitCast(Addr, PTy);
4953
4954 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka37715282012-01-23 23:59:52 +00004955 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004956 uint64_t Offset =
4957 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
4958 llvm::Value *NextAddr =
Akira Hatanaka37715282012-01-23 23:59:52 +00004959 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004960 "ap.next");
4961 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4962
4963 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004964}
4965
John McCall943fae92010-05-27 06:19:26 +00004966bool
4967MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4968 llvm::Value *Address) const {
4969 // This information comes from gcc's implementation, which seems to
4970 // as canonical as it gets.
4971
John McCall943fae92010-05-27 06:19:26 +00004972 // Everything on MIPS is 4 bytes. Double-precision FP registers
4973 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004974 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00004975
4976 // 0-31 are the general purpose registers, $0 - $31.
4977 // 32-63 are the floating-point registers, $f0 - $f31.
4978 // 64 and 65 are the multiply/divide registers, $hi and $lo.
4979 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00004980 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00004981
4982 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
4983 // They are one bit wide and ignored here.
4984
4985 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
4986 // (coprocessor 1 is the FP unit)
4987 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
4988 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
4989 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004990 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00004991 return false;
4992}
4993
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004994//===----------------------------------------------------------------------===//
4995// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
4996// Currently subclassed only to implement custom OpenCL C function attribute
4997// handling.
4998//===----------------------------------------------------------------------===//
4999
5000namespace {
5001
5002class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5003public:
5004 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5005 : DefaultTargetCodeGenInfo(CGT) {}
5006
5007 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5008 CodeGen::CodeGenModule &M) const;
5009};
5010
5011void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5012 llvm::GlobalValue *GV,
5013 CodeGen::CodeGenModule &M) const {
5014 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5015 if (!FD) return;
5016
5017 llvm::Function *F = cast<llvm::Function>(GV);
5018
David Blaikiebbafb8a2012-03-11 07:00:24 +00005019 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005020 if (FD->hasAttr<OpenCLKernelAttr>()) {
5021 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005022 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005023 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5024 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005025 // Convert the reqd_work_group_size() attributes to metadata.
5026 llvm::LLVMContext &Context = F->getContext();
5027 llvm::NamedMDNode *OpenCLMetadata =
5028 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5029
5030 SmallVector<llvm::Value*, 5> Operands;
5031 Operands.push_back(F);
5032
Chris Lattnerece04092012-02-07 00:39:47 +00005033 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005034 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005035 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005036 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005037 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005038 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005039
5040 // Add a boolean constant operand for "required" (true) or "hint" (false)
5041 // for implementing the work_group_size_hint attr later. Currently
5042 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005043 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005044 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5045 }
5046 }
5047 }
5048}
5049
5050}
John McCall943fae92010-05-27 06:19:26 +00005051
Tony Linthicum76329bf2011-12-12 21:14:55 +00005052//===----------------------------------------------------------------------===//
5053// Hexagon ABI Implementation
5054//===----------------------------------------------------------------------===//
5055
5056namespace {
5057
5058class HexagonABIInfo : public ABIInfo {
5059
5060
5061public:
5062 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5063
5064private:
5065
5066 ABIArgInfo classifyReturnType(QualType RetTy) const;
5067 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5068
5069 virtual void computeInfo(CGFunctionInfo &FI) const;
5070
5071 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5072 CodeGenFunction &CGF) const;
5073};
5074
5075class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5076public:
5077 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5078 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5079
5080 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5081 return 29;
5082 }
5083};
5084
5085}
5086
5087void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5088 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5089 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5090 it != ie; ++it)
5091 it->info = classifyArgumentType(it->type);
5092}
5093
5094ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5095 if (!isAggregateTypeForABI(Ty)) {
5096 // Treat an enum type as its underlying type.
5097 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5098 Ty = EnumTy->getDecl()->getIntegerType();
5099
5100 return (Ty->isPromotableIntegerType() ?
5101 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5102 }
5103
5104 // Ignore empty records.
5105 if (isEmptyRecord(getContext(), Ty, true))
5106 return ABIArgInfo::getIgnore();
5107
Mark Lacey3825e832013-10-06 01:33:34 +00005108 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005109 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005110
5111 uint64_t Size = getContext().getTypeSize(Ty);
5112 if (Size > 64)
5113 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5114 // Pass in the smallest viable integer type.
5115 else if (Size > 32)
5116 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5117 else if (Size > 16)
5118 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5119 else if (Size > 8)
5120 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5121 else
5122 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5123}
5124
5125ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5126 if (RetTy->isVoidType())
5127 return ABIArgInfo::getIgnore();
5128
5129 // Large vector types should be returned via memory.
5130 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5131 return ABIArgInfo::getIndirect(0);
5132
5133 if (!isAggregateTypeForABI(RetTy)) {
5134 // Treat an enum type as its underlying type.
5135 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5136 RetTy = EnumTy->getDecl()->getIntegerType();
5137
5138 return (RetTy->isPromotableIntegerType() ?
5139 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5140 }
5141
5142 // Structures with either a non-trivial destructor or a non-trivial
5143 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00005144 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum76329bf2011-12-12 21:14:55 +00005145 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5146
5147 if (isEmptyRecord(getContext(), RetTy, true))
5148 return ABIArgInfo::getIgnore();
5149
5150 // Aggregates <= 8 bytes are returned in r0; other aggregates
5151 // are returned indirectly.
5152 uint64_t Size = getContext().getTypeSize(RetTy);
5153 if (Size <= 64) {
5154 // Return in the smallest viable integer type.
5155 if (Size <= 8)
5156 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5157 if (Size <= 16)
5158 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5159 if (Size <= 32)
5160 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5161 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5162 }
5163
5164 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5165}
5166
5167llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005168 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005169 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005170 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005171
5172 CGBuilderTy &Builder = CGF.Builder;
5173 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5174 "ap");
5175 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5176 llvm::Type *PTy =
5177 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5178 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5179
5180 uint64_t Offset =
5181 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5182 llvm::Value *NextAddr =
5183 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5184 "ap.next");
5185 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5186
5187 return AddrTyped;
5188}
5189
5190
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005191//===----------------------------------------------------------------------===//
5192// SPARC v9 ABI Implementation.
5193// Based on the SPARC Compliance Definition version 2.4.1.
5194//
5195// Function arguments a mapped to a nominal "parameter array" and promoted to
5196// registers depending on their type. Each argument occupies 8 or 16 bytes in
5197// the array, structs larger than 16 bytes are passed indirectly.
5198//
5199// One case requires special care:
5200//
5201// struct mixed {
5202// int i;
5203// float f;
5204// };
5205//
5206// When a struct mixed is passed by value, it only occupies 8 bytes in the
5207// parameter array, but the int is passed in an integer register, and the float
5208// is passed in a floating point register. This is represented as two arguments
5209// with the LLVM IR inreg attribute:
5210//
5211// declare void f(i32 inreg %i, float inreg %f)
5212//
5213// The code generator will only allocate 4 bytes from the parameter array for
5214// the inreg arguments. All other arguments are allocated a multiple of 8
5215// bytes.
5216//
5217namespace {
5218class SparcV9ABIInfo : public ABIInfo {
5219public:
5220 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5221
5222private:
5223 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5224 virtual void computeInfo(CGFunctionInfo &FI) const;
5225 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5226 CodeGenFunction &CGF) const;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005227
5228 // Coercion type builder for structs passed in registers. The coercion type
5229 // serves two purposes:
5230 //
5231 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5232 // in registers.
5233 // 2. Expose aligned floating point elements as first-level elements, so the
5234 // code generator knows to pass them in floating point registers.
5235 //
5236 // We also compute the InReg flag which indicates that the struct contains
5237 // aligned 32-bit floats.
5238 //
5239 struct CoerceBuilder {
5240 llvm::LLVMContext &Context;
5241 const llvm::DataLayout &DL;
5242 SmallVector<llvm::Type*, 8> Elems;
5243 uint64_t Size;
5244 bool InReg;
5245
5246 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5247 : Context(c), DL(dl), Size(0), InReg(false) {}
5248
5249 // Pad Elems with integers until Size is ToSize.
5250 void pad(uint64_t ToSize) {
5251 assert(ToSize >= Size && "Cannot remove elements");
5252 if (ToSize == Size)
5253 return;
5254
5255 // Finish the current 64-bit word.
5256 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5257 if (Aligned > Size && Aligned <= ToSize) {
5258 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5259 Size = Aligned;
5260 }
5261
5262 // Add whole 64-bit words.
5263 while (Size + 64 <= ToSize) {
5264 Elems.push_back(llvm::Type::getInt64Ty(Context));
5265 Size += 64;
5266 }
5267
5268 // Final in-word padding.
5269 if (Size < ToSize) {
5270 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5271 Size = ToSize;
5272 }
5273 }
5274
5275 // Add a floating point element at Offset.
5276 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5277 // Unaligned floats are treated as integers.
5278 if (Offset % Bits)
5279 return;
5280 // The InReg flag is only required if there are any floats < 64 bits.
5281 if (Bits < 64)
5282 InReg = true;
5283 pad(Offset);
5284 Elems.push_back(Ty);
5285 Size = Offset + Bits;
5286 }
5287
5288 // Add a struct type to the coercion type, starting at Offset (in bits).
5289 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5290 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5291 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5292 llvm::Type *ElemTy = StrTy->getElementType(i);
5293 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5294 switch (ElemTy->getTypeID()) {
5295 case llvm::Type::StructTyID:
5296 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5297 break;
5298 case llvm::Type::FloatTyID:
5299 addFloat(ElemOffset, ElemTy, 32);
5300 break;
5301 case llvm::Type::DoubleTyID:
5302 addFloat(ElemOffset, ElemTy, 64);
5303 break;
5304 case llvm::Type::FP128TyID:
5305 addFloat(ElemOffset, ElemTy, 128);
5306 break;
5307 case llvm::Type::PointerTyID:
5308 if (ElemOffset % 64 == 0) {
5309 pad(ElemOffset);
5310 Elems.push_back(ElemTy);
5311 Size += 64;
5312 }
5313 break;
5314 default:
5315 break;
5316 }
5317 }
5318 }
5319
5320 // Check if Ty is a usable substitute for the coercion type.
5321 bool isUsableType(llvm::StructType *Ty) const {
5322 if (Ty->getNumElements() != Elems.size())
5323 return false;
5324 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5325 if (Elems[i] != Ty->getElementType(i))
5326 return false;
5327 return true;
5328 }
5329
5330 // Get the coercion type as a literal struct type.
5331 llvm::Type *getType() const {
5332 if (Elems.size() == 1)
5333 return Elems.front();
5334 else
5335 return llvm::StructType::get(Context, Elems);
5336 }
5337 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005338};
5339} // end anonymous namespace
5340
5341ABIArgInfo
5342SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5343 if (Ty->isVoidType())
5344 return ABIArgInfo::getIgnore();
5345
5346 uint64_t Size = getContext().getTypeSize(Ty);
5347
5348 // Anything too big to fit in registers is passed with an explicit indirect
5349 // pointer / sret pointer.
5350 if (Size > SizeLimit)
5351 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5352
5353 // Treat an enum type as its underlying type.
5354 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5355 Ty = EnumTy->getDecl()->getIntegerType();
5356
5357 // Integer types smaller than a register are extended.
5358 if (Size < 64 && Ty->isIntegerType())
5359 return ABIArgInfo::getExtend();
5360
5361 // Other non-aggregates go in registers.
5362 if (!isAggregateTypeForABI(Ty))
5363 return ABIArgInfo::getDirect();
5364
5365 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005366 // Build a coercion type from the LLVM struct type.
5367 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5368 if (!StrTy)
5369 return ABIArgInfo::getDirect();
5370
5371 CoerceBuilder CB(getVMContext(), getDataLayout());
5372 CB.addStruct(0, StrTy);
5373 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5374
5375 // Try to use the original type for coercion.
5376 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5377
5378 if (CB.InReg)
5379 return ABIArgInfo::getDirectInReg(CoerceTy);
5380 else
5381 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005382}
5383
5384llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5385 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005386 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5387 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5388 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5389 AI.setCoerceToType(ArgTy);
5390
5391 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5392 CGBuilderTy &Builder = CGF.Builder;
5393 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5394 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5395 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5396 llvm::Value *ArgAddr;
5397 unsigned Stride;
5398
5399 switch (AI.getKind()) {
5400 case ABIArgInfo::Expand:
5401 llvm_unreachable("Unsupported ABI kind for va_arg");
5402
5403 case ABIArgInfo::Extend:
5404 Stride = 8;
5405 ArgAddr = Builder
5406 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5407 "extend");
5408 break;
5409
5410 case ABIArgInfo::Direct:
5411 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5412 ArgAddr = Addr;
5413 break;
5414
5415 case ABIArgInfo::Indirect:
5416 Stride = 8;
5417 ArgAddr = Builder.CreateBitCast(Addr,
5418 llvm::PointerType::getUnqual(ArgPtrTy),
5419 "indirect");
5420 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5421 break;
5422
5423 case ABIArgInfo::Ignore:
5424 return llvm::UndefValue::get(ArgPtrTy);
5425 }
5426
5427 // Update VAList.
5428 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5429 Builder.CreateStore(Addr, VAListAddrAsBPP);
5430
5431 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005432}
5433
5434void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5435 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5436 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5437 it != ie; ++it)
5438 it->info = classifyType(it->type, 16 * 8);
5439}
5440
5441namespace {
5442class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5443public:
5444 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5445 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
5446};
5447} // end anonymous namespace
5448
5449
Robert Lytton0e076492013-08-13 09:43:10 +00005450//===----------------------------------------------------------------------===//
5451// Xcore ABI Implementation
5452//===----------------------------------------------------------------------===//
5453namespace {
Robert Lytton7d1db152013-08-19 09:46:39 +00005454class XCoreABIInfo : public DefaultABIInfo {
5455public:
5456 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
5457 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5458 CodeGenFunction &CGF) const;
5459};
5460
Robert Lytton0e076492013-08-13 09:43:10 +00005461class XcoreTargetCodeGenInfo : public TargetCodeGenInfo {
5462public:
5463 XcoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00005464 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton0e076492013-08-13 09:43:10 +00005465};
Robert Lytton2d196952013-10-11 10:29:34 +00005466} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00005467
Robert Lytton7d1db152013-08-19 09:46:39 +00005468llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5469 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00005470 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00005471
Robert Lytton2d196952013-10-11 10:29:34 +00005472 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00005473 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5474 CGF.Int8PtrPtrTy);
5475 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00005476
Robert Lytton2d196952013-10-11 10:29:34 +00005477 // Handle the argument.
5478 ABIArgInfo AI = classifyArgumentType(Ty);
5479 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5480 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5481 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00005482 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00005483 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00005484 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00005485 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00005486 case ABIArgInfo::Expand:
5487 llvm_unreachable("Unsupported ABI kind for va_arg");
5488 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00005489 Val = llvm::UndefValue::get(ArgPtrTy);
5490 ArgSize = 0;
5491 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005492 case ABIArgInfo::Extend:
5493 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00005494 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5495 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5496 if (ArgSize < 4)
5497 ArgSize = 4;
5498 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005499 case ABIArgInfo::Indirect:
5500 llvm::Value *ArgAddr;
5501 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5502 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00005503 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5504 ArgSize = 4;
5505 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005506 }
Robert Lytton2d196952013-10-11 10:29:34 +00005507
5508 // Increment the VAList.
5509 if (ArgSize) {
5510 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
5511 Builder.CreateStore(APN, VAListAddrAsBPP);
5512 }
5513 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00005514}
Robert Lytton0e076492013-08-13 09:43:10 +00005515
5516//===----------------------------------------------------------------------===//
5517// Driver code
5518//===----------------------------------------------------------------------===//
5519
Chris Lattner2b037972010-07-29 02:01:43 +00005520const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005521 if (TheTargetCodeGenInfo)
5522 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005523
John McCallc8e01702013-04-16 22:48:15 +00005524 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00005525 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00005526 default:
Chris Lattner2b037972010-07-29 02:01:43 +00005527 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00005528
Derek Schuff09338a22012-09-06 17:37:28 +00005529 case llvm::Triple::le32:
5530 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00005531 case llvm::Triple::mips:
5532 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005533 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
5534
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00005535 case llvm::Triple::mips64:
5536 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005537 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
5538
Tim Northover9bb857a2013-01-31 12:13:10 +00005539 case llvm::Triple::aarch64:
5540 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5541
Daniel Dunbard59655c2009-09-12 00:59:49 +00005542 case llvm::Triple::arm:
5543 case llvm::Triple::thumb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005544 {
5545 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCallc8e01702013-04-16 22:48:15 +00005546 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005547 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00005548 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00005549 (CodeGenOpts.FloatABI != "soft" &&
5550 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005551 Kind = ARMABIInfo::AAPCS_VFP;
5552
Derek Schuffa2020962012-10-16 22:30:41 +00005553 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00005554 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00005555 return *(TheTargetCodeGenInfo =
5556 new NaClARMTargetCodeGenInfo(Types, Kind));
5557 default:
5558 return *(TheTargetCodeGenInfo =
5559 new ARMTargetCodeGenInfo(Types, Kind));
5560 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005561 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00005562
John McCallea8d8bb2010-03-11 00:10:12 +00005563 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00005564 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00005565 case llvm::Triple::ppc64:
Bill Schmidt25cb3492012-10-03 19:18:57 +00005566 if (Triple.isOSBinFormatELF())
5567 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5568 else
5569 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidt778d3872013-07-26 01:36:11 +00005570 case llvm::Triple::ppc64le:
5571 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5572 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallea8d8bb2010-03-11 00:10:12 +00005573
Peter Collingbournec947aae2012-05-20 23:28:41 +00005574 case llvm::Triple::nvptx:
5575 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00005576 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005577
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005578 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00005579 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00005580
Ulrich Weigand47445072013-05-06 16:26:41 +00005581 case llvm::Triple::systemz:
5582 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5583
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005584 case llvm::Triple::tce:
5585 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5586
Eli Friedman33465822011-07-08 23:31:17 +00005587 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00005588 bool IsDarwinVectorABI = Triple.isOSDarwin();
5589 bool IsSmallStructInRegABI =
5590 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5591 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005592
John McCall1fe2a8c2013-06-18 02:46:29 +00005593 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00005594 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005595 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00005596 IsDarwinVectorABI, IsSmallStructInRegABI,
5597 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005598 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00005599 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005600 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00005601 new X86_32TargetCodeGenInfo(Types,
5602 IsDarwinVectorABI, IsSmallStructInRegABI,
5603 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00005604 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005605 }
Eli Friedman33465822011-07-08 23:31:17 +00005606 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005607
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005608 case llvm::Triple::x86_64: {
John McCallc8e01702013-04-16 22:48:15 +00005609 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005610
Chris Lattner04dc9572010-08-31 16:44:54 +00005611 switch (Triple.getOS()) {
5612 case llvm::Triple::Win32:
NAKAMURA Takumi31ea2f12011-02-17 08:51:38 +00005613 case llvm::Triple::MinGW32:
Chris Lattner04dc9572010-08-31 16:44:54 +00005614 case llvm::Triple::Cygwin:
5615 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00005616 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00005617 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5618 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005619 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005620 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5621 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005622 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00005623 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00005624 case llvm::Triple::hexagon:
5625 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005626 case llvm::Triple::sparcv9:
5627 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00005628 case llvm::Triple::xcore:
5629 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types));
5630
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005631 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005632}