blob: 0d5c47686f0341f21be6ad0b51de9e9aa8ce9ae9 [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)) {
398 // Records with non trivial destructors/constructors should not be passed
399 // 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) {
812 --FreeRegs; // Non byval indirects just use one pointer.
813 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;
1310 if (Lib.size() <= 4 ||
1311 Lib.substr(Lib.size() - 4).compare_lower(".lib") != 0) {
1312 ArgStr += ".lib";
1313 }
1314 return ArgStr;
1315}
1316
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001317class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1318public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001319 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1320 bool d, bool p, bool w, unsigned RegParms)
1321 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001322
1323 void getDependentLibraryOption(llvm::StringRef Lib,
1324 llvm::SmallString<24> &Opt) const {
1325 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001326 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001327 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001328
1329 void getDetectMismatchOption(llvm::StringRef Name,
1330 llvm::StringRef Value,
1331 llvm::SmallString<32> &Opt) const {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001332 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001333 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001334};
1335
Chris Lattner04dc9572010-08-31 16:44:54 +00001336class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1337public:
1338 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1339 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1340
1341 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1342 return 7;
1343 }
1344
1345 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1346 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001347 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001348
Chris Lattner04dc9572010-08-31 16:44:54 +00001349 // 0-15 are the 16 integer registers.
1350 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001351 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001352 return false;
1353 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001354
1355 void getDependentLibraryOption(llvm::StringRef Lib,
1356 llvm::SmallString<24> &Opt) const {
1357 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001358 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001359 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001360
1361 void getDetectMismatchOption(llvm::StringRef Name,
1362 llvm::StringRef Value,
1363 llvm::SmallString<32> &Opt) const {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001364 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001365 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001366};
1367
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001368}
1369
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001370void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1371 Class &Hi) const {
1372 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1373 //
1374 // (a) If one of the classes is Memory, the whole argument is passed in
1375 // memory.
1376 //
1377 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1378 // memory.
1379 //
1380 // (c) If the size of the aggregate exceeds two eightbytes and the first
1381 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1382 // argument is passed in memory. NOTE: This is necessary to keep the
1383 // ABI working for processors that don't support the __m256 type.
1384 //
1385 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1386 //
1387 // Some of these are enforced by the merging logic. Others can arise
1388 // only with unions; for example:
1389 // union { _Complex double; unsigned; }
1390 //
1391 // Note that clauses (b) and (c) were added in 0.98.
1392 //
1393 if (Hi == Memory)
1394 Lo = Memory;
1395 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1396 Lo = Memory;
1397 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1398 Lo = Memory;
1399 if (Hi == SSEUp && Lo != SSE)
1400 Hi = SSE;
1401}
1402
Chris Lattnerd776fb12010-06-28 21:43:59 +00001403X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001404 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1405 // classified recursively so that always two fields are
1406 // considered. The resulting class is calculated according to
1407 // the classes of the fields in the eightbyte:
1408 //
1409 // (a) If both classes are equal, this is the resulting class.
1410 //
1411 // (b) If one of the classes is NO_CLASS, the resulting class is
1412 // the other class.
1413 //
1414 // (c) If one of the classes is MEMORY, the result is the MEMORY
1415 // class.
1416 //
1417 // (d) If one of the classes is INTEGER, the result is the
1418 // INTEGER.
1419 //
1420 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1421 // MEMORY is used as class.
1422 //
1423 // (f) Otherwise class SSE is used.
1424
1425 // Accum should never be memory (we should have returned) or
1426 // ComplexX87 (because this cannot be passed in a structure).
1427 assert((Accum != Memory && Accum != ComplexX87) &&
1428 "Invalid accumulated classification during merge.");
1429 if (Accum == Field || Field == NoClass)
1430 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001431 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001432 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001433 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001434 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001435 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001436 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001437 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1438 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001439 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001440 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001441}
1442
Chris Lattner5c740f12010-06-30 19:14:05 +00001443void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001444 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001445 // FIXME: This code can be simplified by introducing a simple value class for
1446 // Class pairs with appropriate constructor methods for the various
1447 // situations.
1448
1449 // FIXME: Some of the split computations are wrong; unaligned vectors
1450 // shouldn't be passed in registers for example, so there is no chance they
1451 // can straddle an eightbyte. Verify & simplify.
1452
1453 Lo = Hi = NoClass;
1454
1455 Class &Current = OffsetBase < 64 ? Lo : Hi;
1456 Current = Memory;
1457
John McCall9dd450b2009-09-21 23:43:11 +00001458 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001459 BuiltinType::Kind k = BT->getKind();
1460
1461 if (k == BuiltinType::Void) {
1462 Current = NoClass;
1463 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1464 Lo = Integer;
1465 Hi = Integer;
1466 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1467 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001468 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1469 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001470 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001471 Current = SSE;
1472 } else if (k == BuiltinType::LongDouble) {
1473 Lo = X87;
1474 Hi = X87Up;
1475 }
1476 // FIXME: _Decimal32 and _Decimal64 are SSE.
1477 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001478 return;
1479 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001480
Chris Lattnerd776fb12010-06-28 21:43:59 +00001481 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001482 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001483 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001484 return;
1485 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001486
Chris Lattnerd776fb12010-06-28 21:43:59 +00001487 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001488 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001489 return;
1490 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001491
Chris Lattnerd776fb12010-06-28 21:43:59 +00001492 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001493 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001494 Lo = Hi = Integer;
1495 else
1496 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001497 return;
1498 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001499
Chris Lattnerd776fb12010-06-28 21:43:59 +00001500 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001501 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001502 if (Size == 32) {
1503 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1504 // float> as integer.
1505 Current = Integer;
1506
1507 // If this type crosses an eightbyte boundary, it should be
1508 // split.
1509 uint64_t EB_Real = (OffsetBase) / 64;
1510 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1511 if (EB_Real != EB_Imag)
1512 Hi = Lo;
1513 } else if (Size == 64) {
1514 // gcc passes <1 x double> in memory. :(
1515 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1516 return;
1517
1518 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001519 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001520 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1521 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1522 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001523 Current = Integer;
1524 else
1525 Current = SSE;
1526
1527 // If this type crosses an eightbyte boundary, it should be
1528 // split.
1529 if (OffsetBase && OffsetBase != 64)
1530 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001531 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001532 // Arguments of 256-bits are split into four eightbyte chunks. The
1533 // least significant one belongs to class SSE and all the others to class
1534 // SSEUP. The original Lo and Hi design considers that types can't be
1535 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1536 // This design isn't correct for 256-bits, but since there're no cases
1537 // where the upper parts would need to be inspected, avoid adding
1538 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001539 //
1540 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1541 // registers if they are "named", i.e. not part of the "..." of a
1542 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001543 Lo = SSE;
1544 Hi = SSEUp;
1545 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001546 return;
1547 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001548
Chris Lattnerd776fb12010-06-28 21:43:59 +00001549 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001550 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001551
Chris Lattner2b037972010-07-29 02:01:43 +00001552 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001553 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001554 if (Size <= 64)
1555 Current = Integer;
1556 else if (Size <= 128)
1557 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001558 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001559 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001560 else if (ET == getContext().DoubleTy ||
1561 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001562 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001563 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001564 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001565 Current = ComplexX87;
1566
1567 // If this complex type crosses an eightbyte boundary then it
1568 // should be split.
1569 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001570 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001571 if (Hi == NoClass && EB_Real != EB_Imag)
1572 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001573
Chris Lattnerd776fb12010-06-28 21:43:59 +00001574 return;
1575 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001576
Chris Lattner2b037972010-07-29 02:01:43 +00001577 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001578 // Arrays are treated like structures.
1579
Chris Lattner2b037972010-07-29 02:01:43 +00001580 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001581
1582 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001583 // than four eightbytes, ..., it has class MEMORY.
1584 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001585 return;
1586
1587 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1588 // fields, it has class MEMORY.
1589 //
1590 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001591 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001592 return;
1593
1594 // Otherwise implement simplified merge. We could be smarter about
1595 // this, but it isn't worth it and would be harder to verify.
1596 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001597 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001598 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001599
1600 // The only case a 256-bit wide vector could be used is when the array
1601 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1602 // to work for sizes wider than 128, early check and fallback to memory.
1603 if (Size > 128 && EltSize != 256)
1604 return;
1605
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001606 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1607 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001608 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001609 Lo = merge(Lo, FieldLo);
1610 Hi = merge(Hi, FieldHi);
1611 if (Lo == Memory || Hi == Memory)
1612 break;
1613 }
1614
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001615 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001616 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001617 return;
1618 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001619
Chris Lattnerd776fb12010-06-28 21:43:59 +00001620 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001621 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001622
1623 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001624 // than four eightbytes, ..., it has class MEMORY.
1625 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001626 return;
1627
Anders Carlsson20759ad2009-09-16 15:53:40 +00001628 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1629 // copy constructor or a non-trivial destructor, it is passed by invisible
1630 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001631 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001632 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001633
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001634 const RecordDecl *RD = RT->getDecl();
1635
1636 // Assume variable sized types are passed in memory.
1637 if (RD->hasFlexibleArrayMember())
1638 return;
1639
Chris Lattner2b037972010-07-29 02:01:43 +00001640 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001641
1642 // Reset Lo class, this will be recomputed.
1643 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001644
1645 // If this is a C++ record, classify the bases first.
1646 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1647 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1648 e = CXXRD->bases_end(); i != e; ++i) {
1649 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1650 "Unexpected base class!");
1651 const CXXRecordDecl *Base =
1652 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1653
1654 // Classify this field.
1655 //
1656 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1657 // single eightbyte, each is classified separately. Each eightbyte gets
1658 // initialized to class NO_CLASS.
1659 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001660 uint64_t Offset =
1661 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Eli Friedman96fd2642013-06-12 00:13:45 +00001662 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001663 Lo = merge(Lo, FieldLo);
1664 Hi = merge(Hi, FieldHi);
1665 if (Lo == Memory || Hi == Memory)
1666 break;
1667 }
1668 }
1669
1670 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001671 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001672 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001673 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001674 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1675 bool BitField = i->isBitField();
1676
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001677 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1678 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001679 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001680 // The only case a 256-bit wide vector could be used is when the struct
1681 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1682 // to work for sizes wider than 128, early check and fallback to memory.
1683 //
1684 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1685 Lo = Memory;
1686 return;
1687 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001688 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001689 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001690 Lo = Memory;
1691 return;
1692 }
1693
1694 // Classify this field.
1695 //
1696 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1697 // exceeds a single eightbyte, each is classified
1698 // separately. Each eightbyte gets initialized to class
1699 // NO_CLASS.
1700 Class FieldLo, FieldHi;
1701
1702 // Bit-fields require special handling, they do not force the
1703 // structure to be passed in memory even if unaligned, and
1704 // therefore they can straddle an eightbyte.
1705 if (BitField) {
1706 // Ignore padding bit-fields.
1707 if (i->isUnnamedBitfield())
1708 continue;
1709
1710 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001711 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001712
1713 uint64_t EB_Lo = Offset / 64;
1714 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001715
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001716 if (EB_Lo) {
1717 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1718 FieldLo = NoClass;
1719 FieldHi = Integer;
1720 } else {
1721 FieldLo = Integer;
1722 FieldHi = EB_Hi ? Integer : NoClass;
1723 }
1724 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001725 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001726 Lo = merge(Lo, FieldLo);
1727 Hi = merge(Hi, FieldHi);
1728 if (Lo == Memory || Hi == Memory)
1729 break;
1730 }
1731
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001732 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001733 }
1734}
1735
Chris Lattner22a931e2010-06-29 06:01:59 +00001736ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001737 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1738 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001739 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001740 // Treat an enum type as its underlying type.
1741 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1742 Ty = EnumTy->getDecl()->getIntegerType();
1743
1744 return (Ty->isPromotableIntegerType() ?
1745 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1746 }
1747
1748 return ABIArgInfo::getIndirect(0);
1749}
1750
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001751bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1752 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1753 uint64_t Size = getContext().getTypeSize(VecTy);
1754 unsigned LargestVector = HasAVX ? 256 : 128;
1755 if (Size <= 64 || Size > LargestVector)
1756 return true;
1757 }
1758
1759 return false;
1760}
1761
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001762ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1763 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001764 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1765 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001766 //
1767 // This assumption is optimistic, as there could be free registers available
1768 // when we need to pass this argument in memory, and LLVM could try to pass
1769 // the argument in the free register. This does not seem to happen currently,
1770 // but this code would be much safer if we could mark the argument with
1771 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001772 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001773 // Treat an enum type as its underlying type.
1774 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1775 Ty = EnumTy->getDecl()->getIntegerType();
1776
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001777 return (Ty->isPromotableIntegerType() ?
1778 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001779 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001780
Mark Lacey3825e832013-10-06 01:33:34 +00001781 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001782 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001783
Chris Lattner44c2b902011-05-22 23:21:23 +00001784 // Compute the byval alignment. We specify the alignment of the byval in all
1785 // cases so that the mid-level optimizer knows the alignment of the byval.
1786 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001787
1788 // Attempt to avoid passing indirect results using byval when possible. This
1789 // is important for good codegen.
1790 //
1791 // We do this by coercing the value into a scalar type which the backend can
1792 // handle naturally (i.e., without using byval).
1793 //
1794 // For simplicity, we currently only do this when we have exhausted all of the
1795 // free integer registers. Doing this when there are free integer registers
1796 // would require more care, as we would have to ensure that the coerced value
1797 // did not claim the unused register. That would require either reording the
1798 // arguments to the function (so that any subsequent inreg values came first),
1799 // or only doing this optimization when there were no following arguments that
1800 // might be inreg.
1801 //
1802 // We currently expect it to be rare (particularly in well written code) for
1803 // arguments to be passed on the stack when there are still free integer
1804 // registers available (this would typically imply large structs being passed
1805 // by value), so this seems like a fair tradeoff for now.
1806 //
1807 // We can revisit this if the backend grows support for 'onstack' parameter
1808 // attributes. See PR12193.
1809 if (freeIntRegs == 0) {
1810 uint64_t Size = getContext().getTypeSize(Ty);
1811
1812 // If this type fits in an eightbyte, coerce it into the matching integral
1813 // type, which will end up on the stack (with alignment 8).
1814 if (Align == 8 && Size <= 64)
1815 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1816 Size));
1817 }
1818
Chris Lattner44c2b902011-05-22 23:21:23 +00001819 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001820}
1821
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001822/// GetByteVectorType - The ABI specifies that a value should be passed in an
1823/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00001824/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001825llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001826 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001827
Chris Lattner9fa15c32010-07-29 05:02:29 +00001828 // Wrapper structs that just contain vectors are passed just like vectors,
1829 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001830 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00001831 while (STy && STy->getNumElements() == 1) {
1832 IRType = STy->getElementType(0);
1833 STy = dyn_cast<llvm::StructType>(IRType);
1834 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001835
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00001836 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001837 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1838 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001839 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00001840 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00001841 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1842 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1843 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1844 EltTy->isIntegerTy(128)))
1845 return VT;
1846 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001847
Chris Lattner4200fe42010-07-29 04:56:46 +00001848 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1849}
1850
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001851/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1852/// is known to either be off the end of the specified type or being in
1853/// alignment padding. The user type specified is known to be at most 128 bits
1854/// in size, and have passed through X86_64ABIInfo::classify with a successful
1855/// classification that put one of the two halves in the INTEGER class.
1856///
1857/// It is conservatively correct to return false.
1858static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1859 unsigned EndBit, ASTContext &Context) {
1860 // If the bytes being queried are off the end of the type, there is no user
1861 // data hiding here. This handles analysis of builtins, vectors and other
1862 // types that don't contain interesting padding.
1863 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1864 if (TySize <= StartBit)
1865 return true;
1866
Chris Lattner98076a22010-07-29 07:43:55 +00001867 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1868 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1869 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1870
1871 // Check each element to see if the element overlaps with the queried range.
1872 for (unsigned i = 0; i != NumElts; ++i) {
1873 // If the element is after the span we care about, then we're done..
1874 unsigned EltOffset = i*EltSize;
1875 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001876
Chris Lattner98076a22010-07-29 07:43:55 +00001877 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1878 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1879 EndBit-EltOffset, Context))
1880 return false;
1881 }
1882 // If it overlaps no elements, then it is safe to process as padding.
1883 return true;
1884 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001885
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001886 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1887 const RecordDecl *RD = RT->getDecl();
1888 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001889
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001890 // If this is a C++ record, check the bases first.
1891 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1892 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1893 e = CXXRD->bases_end(); i != e; ++i) {
1894 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1895 "Unexpected base class!");
1896 const CXXRecordDecl *Base =
1897 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001898
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001899 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001900 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001901 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001902
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001903 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1904 if (!BitsContainNoUserData(i->getType(), BaseStart,
1905 EndBit-BaseOffset, Context))
1906 return false;
1907 }
1908 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001909
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001910 // Verify that no field has data that overlaps the region of interest. Yes
1911 // this could be sped up a lot by being smarter about queried fields,
1912 // however we're only looking at structs up to 16 bytes, so we don't care
1913 // much.
1914 unsigned idx = 0;
1915 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1916 i != e; ++i, ++idx) {
1917 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001918
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001919 // If we found a field after the region we care about, then we're done.
1920 if (FieldOffset >= EndBit) break;
1921
1922 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1923 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1924 Context))
1925 return false;
1926 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001927
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001928 // If nothing in this record overlapped the area of interest, then we're
1929 // clean.
1930 return true;
1931 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001932
Chris Lattnerc8b7b532010-07-29 07:30:00 +00001933 return false;
1934}
1935
Chris Lattnere556a712010-07-29 18:39:32 +00001936/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1937/// float member at the specified offset. For example, {int,{float}} has a
1938/// float at offset 4. It is conservatively correct for this routine to return
1939/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00001940static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001941 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00001942 // Base case if we find a float.
1943 if (IROffset == 0 && IRType->isFloatTy())
1944 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001945
Chris Lattnere556a712010-07-29 18:39:32 +00001946 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00001947 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00001948 const llvm::StructLayout *SL = TD.getStructLayout(STy);
1949 unsigned Elt = SL->getElementContainingOffset(IROffset);
1950 IROffset -= SL->getElementOffset(Elt);
1951 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1952 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001953
Chris Lattnere556a712010-07-29 18:39:32 +00001954 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00001955 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1956 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00001957 unsigned EltSize = TD.getTypeAllocSize(EltTy);
1958 IROffset -= IROffset/EltSize*EltSize;
1959 return ContainsFloatAtOffset(EltTy, IROffset, TD);
1960 }
1961
1962 return false;
1963}
1964
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001965
1966/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1967/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001968llvm::Type *X86_64ABIInfo::
1969GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001970 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00001971 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001972 // pass as float if the last 4 bytes is just padding. This happens for
1973 // structs that contain 3 floats.
1974 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1975 SourceOffset*8+64, getContext()))
1976 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001977
Chris Lattnere556a712010-07-29 18:39:32 +00001978 // We want to pass as <2 x float> if the LLVM IR type contains a float at
1979 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
1980 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00001981 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
1982 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00001983 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001984
Chris Lattner7f4b81a2010-07-29 18:13:09 +00001985 return llvm::Type::getDoubleTy(getVMContext());
1986}
1987
1988
Chris Lattner1c56d9a2010-07-29 17:40:35 +00001989/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1990/// an 8-byte GPR. This means that we either have a scalar or we are talking
1991/// about the high or low part of an up-to-16-byte struct. This routine picks
1992/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00001993/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1994/// etc).
1995///
1996/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1997/// the source type. IROffset is an offset in bytes into the LLVM IR type that
1998/// the 8-byte value references. PrefType may be null.
1999///
2000/// SourceTy is the source level type for the entire argument. SourceOffset is
2001/// an offset into this that we're processing (which is always either 0 or 8).
2002///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002003llvm::Type *X86_64ABIInfo::
2004GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002005 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002006 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2007 // returning an 8-byte unit starting with it. See if we can safely use it.
2008 if (IROffset == 0) {
2009 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002010 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2011 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002012 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002013
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002014 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2015 // goodness in the source type is just tail padding. This is allowed to
2016 // kick in for struct {double,int} on the int, but not on
2017 // struct{double,int,int} because we wouldn't return the second int. We
2018 // have to do this analysis on the source type because we can't depend on
2019 // unions being lowered a specific way etc.
2020 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002021 IRType->isIntegerTy(32) ||
2022 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2023 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2024 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002025
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002026 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2027 SourceOffset*8+64, getContext()))
2028 return IRType;
2029 }
2030 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002031
Chris Lattner2192fe52011-07-18 04:24:23 +00002032 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002033 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002034 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002035 if (IROffset < SL->getSizeInBytes()) {
2036 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2037 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002038
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002039 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2040 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002041 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002042 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002043
Chris Lattner2192fe52011-07-18 04:24:23 +00002044 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002045 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002046 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002047 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002048 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2049 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002050 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002051
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002052 // Okay, we don't have any better idea of what to pass, so we pass this in an
2053 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002054 unsigned TySizeInBytes =
2055 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002056
Chris Lattner3f763422010-07-29 17:34:39 +00002057 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002058
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002059 // It is always safe to classify this as an integer type up to i64 that
2060 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002061 return llvm::IntegerType::get(getVMContext(),
2062 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002063}
2064
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002065
2066/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2067/// be used as elements of a two register pair to pass or return, return a
2068/// first class aggregate to represent them. For example, if the low part of
2069/// a by-value argument should be passed as i32* and the high part as float,
2070/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002071static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002072GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002073 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002074 // In order to correctly satisfy the ABI, we need to the high part to start
2075 // at offset 8. If the high and low parts we inferred are both 4-byte types
2076 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2077 // the second element at offset 8. Check for this:
2078 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2079 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002080 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002081 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002082
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002083 // To handle this, we have to increase the size of the low part so that the
2084 // second element will start at an 8 byte offset. We can't increase the size
2085 // of the second element because it might make us access off the end of the
2086 // struct.
2087 if (HiStart != 8) {
2088 // There are only two sorts of types the ABI generation code can produce for
2089 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2090 // Promote these to a larger type.
2091 if (Lo->isFloatTy())
2092 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2093 else {
2094 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2095 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2096 }
2097 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002098
Chris Lattnera5f58b02011-07-09 17:41:47 +00002099 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002100
2101
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002102 // Verify that the second element is at an 8-byte offset.
2103 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2104 "Invalid x86-64 argument pair!");
2105 return Result;
2106}
2107
Chris Lattner31faff52010-07-28 23:06:14 +00002108ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002109classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002110 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2111 // classification algorithm.
2112 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002113 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002114
2115 // Check some invariants.
2116 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002117 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2118
Chris Lattnera5f58b02011-07-09 17:41:47 +00002119 llvm::Type *ResType = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002120 switch (Lo) {
2121 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002122 if (Hi == NoClass)
2123 return ABIArgInfo::getIgnore();
2124 // If the low part is just padding, it takes no register, leave ResType
2125 // null.
2126 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2127 "Unknown missing lo part");
2128 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002129
2130 case SSEUp:
2131 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002132 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002133
2134 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2135 // hidden argument.
2136 case Memory:
2137 return getIndirectReturnResult(RetTy);
2138
2139 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2140 // available register of the sequence %rax, %rdx is used.
2141 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002142 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002143
Chris Lattner1f3a0632010-07-29 21:42:50 +00002144 // If we have a sign or zero extended integer, make sure to return Extend
2145 // so that the parameter gets the right LLVM IR attributes.
2146 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2147 // Treat an enum type as its underlying type.
2148 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2149 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002150
Chris Lattner1f3a0632010-07-29 21:42:50 +00002151 if (RetTy->isIntegralOrEnumerationType() &&
2152 RetTy->isPromotableIntegerType())
2153 return ABIArgInfo::getExtend();
2154 }
Chris Lattner31faff52010-07-28 23:06:14 +00002155 break;
2156
2157 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2158 // available SSE register of the sequence %xmm0, %xmm1 is used.
2159 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002160 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002161 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002162
2163 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2164 // returned on the X87 stack in %st0 as 80-bit x87 number.
2165 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002166 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002167 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002168
2169 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2170 // part of the value is returned in %st0 and the imaginary part in
2171 // %st1.
2172 case ComplexX87:
2173 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002174 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002175 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002176 NULL);
2177 break;
2178 }
2179
Chris Lattnera5f58b02011-07-09 17:41:47 +00002180 llvm::Type *HighPart = 0;
Chris Lattner31faff52010-07-28 23:06:14 +00002181 switch (Hi) {
2182 // Memory was handled previously and X87 should
2183 // never occur as a hi class.
2184 case Memory:
2185 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002186 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002187
2188 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002189 case NoClass:
2190 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002191
Chris Lattner52b3c132010-09-01 00:20:33 +00002192 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002193 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002194 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2195 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002196 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002197 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002198 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002199 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2200 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002201 break;
2202
2203 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002204 // is passed in the next available eightbyte chunk if the last used
2205 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002206 //
Chris Lattner57540c52011-04-15 05:22:18 +00002207 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002208 case SSEUp:
2209 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002210 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002211 break;
2212
2213 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2214 // returned together with the previous X87 value in %st0.
2215 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002216 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002217 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002218 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002219 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002220 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002221 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002222 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2223 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002224 }
Chris Lattner31faff52010-07-28 23:06:14 +00002225 break;
2226 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002227
Chris Lattner52b3c132010-09-01 00:20:33 +00002228 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002229 // known to pass in the high eightbyte of the result. We do this by forming a
2230 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002231 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002232 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002233
Chris Lattner1f3a0632010-07-29 21:42:50 +00002234 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002235}
2236
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002237ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002238 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2239 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002240 const
2241{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002242 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002243 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002244
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002245 // Check some invariants.
2246 // FIXME: Enforce these by construction.
2247 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002248 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2249
2250 neededInt = 0;
2251 neededSSE = 0;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002252 llvm::Type *ResType = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002253 switch (Lo) {
2254 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002255 if (Hi == NoClass)
2256 return ABIArgInfo::getIgnore();
2257 // If the low part is just padding, it takes no register, leave ResType
2258 // null.
2259 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2260 "Unknown missing lo part");
2261 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002262
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002263 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2264 // on the stack.
2265 case Memory:
2266
2267 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2268 // COMPLEX_X87, it is passed in memory.
2269 case X87:
2270 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002271 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002272 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002273 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002274
2275 case SSEUp:
2276 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002277 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002278
2279 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2280 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2281 // and %r9 is used.
2282 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002283 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002284
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002285 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002286 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002287
2288 // If we have a sign or zero extended integer, make sure to return Extend
2289 // so that the parameter gets the right LLVM IR attributes.
2290 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2291 // Treat an enum type as its underlying type.
2292 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2293 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002294
Chris Lattner1f3a0632010-07-29 21:42:50 +00002295 if (Ty->isIntegralOrEnumerationType() &&
2296 Ty->isPromotableIntegerType())
2297 return ABIArgInfo::getExtend();
2298 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002299
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002300 break;
2301
2302 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2303 // available SSE register is used, the registers are taken in the
2304 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002305 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002306 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002307 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002308 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002309 break;
2310 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002311 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002312
Chris Lattnera5f58b02011-07-09 17:41:47 +00002313 llvm::Type *HighPart = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002314 switch (Hi) {
2315 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002316 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002317 // which is passed in memory.
2318 case Memory:
2319 case X87:
2320 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002321 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002322
2323 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002324
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002325 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002326 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002327 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002328 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002329
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002330 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2331 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002332 break;
2333
2334 // X87Up generally doesn't occur here (long double is passed in
2335 // memory), except in situations involving unions.
2336 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002337 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002338 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002339
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002340 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2341 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002342
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002343 ++neededSSE;
2344 break;
2345
2346 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2347 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002348 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002349 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002350 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002351 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002352 break;
2353 }
2354
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002355 // If a high part was specified, merge it together with the low part. It is
2356 // known to pass in the high eightbyte of the result. We do this by forming a
2357 // first class struct aggregate with the high and low part: {low, high}
2358 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002359 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002360
Chris Lattner1f3a0632010-07-29 21:42:50 +00002361 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002362}
2363
Chris Lattner22326a12010-07-29 02:31:05 +00002364void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002365
Chris Lattner458b2aa2010-07-29 02:16:43 +00002366 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002367
2368 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002369 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002370
2371 // If the return value is indirect, then the hidden argument is consuming one
2372 // integer register.
2373 if (FI.getReturnInfo().isIndirect())
2374 --freeIntRegs;
2375
Eli Friedman96fd2642013-06-12 00:13:45 +00002376 bool isVariadic = FI.isVariadic();
2377 unsigned numRequiredArgs = 0;
2378 if (isVariadic)
2379 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2380
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002381 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2382 // get assigned (in left-to-right order) for passing as follows...
2383 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2384 it != ie; ++it) {
Eli Friedman96fd2642013-06-12 00:13:45 +00002385 bool isNamedArg = true;
2386 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002387 isNamedArg = (it - FI.arg_begin()) <
2388 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002389
Bill Wendling9987c0e2010-10-18 23:51:38 +00002390 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002391 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002392 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002393
2394 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2395 // eightbyte of an argument, the whole argument is passed on the
2396 // stack. If registers have already been assigned for some
2397 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002398 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002399 freeIntRegs -= neededInt;
2400 freeSSERegs -= neededSSE;
2401 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002402 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002403 }
2404 }
2405}
2406
2407static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2408 QualType Ty,
2409 CodeGenFunction &CGF) {
2410 llvm::Value *overflow_arg_area_p =
2411 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2412 llvm::Value *overflow_arg_area =
2413 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2414
2415 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2416 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002417 // It isn't stated explicitly in the standard, but in practice we use
2418 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002419 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2420 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002421 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002422 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002423 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002424 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2425 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002426 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002427 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002428 overflow_arg_area =
2429 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2430 overflow_arg_area->getType(),
2431 "overflow_arg_area.align");
2432 }
2433
2434 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002435 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002436 llvm::Value *Res =
2437 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002438 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002439
2440 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2441 // l->overflow_arg_area + sizeof(type).
2442 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2443 // an 8 byte boundary.
2444
2445 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002446 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002447 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002448 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2449 "overflow_arg_area.next");
2450 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2451
2452 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2453 return Res;
2454}
2455
2456llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2457 CodeGenFunction &CGF) const {
2458 // Assume that va_list type is correct; should be pointer to LLVM type:
2459 // struct {
2460 // i32 gp_offset;
2461 // i32 fp_offset;
2462 // i8* overflow_arg_area;
2463 // i8* reg_save_area;
2464 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002465 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002466
Chris Lattner9723d6c2010-03-11 18:19:55 +00002467 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002468 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2469 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002470
2471 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2472 // in the registers. If not go to step 7.
2473 if (!neededInt && !neededSSE)
2474 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2475
2476 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2477 // general purpose registers needed to pass type and num_fp to hold
2478 // the number of floating point registers needed.
2479
2480 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2481 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2482 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2483 //
2484 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2485 // register save space).
2486
2487 llvm::Value *InRegs = 0;
2488 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2489 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2490 if (neededInt) {
2491 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2492 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002493 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2494 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002495 }
2496
2497 if (neededSSE) {
2498 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2499 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2500 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002501 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2502 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002503 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2504 }
2505
2506 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2507 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2508 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2509 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2510
2511 // Emit code to load the value if it was passed in registers.
2512
2513 CGF.EmitBlock(InRegBlock);
2514
2515 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2516 // an offset of l->gp_offset and/or l->fp_offset. This may require
2517 // copying to a temporary location in case the parameter is passed
2518 // in different register classes or requires an alignment greater
2519 // than 8 for general purpose registers and 16 for XMM registers.
2520 //
2521 // FIXME: This really results in shameful code when we end up needing to
2522 // collect arguments from different places; often what should result in a
2523 // simple assembling of a structure from scattered addresses has many more
2524 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002525 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002526 llvm::Value *RegAddr =
2527 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2528 "reg_save_area");
2529 if (neededInt && neededSSE) {
2530 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002531 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002532 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002533 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2534 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002535 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002536 llvm::Type *TyLo = ST->getElementType(0);
2537 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002538 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002539 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002540 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2541 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002542 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2543 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sands998f9d92010-02-15 16:14:01 +00002544 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2545 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002546 llvm::Value *V =
2547 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2548 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2549 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2550 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2551
Owen Anderson170229f2009-07-14 23:10:40 +00002552 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002553 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002554 } else if (neededInt) {
2555 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2556 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002557 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002558
2559 // Copy to a temporary if necessary to ensure the appropriate alignment.
2560 std::pair<CharUnits, CharUnits> SizeAlign =
2561 CGF.getContext().getTypeInfoInChars(Ty);
2562 uint64_t TySize = SizeAlign.first.getQuantity();
2563 unsigned TyAlign = SizeAlign.second.getQuantity();
2564 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002565 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2566 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2567 RegAddr = Tmp;
2568 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002569 } else if (neededSSE == 1) {
2570 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2571 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2572 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002573 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002574 assert(neededSSE == 2 && "Invalid number of needed registers!");
2575 // SSE registers are spaced 16 bytes apart in the register save
2576 // area, we need to collect the two eightbytes together.
2577 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002578 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002579 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002580 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002581 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002582 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2583 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2584 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002585 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2586 DblPtrTy));
2587 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2588 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2589 DblPtrTy));
2590 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2591 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2592 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002593 }
2594
2595 // AMD64-ABI 3.5.7p5: Step 5. Set:
2596 // l->gp_offset = l->gp_offset + num_gp * 8
2597 // l->fp_offset = l->fp_offset + num_fp * 16.
2598 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002599 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002600 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2601 gp_offset_p);
2602 }
2603 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002604 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002605 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2606 fp_offset_p);
2607 }
2608 CGF.EmitBranch(ContBlock);
2609
2610 // Emit code to load the value if it was passed in memory.
2611
2612 CGF.EmitBlock(InMemBlock);
2613 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2614
2615 // Return the appropriate result.
2616
2617 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002618 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002619 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002620 ResAddr->addIncoming(RegAddr, InRegBlock);
2621 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002622 return ResAddr;
2623}
2624
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002625ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002626
2627 if (Ty->isVoidType())
2628 return ABIArgInfo::getIgnore();
2629
2630 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2631 Ty = EnumTy->getDecl()->getIntegerType();
2632
2633 uint64_t Size = getContext().getTypeSize(Ty);
2634
2635 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002636 if (IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002637 if (isRecordReturnIndirect(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002638 return ABIArgInfo::getIndirect(0, false);
2639 } else {
Mark Lacey3825e832013-10-06 01:33:34 +00002640 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002641 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2642 }
2643
2644 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002645 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2646
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002647 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCallc8e01702013-04-16 22:48:15 +00002648 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002649 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2650 Size));
2651
2652 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2653 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2654 if (Size <= 64 &&
NAKAMURA Takumie03c6032011-01-19 00:11:33 +00002655 (Size & (Size - 1)) == 0)
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002656 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2657 Size));
2658
2659 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2660 }
2661
2662 if (Ty->isPromotableIntegerType())
2663 return ABIArgInfo::getExtend();
2664
2665 return ABIArgInfo::getDirect();
2666}
2667
2668void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2669
2670 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002671 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002672
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002673 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2674 it != ie; ++it)
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002675 it->info = classify(it->type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002676}
2677
Chris Lattner04dc9572010-08-31 16:44:54 +00002678llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2679 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002680 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002681
Chris Lattner04dc9572010-08-31 16:44:54 +00002682 CGBuilderTy &Builder = CGF.Builder;
2683 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2684 "ap");
2685 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2686 llvm::Type *PTy =
2687 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2688 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2689
2690 uint64_t Offset =
2691 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2692 llvm::Value *NextAddr =
2693 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2694 "ap.next");
2695 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2696
2697 return AddrTyped;
2698}
Chris Lattner0cf24192010-06-28 20:05:43 +00002699
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002700namespace {
2701
Derek Schuffa2020962012-10-16 22:30:41 +00002702class NaClX86_64ABIInfo : public ABIInfo {
2703 public:
2704 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2705 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2706 virtual void computeInfo(CGFunctionInfo &FI) const;
2707 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2708 CodeGenFunction &CGF) const;
2709 private:
2710 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2711 X86_64ABIInfo NInfo; // Used for everything else.
2712};
2713
2714class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2715 public:
2716 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2717 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2718};
2719
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002720}
2721
Derek Schuffa2020962012-10-16 22:30:41 +00002722void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2723 if (FI.getASTCallingConvention() == CC_PnaclCall)
2724 PInfo.computeInfo(FI);
2725 else
2726 NInfo.computeInfo(FI);
2727}
2728
2729llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2730 CodeGenFunction &CGF) const {
2731 // Always use the native convention; calling pnacl-style varargs functions
2732 // is unuspported.
2733 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2734}
2735
2736
John McCallea8d8bb2010-03-11 00:10:12 +00002737// PowerPC-32
2738
2739namespace {
2740class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2741public:
Chris Lattner2b037972010-07-29 02:01:43 +00002742 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002743
John McCallea8d8bb2010-03-11 00:10:12 +00002744 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2745 // This is recovered from gcc output.
2746 return 1; // r1 is the dedicated stack pointer
2747 }
2748
2749 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002750 llvm::Value *Address) const;
John McCallea8d8bb2010-03-11 00:10:12 +00002751};
2752
2753}
2754
2755bool
2756PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2757 llvm::Value *Address) const {
2758 // This is calculated from the LLVM and GCC tables and verified
2759 // against gcc output. AFAIK all ABIs use the same encoding.
2760
2761 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002762
Chris Lattnerece04092012-02-07 00:39:47 +00002763 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002764 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2765 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2766 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2767
2768 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002769 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002770
2771 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002772 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00002773
2774 // 64-76 are various 4-byte special-purpose registers:
2775 // 64: mq
2776 // 65: lr
2777 // 66: ctr
2778 // 67: ap
2779 // 68-75 cr0-7
2780 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00002781 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002782
2783 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002784 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002785
2786 // 109: vrsave
2787 // 110: vscr
2788 // 111: spe_acc
2789 // 112: spefscr
2790 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002791 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002792
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002793 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002794}
2795
Roman Divackyd966e722012-05-09 18:22:46 +00002796// PowerPC-64
2797
2798namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00002799/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2800class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2801
2802public:
2803 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2804
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002805 bool isPromotableTypeForABI(QualType Ty) const;
2806
2807 ABIArgInfo classifyReturnType(QualType RetTy) const;
2808 ABIArgInfo classifyArgumentType(QualType Ty) const;
2809
Bill Schmidt84d37792012-10-12 19:26:17 +00002810 // TODO: We can add more logic to computeInfo to improve performance.
2811 // Example: For aggregate arguments that fit in a register, we could
2812 // use getDirectInReg (as is done below for structs containing a single
2813 // floating-point value) to avoid pushing them to memory on function
2814 // entry. This would require changing the logic in PPCISelLowering
2815 // when lowering the parameters in the caller and args in the callee.
2816 virtual void computeInfo(CGFunctionInfo &FI) const {
2817 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2818 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2819 it != ie; ++it) {
2820 // We rely on the default argument classification for the most part.
2821 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00002822 // or vector item must be passed in a register if one is available.
Bill Schmidt84d37792012-10-12 19:26:17 +00002823 const Type *T = isSingleElementStruct(it->type, getContext());
2824 if (T) {
2825 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidt179afae2013-07-23 22:15:57 +00002826 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00002827 QualType QT(T, 0);
2828 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2829 continue;
2830 }
2831 }
2832 it->info = classifyArgumentType(it->type);
2833 }
2834 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00002835
2836 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2837 QualType Ty,
2838 CodeGenFunction &CGF) const;
2839};
2840
2841class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2842public:
2843 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2844 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2845
2846 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2847 // This is recovered from gcc output.
2848 return 1; // r1 is the dedicated stack pointer
2849 }
2850
2851 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2852 llvm::Value *Address) const;
2853};
2854
Roman Divackyd966e722012-05-09 18:22:46 +00002855class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2856public:
2857 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2858
2859 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2860 // This is recovered from gcc output.
2861 return 1; // r1 is the dedicated stack pointer
2862 }
2863
2864 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2865 llvm::Value *Address) const;
2866};
2867
2868}
2869
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002870// Return true if the ABI requires Ty to be passed sign- or zero-
2871// extended to 64 bits.
2872bool
2873PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2874 // Treat an enum type as its underlying type.
2875 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2876 Ty = EnumTy->getDecl()->getIntegerType();
2877
2878 // Promotable integer types are required to be promoted by the ABI.
2879 if (Ty->isPromotableIntegerType())
2880 return true;
2881
2882 // In addition to the usual promotable integer types, we also need to
2883 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2884 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2885 switch (BT->getKind()) {
2886 case BuiltinType::Int:
2887 case BuiltinType::UInt:
2888 return true;
2889 default:
2890 break;
2891 }
2892
2893 return false;
2894}
2895
2896ABIArgInfo
2897PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00002898 if (Ty->isAnyComplexType())
2899 return ABIArgInfo::getDirect();
2900
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002901 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00002902 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002903 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002904
2905 return ABIArgInfo::getIndirect(0);
2906 }
2907
2908 return (isPromotableTypeForABI(Ty) ?
2909 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2910}
2911
2912ABIArgInfo
2913PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
2914 if (RetTy->isVoidType())
2915 return ABIArgInfo::getIgnore();
2916
Bill Schmidta3d121c2012-12-17 04:20:17 +00002917 if (RetTy->isAnyComplexType())
2918 return ABIArgInfo::getDirect();
2919
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00002920 if (isAggregateTypeForABI(RetTy))
2921 return ABIArgInfo::getIndirect(0);
2922
2923 return (isPromotableTypeForABI(RetTy) ?
2924 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2925}
2926
Bill Schmidt25cb3492012-10-03 19:18:57 +00002927// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
2928llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2929 QualType Ty,
2930 CodeGenFunction &CGF) const {
2931 llvm::Type *BP = CGF.Int8PtrTy;
2932 llvm::Type *BPP = CGF.Int8PtrPtrTy;
2933
2934 CGBuilderTy &Builder = CGF.Builder;
2935 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2936 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2937
Bill Schmidt924c4782013-01-14 17:45:36 +00002938 // Update the va_list pointer. The pointer should be bumped by the
2939 // size of the object. We can trust getTypeSize() except for a complex
2940 // type whose base type is smaller than a doubleword. For these, the
2941 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00002942 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00002943 QualType BaseTy;
2944 unsigned CplxBaseSize = 0;
2945
2946 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
2947 BaseTy = CTy->getElementType();
2948 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
2949 if (CplxBaseSize < 8)
2950 SizeInBytes = 16;
2951 }
2952
Bill Schmidt25cb3492012-10-03 19:18:57 +00002953 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
2954 llvm::Value *NextAddr =
2955 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
2956 "ap.next");
2957 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2958
Bill Schmidt924c4782013-01-14 17:45:36 +00002959 // If we have a complex type and the base type is smaller than 8 bytes,
2960 // the ABI calls for the real and imaginary parts to be right-adjusted
2961 // in separate doublewords. However, Clang expects us to produce a
2962 // pointer to a structure with the two parts packed tightly. So generate
2963 // loads of the real and imaginary parts relative to the va_list pointer,
2964 // and store them to a temporary structure.
2965 if (CplxBaseSize && CplxBaseSize < 8) {
2966 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2967 llvm::Value *ImagAddr = RealAddr;
2968 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
2969 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
2970 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
2971 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
2972 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
2973 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
2974 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
2975 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
2976 "vacplx");
2977 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
2978 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
2979 Builder.CreateStore(Real, RealPtr, false);
2980 Builder.CreateStore(Imag, ImagPtr, false);
2981 return Ptr;
2982 }
2983
Bill Schmidt25cb3492012-10-03 19:18:57 +00002984 // If the argument is smaller than 8 bytes, it is right-adjusted in
2985 // its doubleword slot. Adjust the pointer to pick it up from the
2986 // correct offset.
2987 if (SizeInBytes < 8) {
2988 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2989 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
2990 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2991 }
2992
2993 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2994 return Builder.CreateBitCast(Addr, PTy);
2995}
2996
2997static bool
2998PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2999 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003000 // This is calculated from the LLVM and GCC tables and verified
3001 // against gcc output. AFAIK all ABIs use the same encoding.
3002
3003 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3004
3005 llvm::IntegerType *i8 = CGF.Int8Ty;
3006 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3007 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3008 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3009
3010 // 0-31: r0-31, the 8-byte general-purpose registers
3011 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3012
3013 // 32-63: fp0-31, the 8-byte floating-point registers
3014 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3015
3016 // 64-76 are various 4-byte special-purpose registers:
3017 // 64: mq
3018 // 65: lr
3019 // 66: ctr
3020 // 67: ap
3021 // 68-75 cr0-7
3022 // 76: xer
3023 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3024
3025 // 77-108: v0-31, the 16-byte vector registers
3026 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3027
3028 // 109: vrsave
3029 // 110: vscr
3030 // 111: spe_acc
3031 // 112: spefscr
3032 // 113: sfp
3033 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3034
3035 return false;
3036}
John McCallea8d8bb2010-03-11 00:10:12 +00003037
Bill Schmidt25cb3492012-10-03 19:18:57 +00003038bool
3039PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3040 CodeGen::CodeGenFunction &CGF,
3041 llvm::Value *Address) const {
3042
3043 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3044}
3045
3046bool
3047PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3048 llvm::Value *Address) const {
3049
3050 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3051}
3052
Chris Lattner0cf24192010-06-28 20:05:43 +00003053//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003054// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00003055//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00003056
3057namespace {
3058
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003059class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003060public:
3061 enum ABIKind {
3062 APCS = 0,
3063 AAPCS = 1,
3064 AAPCS_VFP
3065 };
3066
3067private:
3068 ABIKind Kind;
3069
3070public:
John McCall882987f2013-02-28 19:01:20 +00003071 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
3072 setRuntimeCC();
3073 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003074
John McCall3480ef22011-08-30 01:42:09 +00003075 bool isEABI() const {
John McCallc8e01702013-04-16 22:48:15 +00003076 StringRef Env = getTarget().getTriple().getEnvironmentName();
Logan Chienc6fd8202012-09-02 09:30:11 +00003077 return (Env == "gnueabi" || Env == "eabi" ||
3078 Env == "android" || Env == "androideabi");
John McCall3480ef22011-08-30 01:42:09 +00003079 }
3080
Daniel Dunbar020daa92009-09-12 01:00:39 +00003081 ABIKind getABIKind() const { return Kind; }
3082
Tim Northovera484bc02013-10-01 14:34:25 +00003083private:
Chris Lattner458b2aa2010-07-29 02:16:43 +00003084 ABIArgInfo classifyReturnType(QualType RetTy) const;
Manman Renb505d332012-10-31 19:02:26 +00003085 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs,
3086 unsigned &AllocatedVFP,
Manman Ren2a523d82012-10-30 23:21:41 +00003087 bool &IsHA) const;
Manman Renfef9e312012-10-16 19:18:39 +00003088 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003089
Chris Lattner22326a12010-07-29 02:31:05 +00003090 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003091
3092 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3093 CodeGenFunction &CGF) const;
John McCall882987f2013-02-28 19:01:20 +00003094
3095 llvm::CallingConv::ID getLLVMDefaultCC() const;
3096 llvm::CallingConv::ID getABIDefaultCC() const;
3097 void setRuntimeCC();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003098};
3099
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003100class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3101public:
Chris Lattner2b037972010-07-29 02:01:43 +00003102 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3103 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00003104
John McCall3480ef22011-08-30 01:42:09 +00003105 const ARMABIInfo &getABIInfo() const {
3106 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3107 }
3108
John McCallbeec5a02010-03-06 00:35:14 +00003109 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3110 return 13;
3111 }
Roman Divackyc1617352011-05-18 19:36:54 +00003112
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003113 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
John McCall31168b02011-06-15 23:02:42 +00003114 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3115 }
3116
Roman Divackyc1617352011-05-18 19:36:54 +00003117 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3118 llvm::Value *Address) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003119 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00003120
3121 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00003122 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00003123 return false;
3124 }
John McCall3480ef22011-08-30 01:42:09 +00003125
3126 unsigned getSizeOfUnwindException() const {
3127 if (getABIInfo().isEABI()) return 88;
3128 return TargetCodeGenInfo::getSizeOfUnwindException();
3129 }
Tim Northovera484bc02013-10-01 14:34:25 +00003130
3131 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3132 CodeGen::CodeGenModule &CGM) const {
3133 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3134 if (!FD)
3135 return;
3136
3137 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3138 if (!Attr)
3139 return;
3140
3141 const char *Kind;
3142 switch (Attr->getInterrupt()) {
3143 case ARMInterruptAttr::Generic: Kind = ""; break;
3144 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3145 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3146 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3147 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3148 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3149 }
3150
3151 llvm::Function *Fn = cast<llvm::Function>(GV);
3152
3153 Fn->addFnAttr("interrupt", Kind);
3154
3155 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3156 return;
3157
3158 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3159 // however this is not necessarily true on taking any interrupt. Instruct
3160 // the backend to perform a realignment as part of the function prologue.
3161 llvm::AttrBuilder B;
3162 B.addStackAlignmentAttr(8);
3163 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3164 llvm::AttributeSet::get(CGM.getLLVMContext(),
3165 llvm::AttributeSet::FunctionIndex,
3166 B));
3167 }
3168
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00003169};
3170
Daniel Dunbard59655c2009-09-12 00:59:49 +00003171}
3172
Chris Lattner22326a12010-07-29 02:31:05 +00003173void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00003174 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00003175 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00003176 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3177 // VFP registers of the appropriate type unallocated then the argument is
3178 // allocated to the lowest-numbered sequence of such registers.
3179 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3180 // unallocated are marked as unavailable.
3181 unsigned AllocatedVFP = 0;
Manman Renb505d332012-10-31 19:02:26 +00003182 int VFPRegs[16] = { 0 };
Chris Lattner458b2aa2010-07-29 02:16:43 +00003183 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003184 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Manman Ren2a523d82012-10-30 23:21:41 +00003185 it != ie; ++it) {
3186 unsigned PreAllocation = AllocatedVFP;
3187 bool IsHA = false;
3188 // 6.1.2.3 There is one VFP co-processor register class using registers
3189 // s0-s15 (d0-d7) for passing arguments.
3190 const unsigned NumVFPs = 16;
Manman Renb505d332012-10-31 19:02:26 +00003191 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA);
Manman Ren2a523d82012-10-30 23:21:41 +00003192 // If we do not have enough VFP registers for the HA, any VFP registers
3193 // that are unallocated are marked as unavailable. To achieve this, we add
3194 // padding of (NumVFPs - PreAllocation) floats.
3195 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3196 llvm::Type *PaddingTy = llvm::ArrayType::get(
3197 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3198 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3199 }
3200 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00003201
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003202 // Always honor user-specified calling convention.
3203 if (FI.getCallingConvention() != llvm::CallingConv::C)
3204 return;
3205
John McCall882987f2013-02-28 19:01:20 +00003206 llvm::CallingConv::ID cc = getRuntimeCC();
3207 if (cc != llvm::CallingConv::C)
3208 FI.setEffectiveCallingConvention(cc);
3209}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00003210
John McCall882987f2013-02-28 19:01:20 +00003211/// Return the default calling convention that LLVM will use.
3212llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3213 // The default calling convention that LLVM will infer.
John McCallc8e01702013-04-16 22:48:15 +00003214 if (getTarget().getTriple().getEnvironmentName()=="gnueabihf")
John McCall882987f2013-02-28 19:01:20 +00003215 return llvm::CallingConv::ARM_AAPCS_VFP;
3216 else if (isEABI())
3217 return llvm::CallingConv::ARM_AAPCS;
3218 else
3219 return llvm::CallingConv::ARM_APCS;
3220}
3221
3222/// Return the calling convention that our ABI would like us to use
3223/// as the C calling convention.
3224llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00003225 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00003226 case APCS: return llvm::CallingConv::ARM_APCS;
3227 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3228 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00003229 }
John McCall882987f2013-02-28 19:01:20 +00003230 llvm_unreachable("bad ABI kind");
3231}
3232
3233void ARMABIInfo::setRuntimeCC() {
3234 assert(getRuntimeCC() == llvm::CallingConv::C);
3235
3236 // Don't muddy up the IR with a ton of explicit annotations if
3237 // they'd just match what LLVM will infer from the triple.
3238 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3239 if (abiCC != getLLVMDefaultCC())
3240 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003241}
3242
Bob Wilsone826a2a2011-08-03 05:58:22 +00003243/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3244/// aggregate. If HAMembers is non-null, the number of base elements
3245/// contained in the type is returned through it; this is used for the
3246/// recursive calls that check aggregate component types.
3247static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3248 ASTContext &Context,
3249 uint64_t *HAMembers = 0) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003250 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003251 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3252 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3253 return false;
3254 Members *= AT->getSize().getZExtValue();
3255 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3256 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003257 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00003258 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003259
Bob Wilsone826a2a2011-08-03 05:58:22 +00003260 Members = 0;
3261 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3262 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003263 const FieldDecl *FD = *i;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003264 uint64_t FldMembers;
3265 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3266 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003267
3268 Members = (RD->isUnion() ?
3269 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003270 }
3271 } else {
3272 Members = 1;
3273 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3274 Members = 2;
3275 Ty = CT->getElementType();
3276 }
3277
3278 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3279 // double, or 64-bit or 128-bit vectors.
3280 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3281 if (BT->getKind() != BuiltinType::Float &&
Tim Northovereb752d42012-07-20 22:29:29 +00003282 BT->getKind() != BuiltinType::Double &&
3283 BT->getKind() != BuiltinType::LongDouble)
Bob Wilsone826a2a2011-08-03 05:58:22 +00003284 return false;
3285 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3286 unsigned VecSize = Context.getTypeSize(VT);
3287 if (VecSize != 64 && VecSize != 128)
3288 return false;
3289 } else {
3290 return false;
3291 }
3292
3293 // The base type must be the same for all members. Vector types of the
3294 // same total size are treated as being equivalent here.
3295 const Type *TyPtr = Ty.getTypePtr();
3296 if (!Base)
3297 Base = TyPtr;
3298 if (Base != TyPtr &&
3299 (!Base->isVectorType() || !TyPtr->isVectorType() ||
3300 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
3301 return false;
3302 }
3303
3304 // Homogeneous Aggregates can have at most 4 members of the base type.
3305 if (HAMembers)
3306 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003307
3308 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00003309}
3310
Manman Renb505d332012-10-31 19:02:26 +00003311/// markAllocatedVFPs - update VFPRegs according to the alignment and
3312/// number of VFP registers (unit is S register) requested.
3313static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP,
3314 unsigned Alignment,
3315 unsigned NumRequired) {
3316 // Early Exit.
3317 if (AllocatedVFP >= 16)
3318 return;
3319 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3320 // VFP registers of the appropriate type unallocated then the argument is
3321 // allocated to the lowest-numbered sequence of such registers.
3322 for (unsigned I = 0; I < 16; I += Alignment) {
3323 bool FoundSlot = true;
3324 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3325 if (J >= 16 || VFPRegs[J]) {
3326 FoundSlot = false;
3327 break;
3328 }
3329 if (FoundSlot) {
3330 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3331 VFPRegs[J] = 1;
3332 AllocatedVFP += NumRequired;
3333 return;
3334 }
3335 }
3336 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3337 // unallocated are marked as unavailable.
3338 for (unsigned I = 0; I < 16; I++)
3339 VFPRegs[I] = 1;
3340 AllocatedVFP = 17; // We do not have enough VFP registers.
3341}
3342
3343ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
3344 unsigned &AllocatedVFP,
Manman Ren2a523d82012-10-30 23:21:41 +00003345 bool &IsHA) const {
3346 // We update number of allocated VFPs according to
3347 // 6.1.2.1 The following argument types are VFP CPRCs:
3348 // A single-precision floating-point type (including promoted
3349 // half-precision types); A double-precision floating-point type;
3350 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3351 // with a Base Type of a single- or double-precision floating-point type,
3352 // 64-bit containerized vectors or 128-bit containerized vectors with one
3353 // to four Elements.
3354
Manman Renfef9e312012-10-16 19:18:39 +00003355 // Handle illegal vector types here.
3356 if (isIllegalVectorType(Ty)) {
3357 uint64_t Size = getContext().getTypeSize(Ty);
3358 if (Size <= 32) {
3359 llvm::Type *ResType =
3360 llvm::Type::getInt32Ty(getVMContext());
3361 return ABIArgInfo::getDirect(ResType);
3362 }
3363 if (Size == 64) {
3364 llvm::Type *ResType = llvm::VectorType::get(
3365 llvm::Type::getInt32Ty(getVMContext()), 2);
Manman Renb505d332012-10-31 19:02:26 +00003366 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Renfef9e312012-10-16 19:18:39 +00003367 return ABIArgInfo::getDirect(ResType);
3368 }
3369 if (Size == 128) {
3370 llvm::Type *ResType = llvm::VectorType::get(
3371 llvm::Type::getInt32Ty(getVMContext()), 4);
Manman Renb505d332012-10-31 19:02:26 +00003372 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4);
Manman Renfef9e312012-10-16 19:18:39 +00003373 return ABIArgInfo::getDirect(ResType);
3374 }
3375 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3376 }
Manman Renb505d332012-10-31 19:02:26 +00003377 // Update VFPRegs for legal vector types.
Manman Ren2a523d82012-10-30 23:21:41 +00003378 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3379 uint64_t Size = getContext().getTypeSize(VT);
3380 // Size of a legal vector should be power of 2 and above 64.
Manman Renb505d332012-10-31 19:02:26 +00003381 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32);
Manman Ren2a523d82012-10-30 23:21:41 +00003382 }
Manman Renb505d332012-10-31 19:02:26 +00003383 // Update VFPRegs for floating point types.
Manman Ren2a523d82012-10-30 23:21:41 +00003384 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3385 if (BT->getKind() == BuiltinType::Half ||
3386 BT->getKind() == BuiltinType::Float)
Manman Renb505d332012-10-31 19:02:26 +00003387 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1);
Manman Ren2a523d82012-10-30 23:21:41 +00003388 if (BT->getKind() == BuiltinType::Double ||
Manman Renb505d332012-10-31 19:02:26 +00003389 BT->getKind() == BuiltinType::LongDouble)
3390 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003391 }
Manman Renfef9e312012-10-16 19:18:39 +00003392
John McCalla1dee5302010-08-22 10:59:02 +00003393 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003394 // Treat an enum type as its underlying type.
3395 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3396 Ty = EnumTy->getDecl()->getIntegerType();
3397
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003398 return (Ty->isPromotableIntegerType() ?
3399 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003400 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003401
Mark Lacey3825e832013-10-06 01:33:34 +00003402 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Tim Northover1060eae2013-06-21 22:49:34 +00003403 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3404
Daniel Dunbar09d33622009-09-14 21:54:03 +00003405 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003406 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00003407 return ABIArgInfo::getIgnore();
3408
Bob Wilsone826a2a2011-08-03 05:58:22 +00003409 if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00003410 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3411 // into VFP registers.
Bob Wilsone826a2a2011-08-03 05:58:22 +00003412 const Type *Base = 0;
Manman Ren2a523d82012-10-30 23:21:41 +00003413 uint64_t Members = 0;
3414 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003415 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00003416 // Base can be a floating-point or a vector.
3417 if (Base->isVectorType()) {
3418 // ElementSize is in number of floats.
3419 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Manman Ren77b02382012-11-06 19:05:29 +00003420 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize,
3421 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00003422 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Manman Renb505d332012-10-31 19:02:26 +00003423 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00003424 else {
3425 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3426 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Manman Renb505d332012-10-31 19:02:26 +00003427 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00003428 }
3429 IsHA = true;
Bob Wilsone826a2a2011-08-03 05:58:22 +00003430 return ABIArgInfo::getExpand();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003431 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00003432 }
3433
Manman Ren6c30e132012-08-13 21:23:55 +00003434 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00003435 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3436 // most 8-byte. We realign the indirect argument if type alignment is bigger
3437 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00003438 uint64_t ABIAlign = 4;
3439 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3440 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3441 getABIKind() == ARMABIInfo::AAPCS)
3442 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00003443 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
3444 return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00003445 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00003446 }
3447
Daniel Dunbarb34b0802010-09-23 01:54:28 +00003448 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00003449 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003450 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00003451 // FIXME: Try to match the types of the arguments more accurately where
3452 // we can.
3453 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00003454 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3455 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00003456 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00003457 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3458 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00003459 }
Stuart Hastings4b214952011-04-28 18:16:06 +00003460
Chris Lattnera5f58b02011-07-09 17:41:47 +00003461 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00003462 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastings4b214952011-04-28 18:16:06 +00003463 return ABIArgInfo::getDirect(STy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003464}
3465
Chris Lattner458b2aa2010-07-29 02:16:43 +00003466static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003467 llvm::LLVMContext &VMContext) {
3468 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3469 // is called integer-like if its size is less than or equal to one word, and
3470 // the offset of each of its addressable sub-fields is zero.
3471
3472 uint64_t Size = Context.getTypeSize(Ty);
3473
3474 // Check that the type fits in a word.
3475 if (Size > 32)
3476 return false;
3477
3478 // FIXME: Handle vector types!
3479 if (Ty->isVectorType())
3480 return false;
3481
Daniel Dunbard53bac72009-09-14 02:20:34 +00003482 // Float types are never treated as "integer like".
3483 if (Ty->isRealFloatingType())
3484 return false;
3485
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003486 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00003487 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003488 return true;
3489
Daniel Dunbar96ebba52010-02-01 23:31:26 +00003490 // Small complex integer types are "integer like".
3491 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3492 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003493
3494 // Single element and zero sized arrays should be allowed, by the definition
3495 // above, but they are not.
3496
3497 // Otherwise, it must be a record type.
3498 const RecordType *RT = Ty->getAs<RecordType>();
3499 if (!RT) return false;
3500
3501 // Ignore records with flexible arrays.
3502 const RecordDecl *RD = RT->getDecl();
3503 if (RD->hasFlexibleArrayMember())
3504 return false;
3505
3506 // Check that all sub-fields are at offset 0, and are themselves "integer
3507 // like".
3508 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3509
3510 bool HadField = false;
3511 unsigned idx = 0;
3512 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3513 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00003514 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003515
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003516 // Bit-fields are not addressable, we only need to verify they are "integer
3517 // like". We still have to disallow a subsequent non-bitfield, for example:
3518 // struct { int : 0; int x }
3519 // is non-integer like according to gcc.
3520 if (FD->isBitField()) {
3521 if (!RD->isUnion())
3522 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003523
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003524 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3525 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003526
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003527 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003528 }
3529
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003530 // Check if this field is at offset 0.
3531 if (Layout.getFieldOffset(idx) != 0)
3532 return false;
3533
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003534 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3535 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003536
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00003537 // Only allow at most one field in a structure. This doesn't match the
3538 // wording above, but follows gcc in situations with a field following an
3539 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003540 if (!RD->isUnion()) {
3541 if (HadField)
3542 return false;
3543
3544 HadField = true;
3545 }
3546 }
3547
3548 return true;
3549}
3550
Chris Lattner458b2aa2010-07-29 02:16:43 +00003551ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003552 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003553 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003554
Daniel Dunbar19964db2010-09-23 01:54:32 +00003555 // Large vector types should be returned via memory.
3556 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3557 return ABIArgInfo::getIndirect(0);
3558
John McCalla1dee5302010-08-22 10:59:02 +00003559 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00003560 // Treat an enum type as its underlying type.
3561 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3562 RetTy = EnumTy->getDecl()->getIntegerType();
3563
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00003564 return (RetTy->isPromotableIntegerType() ?
3565 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00003566 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003567
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003568 // Structures with either a non-trivial destructor or a non-trivial
3569 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00003570 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Rafael Espindolabbd44ef2010-06-08 02:42:08 +00003571 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3572
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003573 // Are we following APCS?
3574 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00003575 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003576 return ABIArgInfo::getIgnore();
3577
Daniel Dunbareedf1512010-02-01 23:31:19 +00003578 // Complex types are all returned as packed integers.
3579 //
3580 // FIXME: Consider using 2 x vector types if the back end handles them
3581 // correctly.
3582 if (RetTy->isAnyComplexType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003583 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00003584 getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00003585
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003586 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003587 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003588 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003589 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003590 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003591 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003592 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003593 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3594 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003595 }
3596
3597 // Otherwise return in memory.
3598 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003599 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003600
3601 // Otherwise this is an AAPCS variant.
3602
Chris Lattner458b2aa2010-07-29 02:16:43 +00003603 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003604 return ABIArgInfo::getIgnore();
3605
Bob Wilson1d9269a2011-11-02 04:51:36 +00003606 // Check for homogeneous aggregates with AAPCS-VFP.
3607 if (getABIKind() == AAPCS_VFP) {
3608 const Type *Base = 0;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003609 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3610 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00003611 // Homogeneous Aggregates are returned directly.
3612 return ABIArgInfo::getDirect();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003613 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00003614 }
3615
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003616 // Aggregates <= 4 bytes are returned in r0; other aggregates
3617 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00003618 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003619 if (Size <= 32) {
3620 // Return in the smallest viable integer type.
3621 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003622 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003623 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003624 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3625 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00003626 }
3627
Daniel Dunbar626f1d82009-09-13 08:03:58 +00003628 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003629}
3630
Manman Renfef9e312012-10-16 19:18:39 +00003631/// isIllegalVector - check whether Ty is an illegal vector type.
3632bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3633 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3634 // Check whether VT is legal.
3635 unsigned NumElements = VT->getNumElements();
3636 uint64_t Size = getContext().getTypeSize(VT);
3637 // NumElements should be power of 2.
3638 if ((NumElements & (NumElements - 1)) != 0)
3639 return true;
3640 // Size should be greater than 32 bits.
3641 return Size <= 32;
3642 }
3643 return false;
3644}
3645
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003646llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003647 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003648 llvm::Type *BP = CGF.Int8PtrTy;
3649 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003650
3651 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00003652 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003653 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00003654
Tim Northover1711cc92013-06-21 23:05:33 +00003655 if (isEmptyRecord(getContext(), Ty, true)) {
3656 // These are ignored for parameter passing purposes.
3657 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3658 return Builder.CreateBitCast(Addr, PTy);
3659 }
3660
Manman Rencca54d02012-10-16 19:01:37 +00003661 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00003662 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00003663 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00003664
3665 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3666 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00003667 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3668 getABIKind() == ARMABIInfo::AAPCS)
3669 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3670 else
3671 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00003672 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3673 if (isIllegalVectorType(Ty) && Size > 16) {
3674 IsIndirect = true;
3675 Size = 4;
3676 TyAlign = 4;
3677 }
Manman Rencca54d02012-10-16 19:01:37 +00003678
3679 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00003680 if (TyAlign > 4) {
3681 assert((TyAlign & (TyAlign - 1)) == 0 &&
3682 "Alignment is not power of 2!");
3683 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3684 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3685 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00003686 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00003687 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003688
3689 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00003690 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003691 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003692 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003693 "ap.next");
3694 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3695
Manman Renfef9e312012-10-16 19:18:39 +00003696 if (IsIndirect)
3697 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00003698 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00003699 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3700 // may not be correctly aligned for the vector type. We create an aligned
3701 // temporary space and copy the content over from ap.cur to the temporary
3702 // space. This is necessary if the natural alignment of the type is greater
3703 // than the ABI alignment.
3704 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3705 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3706 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3707 "var.align");
3708 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3709 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3710 Builder.CreateMemCpy(Dst, Src,
3711 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3712 TyAlign, false);
3713 Addr = AlignedTemp; //The content is in aligned location.
3714 }
3715 llvm::Type *PTy =
3716 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3717 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3718
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003719 return AddrTyped;
3720}
3721
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003722namespace {
3723
Derek Schuffa2020962012-10-16 22:30:41 +00003724class NaClARMABIInfo : public ABIInfo {
3725 public:
3726 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3727 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3728 virtual void computeInfo(CGFunctionInfo &FI) const;
3729 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3730 CodeGenFunction &CGF) const;
3731 private:
3732 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3733 ARMABIInfo NInfo; // Used for everything else.
3734};
3735
3736class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3737 public:
3738 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3739 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3740};
3741
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003742}
3743
Derek Schuffa2020962012-10-16 22:30:41 +00003744void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3745 if (FI.getASTCallingConvention() == CC_PnaclCall)
3746 PInfo.computeInfo(FI);
3747 else
3748 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3749}
3750
3751llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3752 CodeGenFunction &CGF) const {
3753 // Always use the native convention; calling pnacl-style varargs functions
3754 // is unsupported.
3755 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3756}
3757
Chris Lattner0cf24192010-06-28 20:05:43 +00003758//===----------------------------------------------------------------------===//
Tim Northover9bb857a2013-01-31 12:13:10 +00003759// AArch64 ABI Implementation
3760//===----------------------------------------------------------------------===//
3761
3762namespace {
3763
3764class AArch64ABIInfo : public ABIInfo {
3765public:
3766 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3767
3768private:
3769 // The AArch64 PCS is explicit about return types and argument types being
3770 // handled identically, so we don't need to draw a distinction between
3771 // Argument and Return classification.
3772 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3773 int &FreeVFPRegs) const;
3774
3775 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3776 llvm::Type *DirectTy = 0) const;
3777
3778 virtual void computeInfo(CGFunctionInfo &FI) const;
3779
3780 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3781 CodeGenFunction &CGF) const;
3782};
3783
3784class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3785public:
3786 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3787 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3788
3789 const AArch64ABIInfo &getABIInfo() const {
3790 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3791 }
3792
3793 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3794 return 31;
3795 }
3796
3797 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3798 llvm::Value *Address) const {
3799 // 0-31 are x0-x30 and sp: 8 bytes each
3800 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
3801 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
3802
3803 // 64-95 are v0-v31: 16 bytes each
3804 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
3805 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
3806
3807 return false;
3808 }
3809
3810};
3811
3812}
3813
3814void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3815 int FreeIntRegs = 8, FreeVFPRegs = 8;
3816
3817 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
3818 FreeIntRegs, FreeVFPRegs);
3819
3820 FreeIntRegs = FreeVFPRegs = 8;
3821 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3822 it != ie; ++it) {
3823 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
3824
3825 }
3826}
3827
3828ABIArgInfo
3829AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
3830 bool IsInt, llvm::Type *DirectTy) const {
3831 if (FreeRegs >= RegsNeeded) {
3832 FreeRegs -= RegsNeeded;
3833 return ABIArgInfo::getDirect(DirectTy);
3834 }
3835
3836 llvm::Type *Padding = 0;
3837
3838 // We need padding so that later arguments don't get filled in anyway. That
3839 // wouldn't happen if only ByVal arguments followed in the same category, but
3840 // a large structure will simply seem to be a pointer as far as LLVM is
3841 // concerned.
3842 if (FreeRegs > 0) {
3843 if (IsInt)
3844 Padding = llvm::Type::getInt64Ty(getVMContext());
3845 else
3846 Padding = llvm::Type::getFloatTy(getVMContext());
3847
3848 // Either [N x i64] or [N x float].
3849 Padding = llvm::ArrayType::get(Padding, FreeRegs);
3850 FreeRegs = 0;
3851 }
3852
3853 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
3854 /*IsByVal=*/ true, /*Realign=*/ false,
3855 Padding);
3856}
3857
3858
3859ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
3860 int &FreeIntRegs,
3861 int &FreeVFPRegs) const {
3862 // Can only occurs for return, but harmless otherwise.
3863 if (Ty->isVoidType())
3864 return ABIArgInfo::getIgnore();
3865
3866 // Large vector types should be returned via memory. There's no such concept
3867 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
3868 // classified they'd go into memory (see B.3).
3869 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
3870 if (FreeIntRegs > 0)
3871 --FreeIntRegs;
3872 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3873 }
3874
3875 // All non-aggregate LLVM types have a concrete ABI representation so they can
3876 // be passed directly. After this block we're guaranteed to be in a
3877 // complicated case.
3878 if (!isAggregateTypeForABI(Ty)) {
3879 // Treat an enum type as its underlying type.
3880 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3881 Ty = EnumTy->getDecl()->getIntegerType();
3882
3883 if (Ty->isFloatingType() || Ty->isVectorType())
3884 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
3885
3886 assert(getContext().getTypeSize(Ty) <= 128 &&
3887 "unexpectedly large scalar type");
3888
3889 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3890
3891 // If the type may need padding registers to ensure "alignment", we must be
3892 // careful when this is accounted for. Increasing the effective size covers
3893 // all cases.
3894 if (getContext().getTypeAlign(Ty) == 128)
3895 RegsNeeded += FreeIntRegs % 2 != 0;
3896
3897 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
3898 }
3899
Mark Lacey3825e832013-10-06 01:33:34 +00003900 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003901 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northover9bb857a2013-01-31 12:13:10 +00003902 --FreeIntRegs;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003903 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northover9bb857a2013-01-31 12:13:10 +00003904 }
3905
3906 if (isEmptyRecord(getContext(), Ty, true)) {
3907 if (!getContext().getLangOpts().CPlusPlus) {
3908 // Empty structs outside C++ mode are a GNU extension, so no ABI can
3909 // possibly tell us what to do. It turns out (I believe) that GCC ignores
3910 // the object for parameter-passsing purposes.
3911 return ABIArgInfo::getIgnore();
3912 }
3913
3914 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
3915 // description of va_arg in the PCS require that an empty struct does
3916 // actually occupy space for parameter-passing. I'm hoping for a
3917 // clarification giving an explicit paragraph to point to in future.
3918 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
3919 llvm::Type::getInt8Ty(getVMContext()));
3920 }
3921
3922 // Homogeneous vector aggregates get passed in registers or on the stack.
3923 const Type *Base = 0;
3924 uint64_t NumMembers = 0;
3925 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
3926 assert(Base && "Base class should be set for homogeneous aggregate");
3927 // Homogeneous aggregates are passed and returned directly.
3928 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
3929 /*IsInt=*/ false);
3930 }
3931
3932 uint64_t Size = getContext().getTypeSize(Ty);
3933 if (Size <= 128) {
3934 // Small structs can use the same direct type whether they're in registers
3935 // or on the stack.
3936 llvm::Type *BaseTy;
3937 unsigned NumBases;
3938 int SizeInRegs = (Size + 63) / 64;
3939
3940 if (getContext().getTypeAlign(Ty) == 128) {
3941 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
3942 NumBases = 1;
3943
3944 // If the type may need padding registers to ensure "alignment", we must
3945 // be careful when this is accounted for. Increasing the effective size
3946 // covers all cases.
3947 SizeInRegs += FreeIntRegs % 2 != 0;
3948 } else {
3949 BaseTy = llvm::Type::getInt64Ty(getVMContext());
3950 NumBases = SizeInRegs;
3951 }
3952 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
3953
3954 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
3955 /*IsInt=*/ true, DirectTy);
3956 }
3957
3958 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
3959 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
3960 --FreeIntRegs;
3961 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
3962}
3963
3964llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3965 CodeGenFunction &CGF) const {
3966 // The AArch64 va_list type and handling is specified in the Procedure Call
3967 // Standard, section B.4:
3968 //
3969 // struct {
3970 // void *__stack;
3971 // void *__gr_top;
3972 // void *__vr_top;
3973 // int __gr_offs;
3974 // int __vr_offs;
3975 // };
3976
3977 assert(!CGF.CGM.getDataLayout().isBigEndian()
3978 && "va_arg not implemented for big-endian AArch64");
3979
3980 int FreeIntRegs = 8, FreeVFPRegs = 8;
3981 Ty = CGF.getContext().getCanonicalType(Ty);
3982 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
3983
3984 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3985 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3986 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3987 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3988
3989 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
3990 int reg_top_index;
3991 int RegSize;
3992 if (FreeIntRegs < 8) {
3993 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
3994 // 3 is the field number of __gr_offs
3995 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3996 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3997 reg_top_index = 1; // field number for __gr_top
3998 RegSize = 8 * (8 - FreeIntRegs);
3999 } else {
4000 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
4001 // 4 is the field number of __vr_offs.
4002 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4003 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4004 reg_top_index = 2; // field number for __vr_top
4005 RegSize = 16 * (8 - FreeVFPRegs);
4006 }
4007
4008 //=======================================
4009 // Find out where argument was passed
4010 //=======================================
4011
4012 // If reg_offs >= 0 we're already using the stack for this type of
4013 // argument. We don't want to keep updating reg_offs (in case it overflows,
4014 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4015 // whatever they get).
4016 llvm::Value *UsingStack = 0;
4017 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
4018 llvm::ConstantInt::get(CGF.Int32Ty, 0));
4019
4020 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4021
4022 // Otherwise, at least some kind of argument could go in these registers, the
4023 // quesiton is whether this particular type is too big.
4024 CGF.EmitBlock(MaybeRegBlock);
4025
4026 // Integer arguments may need to correct register alignment (for example a
4027 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4028 // align __gr_offs to calculate the potential address.
4029 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4030 int Align = getContext().getTypeAlign(Ty) / 8;
4031
4032 reg_offs = CGF.Builder.CreateAdd(reg_offs,
4033 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4034 "align_regoffs");
4035 reg_offs = CGF.Builder.CreateAnd(reg_offs,
4036 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4037 "aligned_regoffs");
4038 }
4039
4040 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4041 llvm::Value *NewOffset = 0;
4042 NewOffset = CGF.Builder.CreateAdd(reg_offs,
4043 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4044 "new_reg_offs");
4045 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4046
4047 // Now we're in a position to decide whether this argument really was in
4048 // registers or not.
4049 llvm::Value *InRegs = 0;
4050 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4051 llvm::ConstantInt::get(CGF.Int32Ty, 0),
4052 "inreg");
4053
4054 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4055
4056 //=======================================
4057 // Argument was in registers
4058 //=======================================
4059
4060 // Now we emit the code for if the argument was originally passed in
4061 // registers. First start the appropriate block:
4062 CGF.EmitBlock(InRegBlock);
4063
4064 llvm::Value *reg_top_p = 0, *reg_top = 0;
4065 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4066 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4067 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4068 llvm::Value *RegAddr = 0;
4069 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4070
4071 if (!AI.isDirect()) {
4072 // If it's been passed indirectly (actually a struct), whatever we find from
4073 // stored registers or on the stack will actually be a struct **.
4074 MemTy = llvm::PointerType::getUnqual(MemTy);
4075 }
4076
4077 const Type *Base = 0;
4078 uint64_t NumMembers;
4079 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4080 && NumMembers > 1) {
4081 // Homogeneous aggregates passed in registers will have their elements split
4082 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4083 // qN+1, ...). We reload and store into a temporary local variable
4084 // contiguously.
4085 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4086 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4087 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4088 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4089
4090 for (unsigned i = 0; i < NumMembers; ++i) {
4091 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
4092 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4093 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4094 llvm::PointerType::getUnqual(BaseTy));
4095 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4096
4097 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4098 CGF.Builder.CreateStore(Elem, StoreAddr);
4099 }
4100
4101 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4102 } else {
4103 // Otherwise the object is contiguous in memory
4104 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4105 }
4106
4107 CGF.EmitBranch(ContBlock);
4108
4109 //=======================================
4110 // Argument was on the stack
4111 //=======================================
4112 CGF.EmitBlock(OnStackBlock);
4113
4114 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4115 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4116 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4117
4118 // Again, stack arguments may need realigmnent. In this case both integer and
4119 // floating-point ones might be affected.
4120 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4121 int Align = getContext().getTypeAlign(Ty) / 8;
4122
4123 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4124
4125 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4126 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4127 "align_stack");
4128 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4129 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4130 "align_stack");
4131
4132 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4133 }
4134
4135 uint64_t StackSize;
4136 if (AI.isDirect())
4137 StackSize = getContext().getTypeSize(Ty) / 8;
4138 else
4139 StackSize = 8;
4140
4141 // All stack slots are 8 bytes
4142 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4143
4144 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4145 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4146 "new_stack");
4147
4148 // Write the new value of __stack for the next call to va_arg
4149 CGF.Builder.CreateStore(NewStack, stack_p);
4150
4151 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4152
4153 CGF.EmitBranch(ContBlock);
4154
4155 //=======================================
4156 // Tidy up
4157 //=======================================
4158 CGF.EmitBlock(ContBlock);
4159
4160 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4161 ResAddr->addIncoming(RegAddr, InRegBlock);
4162 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4163
4164 if (AI.isDirect())
4165 return ResAddr;
4166
4167 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4168}
4169
4170//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004171// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004172//===----------------------------------------------------------------------===//
4173
4174namespace {
4175
Justin Holewinski83e96682012-05-24 17:43:12 +00004176class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004177public:
Justin Holewinski36837432013-03-30 14:38:24 +00004178 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004179
4180 ABIArgInfo classifyReturnType(QualType RetTy) const;
4181 ABIArgInfo classifyArgumentType(QualType Ty) const;
4182
4183 virtual void computeInfo(CGFunctionInfo &FI) const;
4184 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4185 CodeGenFunction &CFG) const;
4186};
4187
Justin Holewinski83e96682012-05-24 17:43:12 +00004188class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004189public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004190 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4191 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Justin Holewinski38031972011-10-05 17:58:44 +00004192
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004193 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4194 CodeGen::CodeGenModule &M) const;
Justin Holewinski36837432013-03-30 14:38:24 +00004195private:
4196 static void addKernelMetadata(llvm::Function *F);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004197};
4198
Justin Holewinski83e96682012-05-24 17:43:12 +00004199ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004200 if (RetTy->isVoidType())
4201 return ABIArgInfo::getIgnore();
4202 if (isAggregateTypeForABI(RetTy))
4203 return ABIArgInfo::getIndirect(0);
4204 return ABIArgInfo::getDirect();
4205}
4206
Justin Holewinski83e96682012-05-24 17:43:12 +00004207ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004208 if (isAggregateTypeForABI(Ty))
4209 return ABIArgInfo::getIndirect(0);
4210
4211 return ABIArgInfo::getDirect();
4212}
4213
Justin Holewinski83e96682012-05-24 17:43:12 +00004214void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004215 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4216 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4217 it != ie; ++it)
4218 it->info = classifyArgumentType(it->type);
4219
4220 // Always honor user-specified calling convention.
4221 if (FI.getCallingConvention() != llvm::CallingConv::C)
4222 return;
4223
John McCall882987f2013-02-28 19:01:20 +00004224 FI.setEffectiveCallingConvention(getRuntimeCC());
4225}
4226
Justin Holewinski83e96682012-05-24 17:43:12 +00004227llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4228 CodeGenFunction &CFG) const {
4229 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004230}
4231
Justin Holewinski83e96682012-05-24 17:43:12 +00004232void NVPTXTargetCodeGenInfo::
4233SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4234 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00004235 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4236 if (!FD) return;
4237
4238 llvm::Function *F = cast<llvm::Function>(GV);
4239
4240 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00004241 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00004242 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00004243 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00004244 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00004245 // OpenCL __kernel functions get kernel metadata
4246 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004247 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004248 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00004249 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004250 }
Justin Holewinski38031972011-10-05 17:58:44 +00004251
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004252 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004253 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00004254 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00004255 // __global__ functions cannot be called from the device, we do not
4256 // need to set the noinline attribute.
4257 if (FD->getAttr<CUDAGlobalAttr>())
Justin Holewinski36837432013-03-30 14:38:24 +00004258 addKernelMetadata(F);
Justin Holewinski38031972011-10-05 17:58:44 +00004259 }
4260}
4261
Justin Holewinski36837432013-03-30 14:38:24 +00004262void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4263 llvm::Module *M = F->getParent();
4264 llvm::LLVMContext &Ctx = M->getContext();
4265
4266 // Get "nvvm.annotations" metadata node
4267 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4268
4269 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4270 llvm::SmallVector<llvm::Value *, 3> MDVals;
4271 MDVals.push_back(F);
4272 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4273 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4274
4275 // Append metadata to nvvm.annotations
4276 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4277}
4278
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004279}
4280
4281//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00004282// SystemZ ABI Implementation
4283//===----------------------------------------------------------------------===//
4284
4285namespace {
4286
4287class SystemZABIInfo : public ABIInfo {
4288public:
4289 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4290
4291 bool isPromotableIntegerType(QualType Ty) const;
4292 bool isCompoundType(QualType Ty) const;
4293 bool isFPArgumentType(QualType Ty) const;
4294
4295 ABIArgInfo classifyReturnType(QualType RetTy) const;
4296 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4297
4298 virtual void computeInfo(CGFunctionInfo &FI) const {
4299 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4300 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4301 it != ie; ++it)
4302 it->info = classifyArgumentType(it->type);
4303 }
4304
4305 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4306 CodeGenFunction &CGF) const;
4307};
4308
4309class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4310public:
4311 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4312 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4313};
4314
4315}
4316
4317bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4318 // Treat an enum type as its underlying type.
4319 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4320 Ty = EnumTy->getDecl()->getIntegerType();
4321
4322 // Promotable integer types are required to be promoted by the ABI.
4323 if (Ty->isPromotableIntegerType())
4324 return true;
4325
4326 // 32-bit values must also be promoted.
4327 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4328 switch (BT->getKind()) {
4329 case BuiltinType::Int:
4330 case BuiltinType::UInt:
4331 return true;
4332 default:
4333 return false;
4334 }
4335 return false;
4336}
4337
4338bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4339 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4340}
4341
4342bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4343 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4344 switch (BT->getKind()) {
4345 case BuiltinType::Float:
4346 case BuiltinType::Double:
4347 return true;
4348 default:
4349 return false;
4350 }
4351
4352 if (const RecordType *RT = Ty->getAsStructureType()) {
4353 const RecordDecl *RD = RT->getDecl();
4354 bool Found = false;
4355
4356 // If this is a C++ record, check the bases first.
4357 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4358 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4359 E = CXXRD->bases_end(); I != E; ++I) {
4360 QualType Base = I->getType();
4361
4362 // Empty bases don't affect things either way.
4363 if (isEmptyRecord(getContext(), Base, true))
4364 continue;
4365
4366 if (Found)
4367 return false;
4368 Found = isFPArgumentType(Base);
4369 if (!Found)
4370 return false;
4371 }
4372
4373 // Check the fields.
4374 for (RecordDecl::field_iterator I = RD->field_begin(),
4375 E = RD->field_end(); I != E; ++I) {
4376 const FieldDecl *FD = *I;
4377
4378 // Empty bitfields don't affect things either way.
4379 // Unlike isSingleElementStruct(), empty structure and array fields
4380 // do count. So do anonymous bitfields that aren't zero-sized.
4381 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4382 return true;
4383
4384 // Unlike isSingleElementStruct(), arrays do not count.
4385 // Nested isFPArgumentType structures still do though.
4386 if (Found)
4387 return false;
4388 Found = isFPArgumentType(FD->getType());
4389 if (!Found)
4390 return false;
4391 }
4392
4393 // Unlike isSingleElementStruct(), trailing padding is allowed.
4394 // An 8-byte aligned struct s { float f; } is passed as a double.
4395 return Found;
4396 }
4397
4398 return false;
4399}
4400
4401llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4402 CodeGenFunction &CGF) const {
4403 // Assume that va_list type is correct; should be pointer to LLVM type:
4404 // struct {
4405 // i64 __gpr;
4406 // i64 __fpr;
4407 // i8 *__overflow_arg_area;
4408 // i8 *__reg_save_area;
4409 // };
4410
4411 // Every argument occupies 8 bytes and is passed by preference in either
4412 // GPRs or FPRs.
4413 Ty = CGF.getContext().getCanonicalType(Ty);
4414 ABIArgInfo AI = classifyArgumentType(Ty);
4415 bool InFPRs = isFPArgumentType(Ty);
4416
4417 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4418 bool IsIndirect = AI.isIndirect();
4419 unsigned UnpaddedBitSize;
4420 if (IsIndirect) {
4421 APTy = llvm::PointerType::getUnqual(APTy);
4422 UnpaddedBitSize = 64;
4423 } else
4424 UnpaddedBitSize = getContext().getTypeSize(Ty);
4425 unsigned PaddedBitSize = 64;
4426 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4427
4428 unsigned PaddedSize = PaddedBitSize / 8;
4429 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4430
4431 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4432 if (InFPRs) {
4433 MaxRegs = 4; // Maximum of 4 FPR arguments
4434 RegCountField = 1; // __fpr
4435 RegSaveIndex = 16; // save offset for f0
4436 RegPadding = 0; // floats are passed in the high bits of an FPR
4437 } else {
4438 MaxRegs = 5; // Maximum of 5 GPR arguments
4439 RegCountField = 0; // __gpr
4440 RegSaveIndex = 2; // save offset for r2
4441 RegPadding = Padding; // values are passed in the low bits of a GPR
4442 }
4443
4444 llvm::Value *RegCountPtr =
4445 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4446 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4447 llvm::Type *IndexTy = RegCount->getType();
4448 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4449 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
4450 "fits_in_regs");
4451
4452 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4453 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4454 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4455 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4456
4457 // Emit code to load the value if it was passed in registers.
4458 CGF.EmitBlock(InRegBlock);
4459
4460 // Work out the address of an argument register.
4461 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4462 llvm::Value *ScaledRegCount =
4463 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4464 llvm::Value *RegBase =
4465 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4466 llvm::Value *RegOffset =
4467 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4468 llvm::Value *RegSaveAreaPtr =
4469 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4470 llvm::Value *RegSaveArea =
4471 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4472 llvm::Value *RawRegAddr =
4473 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4474 llvm::Value *RegAddr =
4475 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4476
4477 // Update the register count
4478 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4479 llvm::Value *NewRegCount =
4480 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4481 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4482 CGF.EmitBranch(ContBlock);
4483
4484 // Emit code to load the value if it was passed in memory.
4485 CGF.EmitBlock(InMemBlock);
4486
4487 // Work out the address of a stack argument.
4488 llvm::Value *OverflowArgAreaPtr =
4489 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4490 llvm::Value *OverflowArgArea =
4491 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4492 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4493 llvm::Value *RawMemAddr =
4494 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4495 llvm::Value *MemAddr =
4496 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4497
4498 // Update overflow_arg_area_ptr pointer
4499 llvm::Value *NewOverflowArgArea =
4500 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4501 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4502 CGF.EmitBranch(ContBlock);
4503
4504 // Return the appropriate result.
4505 CGF.EmitBlock(ContBlock);
4506 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4507 ResAddr->addIncoming(RegAddr, InRegBlock);
4508 ResAddr->addIncoming(MemAddr, InMemBlock);
4509
4510 if (IsIndirect)
4511 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4512
4513 return ResAddr;
4514}
4515
John McCall1fe2a8c2013-06-18 02:46:29 +00004516bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4517 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4518 assert(Triple.getArch() == llvm::Triple::x86);
4519
4520 switch (Opts.getStructReturnConvention()) {
4521 case CodeGenOptions::SRCK_Default:
4522 break;
4523 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4524 return false;
4525 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4526 return true;
4527 }
4528
4529 if (Triple.isOSDarwin())
4530 return true;
4531
4532 switch (Triple.getOS()) {
4533 case llvm::Triple::Cygwin:
4534 case llvm::Triple::MinGW32:
4535 case llvm::Triple::AuroraUX:
4536 case llvm::Triple::DragonFly:
4537 case llvm::Triple::FreeBSD:
4538 case llvm::Triple::OpenBSD:
4539 case llvm::Triple::Bitrig:
4540 case llvm::Triple::Win32:
4541 return true;
4542 default:
4543 return false;
4544 }
4545}
Ulrich Weigand47445072013-05-06 16:26:41 +00004546
4547ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4548 if (RetTy->isVoidType())
4549 return ABIArgInfo::getIgnore();
4550 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4551 return ABIArgInfo::getIndirect(0);
4552 return (isPromotableIntegerType(RetTy) ?
4553 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4554}
4555
4556ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4557 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00004558 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00004559 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4560
4561 // Integers and enums are extended to full register width.
4562 if (isPromotableIntegerType(Ty))
4563 return ABIArgInfo::getExtend();
4564
4565 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4566 uint64_t Size = getContext().getTypeSize(Ty);
4567 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
4568 return ABIArgInfo::getIndirect(0);
4569
4570 // Handle small structures.
4571 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4572 // Structures with flexible arrays have variable length, so really
4573 // fail the size test above.
4574 const RecordDecl *RD = RT->getDecl();
4575 if (RD->hasFlexibleArrayMember())
4576 return ABIArgInfo::getIndirect(0);
4577
4578 // The structure is passed as an unextended integer, a float, or a double.
4579 llvm::Type *PassTy;
4580 if (isFPArgumentType(Ty)) {
4581 assert(Size == 32 || Size == 64);
4582 if (Size == 32)
4583 PassTy = llvm::Type::getFloatTy(getVMContext());
4584 else
4585 PassTy = llvm::Type::getDoubleTy(getVMContext());
4586 } else
4587 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4588 return ABIArgInfo::getDirect(PassTy);
4589 }
4590
4591 // Non-structure compounds are passed indirectly.
4592 if (isCompoundType(Ty))
4593 return ABIArgInfo::getIndirect(0);
4594
4595 return ABIArgInfo::getDirect(0);
4596}
4597
4598//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004599// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004600//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004601
4602namespace {
4603
4604class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4605public:
Chris Lattner2b037972010-07-29 02:01:43 +00004606 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4607 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004608 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4609 CodeGen::CodeGenModule &M) const;
4610};
4611
4612}
4613
4614void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4615 llvm::GlobalValue *GV,
4616 CodeGen::CodeGenModule &M) const {
4617 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4618 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4619 // Handle 'interrupt' attribute:
4620 llvm::Function *F = cast<llvm::Function>(GV);
4621
4622 // Step 1: Set ISR calling convention.
4623 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4624
4625 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00004626 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004627
4628 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004629 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004630 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00004631 "__isr_" + Twine(Num),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004632 GV, &M.getModule());
4633 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004634 }
4635}
4636
Chris Lattner0cf24192010-06-28 20:05:43 +00004637//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00004638// MIPS ABI Implementation. This works for both little-endian and
4639// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00004640//===----------------------------------------------------------------------===//
4641
John McCall943fae92010-05-27 06:19:26 +00004642namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004643class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00004644 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004645 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4646 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004647 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004648 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004649 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004650 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004651public:
Akira Hatanaka618b2982013-10-29 19:00:35 +00004652 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32, bool HasFP64) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004653 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanaka618b2982013-10-29 19:00:35 +00004654 StackAlignInBytes(IsO32 && !HasFP64 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00004655
4656 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004657 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004658 virtual void computeInfo(CGFunctionInfo &FI) const;
4659 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4660 CodeGenFunction &CGF) const;
4661};
4662
John McCall943fae92010-05-27 06:19:26 +00004663class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004664 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00004665public:
Akira Hatanaka618b2982013-10-29 19:00:35 +00004666 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32, const TargetInfo &Info)
4667 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32, Info.hasFeature("fp64"))),
Akira Hatanaka14378522011-11-02 23:14:57 +00004668 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00004669
4670 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4671 return 29;
4672 }
4673
Reed Kotler373feca2013-01-16 17:10:28 +00004674 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4675 CodeGen::CodeGenModule &CGM) const {
Reed Kotler3d5966f2013-03-13 20:40:30 +00004676 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4677 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00004678 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00004679 if (FD->hasAttr<Mips16Attr>()) {
4680 Fn->addFnAttr("mips16");
4681 }
4682 else if (FD->hasAttr<NoMips16Attr>()) {
4683 Fn->addFnAttr("nomips16");
4684 }
Reed Kotler373feca2013-01-16 17:10:28 +00004685 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00004686
John McCall943fae92010-05-27 06:19:26 +00004687 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004688 llvm::Value *Address) const;
John McCall3480ef22011-08-30 01:42:09 +00004689
4690 unsigned getSizeOfUnwindException() const {
Akira Hatanaka0486db02011-09-20 18:23:28 +00004691 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00004692 }
John McCall943fae92010-05-27 06:19:26 +00004693};
4694}
4695
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004696void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00004697 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004698 llvm::IntegerType *IntTy =
4699 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004700
4701 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4702 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4703 ArgList.push_back(IntTy);
4704
4705 // If necessary, add one more integer type to ArgList.
4706 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4707
4708 if (R)
4709 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004710}
4711
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004712// In N32/64, an aligned double precision floating point field is passed in
4713// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004714llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004715 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4716
4717 if (IsO32) {
4718 CoerceToIntArgs(TySize, ArgList);
4719 return llvm::StructType::get(getVMContext(), ArgList);
4720 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004721
Akira Hatanaka02e13e52012-01-12 00:52:17 +00004722 if (Ty->isComplexType())
4723 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00004724
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004725 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004726
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004727 // Unions/vectors are passed in integer registers.
4728 if (!RT || !RT->isStructureOrClassType()) {
4729 CoerceToIntArgs(TySize, ArgList);
4730 return llvm::StructType::get(getVMContext(), ArgList);
4731 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004732
4733 const RecordDecl *RD = RT->getDecl();
4734 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004735 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004736
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004737 uint64_t LastOffset = 0;
4738 unsigned idx = 0;
4739 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4740
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00004741 // Iterate over fields in the struct/class and check if there are any aligned
4742 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004743 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4744 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004745 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004746 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4747
4748 if (!BT || BT->getKind() != BuiltinType::Double)
4749 continue;
4750
4751 uint64_t Offset = Layout.getFieldOffset(idx);
4752 if (Offset % 64) // Ignore doubles that are not aligned.
4753 continue;
4754
4755 // Add ((Offset - LastOffset) / 64) args of type i64.
4756 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4757 ArgList.push_back(I64);
4758
4759 // Add double type.
4760 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4761 LastOffset = Offset + 64;
4762 }
4763
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004764 CoerceToIntArgs(TySize - LastOffset, IntArgList);
4765 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00004766
4767 return llvm::StructType::get(getVMContext(), ArgList);
4768}
4769
Akira Hatanakaddd66342013-10-29 18:41:15 +00004770llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
4771 uint64_t Offset) const {
4772 if (OrigOffset + MinABIStackAlignInBytes > Offset)
4773 return 0;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004774
Akira Hatanakaddd66342013-10-29 18:41:15 +00004775 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00004776}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00004777
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004778ABIArgInfo
4779MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00004780 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004781 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00004782 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004783
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004784 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
4785 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00004786 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
4787 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00004788
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004789 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00004790 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004791 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00004792 return ABIArgInfo::getIgnore();
4793
Mark Lacey3825e832013-10-06 01:33:34 +00004794 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004795 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004796 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004797 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00004798
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004799 // If we have reached here, aggregates are passed directly by coercing to
4800 // another structure type. Padding is inserted if the offset of the
4801 // aggregate is unaligned.
4802 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00004803 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00004804 }
4805
4806 // Treat an enum type as its underlying type.
4807 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4808 Ty = EnumTy->getDecl()->getIntegerType();
4809
Akira Hatanaka1632af62012-01-09 19:31:25 +00004810 if (Ty->isPromotableIntegerType())
4811 return ABIArgInfo::getExtend();
4812
Akira Hatanakaddd66342013-10-29 18:41:15 +00004813 return ABIArgInfo::getDirect(
4814 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00004815}
4816
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004817llvm::Type*
4818MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00004819 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004820 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004821
Akira Hatanakab6f74432012-02-09 18:49:26 +00004822 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004823 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00004824 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4825 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004826
Akira Hatanakab6f74432012-02-09 18:49:26 +00004827 // N32/64 returns struct/classes in floating point registers if the
4828 // following conditions are met:
4829 // 1. The size of the struct/class is no larger than 128-bit.
4830 // 2. The struct/class has one or two fields all of which are floating
4831 // point types.
4832 // 3. The offset of the first field is zero (this follows what gcc does).
4833 //
4834 // Any other composite results are returned in integer registers.
4835 //
4836 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
4837 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
4838 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00004839 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004840
Akira Hatanakab6f74432012-02-09 18:49:26 +00004841 if (!BT || !BT->isFloatingPoint())
4842 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004843
David Blaikie2d7c57e2012-04-30 02:36:29 +00004844 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00004845 }
4846
4847 if (b == e)
4848 return llvm::StructType::get(getVMContext(), RTList,
4849 RD->hasAttr<PackedAttr>());
4850
4851 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004852 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004853 }
4854
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004855 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004856 return llvm::StructType::get(getVMContext(), RTList);
4857}
4858
Akira Hatanakab579fe52011-06-02 00:09:17 +00004859ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00004860 uint64_t Size = getContext().getTypeSize(RetTy);
4861
4862 if (RetTy->isVoidType() || Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00004863 return ABIArgInfo::getIgnore();
4864
Akira Hatanakac37eddf2012-05-11 21:01:17 +00004865 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey3825e832013-10-06 01:33:34 +00004866 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004867 return ABIArgInfo::getIndirect(0);
4868
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004869 if (Size <= 128) {
4870 if (RetTy->isAnyComplexType())
4871 return ABIArgInfo::getDirect();
4872
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00004873 // O32 returns integer vectors in registers.
4874 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
4875 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4876
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00004877 if (!IsO32)
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00004878 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4879 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00004880
4881 return ABIArgInfo::getIndirect(0);
4882 }
4883
4884 // Treat an enum type as its underlying type.
4885 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4886 RetTy = EnumTy->getDecl()->getIntegerType();
4887
4888 return (RetTy->isPromotableIntegerType() ?
4889 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4890}
4891
4892void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00004893 ABIArgInfo &RetInfo = FI.getReturnInfo();
4894 RetInfo = classifyReturnType(FI.getReturnType());
4895
4896 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00004897 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00004898
Akira Hatanakab579fe52011-06-02 00:09:17 +00004899 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4900 it != ie; ++it)
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00004901 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00004902}
4903
4904llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4905 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004906 llvm::Type *BP = CGF.Int8PtrTy;
4907 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004908
4909 CGBuilderTy &Builder = CGF.Builder;
4910 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4911 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka37715282012-01-23 23:59:52 +00004912 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004913 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4914 llvm::Value *AddrTyped;
John McCallc8e01702013-04-16 22:48:15 +00004915 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka37715282012-01-23 23:59:52 +00004916 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004917
4918 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka37715282012-01-23 23:59:52 +00004919 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
4920 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
4921 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
4922 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004923 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
4924 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
4925 }
4926 else
4927 AddrTyped = Builder.CreateBitCast(Addr, PTy);
4928
4929 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka37715282012-01-23 23:59:52 +00004930 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004931 uint64_t Offset =
4932 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
4933 llvm::Value *NextAddr =
Akira Hatanaka37715282012-01-23 23:59:52 +00004934 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakafb1d9f32011-08-01 20:48:01 +00004935 "ap.next");
4936 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4937
4938 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00004939}
4940
John McCall943fae92010-05-27 06:19:26 +00004941bool
4942MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4943 llvm::Value *Address) const {
4944 // This information comes from gcc's implementation, which seems to
4945 // as canonical as it gets.
4946
John McCall943fae92010-05-27 06:19:26 +00004947 // Everything on MIPS is 4 bytes. Double-precision FP registers
4948 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004949 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00004950
4951 // 0-31 are the general purpose registers, $0 - $31.
4952 // 32-63 are the floating-point registers, $f0 - $f31.
4953 // 64 and 65 are the multiply/divide registers, $hi and $lo.
4954 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00004955 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00004956
4957 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
4958 // They are one bit wide and ignored here.
4959
4960 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
4961 // (coprocessor 1 is the FP unit)
4962 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
4963 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
4964 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004965 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00004966 return false;
4967}
4968
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004969//===----------------------------------------------------------------------===//
4970// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
4971// Currently subclassed only to implement custom OpenCL C function attribute
4972// handling.
4973//===----------------------------------------------------------------------===//
4974
4975namespace {
4976
4977class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4978public:
4979 TCETargetCodeGenInfo(CodeGenTypes &CGT)
4980 : DefaultTargetCodeGenInfo(CGT) {}
4981
4982 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4983 CodeGen::CodeGenModule &M) const;
4984};
4985
4986void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4987 llvm::GlobalValue *GV,
4988 CodeGen::CodeGenModule &M) const {
4989 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4990 if (!FD) return;
4991
4992 llvm::Function *F = cast<llvm::Function>(GV);
4993
David Blaikiebbafb8a2012-03-11 07:00:24 +00004994 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004995 if (FD->hasAttr<OpenCLKernelAttr>()) {
4996 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00004997 F->addFnAttr(llvm::Attribute::NoInline);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00004998
4999 if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
5000
5001 // Convert the reqd_work_group_size() attributes to metadata.
5002 llvm::LLVMContext &Context = F->getContext();
5003 llvm::NamedMDNode *OpenCLMetadata =
5004 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5005
5006 SmallVector<llvm::Value*, 5> Operands;
5007 Operands.push_back(F);
5008
Chris Lattnerece04092012-02-07 00:39:47 +00005009 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5010 llvm::APInt(32,
5011 FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim())));
5012 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5013 llvm::APInt(32,
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005014 FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005015 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5016 llvm::APInt(32,
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005017 FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim())));
5018
5019 // Add a boolean constant operand for "required" (true) or "hint" (false)
5020 // for implementing the work_group_size_hint attr later. Currently
5021 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005022 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005023 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5024 }
5025 }
5026 }
5027}
5028
5029}
John McCall943fae92010-05-27 06:19:26 +00005030
Tony Linthicum76329bf2011-12-12 21:14:55 +00005031//===----------------------------------------------------------------------===//
5032// Hexagon ABI Implementation
5033//===----------------------------------------------------------------------===//
5034
5035namespace {
5036
5037class HexagonABIInfo : public ABIInfo {
5038
5039
5040public:
5041 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5042
5043private:
5044
5045 ABIArgInfo classifyReturnType(QualType RetTy) const;
5046 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5047
5048 virtual void computeInfo(CGFunctionInfo &FI) const;
5049
5050 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5051 CodeGenFunction &CGF) const;
5052};
5053
5054class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5055public:
5056 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5057 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5058
5059 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5060 return 29;
5061 }
5062};
5063
5064}
5065
5066void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5067 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5068 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5069 it != ie; ++it)
5070 it->info = classifyArgumentType(it->type);
5071}
5072
5073ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5074 if (!isAggregateTypeForABI(Ty)) {
5075 // Treat an enum type as its underlying type.
5076 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5077 Ty = EnumTy->getDecl()->getIntegerType();
5078
5079 return (Ty->isPromotableIntegerType() ?
5080 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5081 }
5082
5083 // Ignore empty records.
5084 if (isEmptyRecord(getContext(), Ty, true))
5085 return ABIArgInfo::getIgnore();
5086
Mark Lacey3825e832013-10-06 01:33:34 +00005087 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005088 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005089
5090 uint64_t Size = getContext().getTypeSize(Ty);
5091 if (Size > 64)
5092 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5093 // Pass in the smallest viable integer type.
5094 else if (Size > 32)
5095 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5096 else if (Size > 16)
5097 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5098 else if (Size > 8)
5099 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5100 else
5101 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5102}
5103
5104ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5105 if (RetTy->isVoidType())
5106 return ABIArgInfo::getIgnore();
5107
5108 // Large vector types should be returned via memory.
5109 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5110 return ABIArgInfo::getIndirect(0);
5111
5112 if (!isAggregateTypeForABI(RetTy)) {
5113 // Treat an enum type as its underlying type.
5114 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5115 RetTy = EnumTy->getDecl()->getIntegerType();
5116
5117 return (RetTy->isPromotableIntegerType() ?
5118 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5119 }
5120
5121 // Structures with either a non-trivial destructor or a non-trivial
5122 // copy constructor are always indirect.
Mark Lacey3825e832013-10-06 01:33:34 +00005123 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum76329bf2011-12-12 21:14:55 +00005124 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5125
5126 if (isEmptyRecord(getContext(), RetTy, true))
5127 return ABIArgInfo::getIgnore();
5128
5129 // Aggregates <= 8 bytes are returned in r0; other aggregates
5130 // are returned indirectly.
5131 uint64_t Size = getContext().getTypeSize(RetTy);
5132 if (Size <= 64) {
5133 // Return in the smallest viable integer type.
5134 if (Size <= 8)
5135 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5136 if (Size <= 16)
5137 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5138 if (Size <= 32)
5139 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5140 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5141 }
5142
5143 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5144}
5145
5146llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005147 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005148 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005149 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005150
5151 CGBuilderTy &Builder = CGF.Builder;
5152 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5153 "ap");
5154 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5155 llvm::Type *PTy =
5156 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5157 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5158
5159 uint64_t Offset =
5160 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5161 llvm::Value *NextAddr =
5162 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5163 "ap.next");
5164 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5165
5166 return AddrTyped;
5167}
5168
5169
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005170//===----------------------------------------------------------------------===//
5171// SPARC v9 ABI Implementation.
5172// Based on the SPARC Compliance Definition version 2.4.1.
5173//
5174// Function arguments a mapped to a nominal "parameter array" and promoted to
5175// registers depending on their type. Each argument occupies 8 or 16 bytes in
5176// the array, structs larger than 16 bytes are passed indirectly.
5177//
5178// One case requires special care:
5179//
5180// struct mixed {
5181// int i;
5182// float f;
5183// };
5184//
5185// When a struct mixed is passed by value, it only occupies 8 bytes in the
5186// parameter array, but the int is passed in an integer register, and the float
5187// is passed in a floating point register. This is represented as two arguments
5188// with the LLVM IR inreg attribute:
5189//
5190// declare void f(i32 inreg %i, float inreg %f)
5191//
5192// The code generator will only allocate 4 bytes from the parameter array for
5193// the inreg arguments. All other arguments are allocated a multiple of 8
5194// bytes.
5195//
5196namespace {
5197class SparcV9ABIInfo : public ABIInfo {
5198public:
5199 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5200
5201private:
5202 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5203 virtual void computeInfo(CGFunctionInfo &FI) const;
5204 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5205 CodeGenFunction &CGF) const;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005206
5207 // Coercion type builder for structs passed in registers. The coercion type
5208 // serves two purposes:
5209 //
5210 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5211 // in registers.
5212 // 2. Expose aligned floating point elements as first-level elements, so the
5213 // code generator knows to pass them in floating point registers.
5214 //
5215 // We also compute the InReg flag which indicates that the struct contains
5216 // aligned 32-bit floats.
5217 //
5218 struct CoerceBuilder {
5219 llvm::LLVMContext &Context;
5220 const llvm::DataLayout &DL;
5221 SmallVector<llvm::Type*, 8> Elems;
5222 uint64_t Size;
5223 bool InReg;
5224
5225 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5226 : Context(c), DL(dl), Size(0), InReg(false) {}
5227
5228 // Pad Elems with integers until Size is ToSize.
5229 void pad(uint64_t ToSize) {
5230 assert(ToSize >= Size && "Cannot remove elements");
5231 if (ToSize == Size)
5232 return;
5233
5234 // Finish the current 64-bit word.
5235 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5236 if (Aligned > Size && Aligned <= ToSize) {
5237 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5238 Size = Aligned;
5239 }
5240
5241 // Add whole 64-bit words.
5242 while (Size + 64 <= ToSize) {
5243 Elems.push_back(llvm::Type::getInt64Ty(Context));
5244 Size += 64;
5245 }
5246
5247 // Final in-word padding.
5248 if (Size < ToSize) {
5249 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5250 Size = ToSize;
5251 }
5252 }
5253
5254 // Add a floating point element at Offset.
5255 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5256 // Unaligned floats are treated as integers.
5257 if (Offset % Bits)
5258 return;
5259 // The InReg flag is only required if there are any floats < 64 bits.
5260 if (Bits < 64)
5261 InReg = true;
5262 pad(Offset);
5263 Elems.push_back(Ty);
5264 Size = Offset + Bits;
5265 }
5266
5267 // Add a struct type to the coercion type, starting at Offset (in bits).
5268 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5269 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5270 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5271 llvm::Type *ElemTy = StrTy->getElementType(i);
5272 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5273 switch (ElemTy->getTypeID()) {
5274 case llvm::Type::StructTyID:
5275 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5276 break;
5277 case llvm::Type::FloatTyID:
5278 addFloat(ElemOffset, ElemTy, 32);
5279 break;
5280 case llvm::Type::DoubleTyID:
5281 addFloat(ElemOffset, ElemTy, 64);
5282 break;
5283 case llvm::Type::FP128TyID:
5284 addFloat(ElemOffset, ElemTy, 128);
5285 break;
5286 case llvm::Type::PointerTyID:
5287 if (ElemOffset % 64 == 0) {
5288 pad(ElemOffset);
5289 Elems.push_back(ElemTy);
5290 Size += 64;
5291 }
5292 break;
5293 default:
5294 break;
5295 }
5296 }
5297 }
5298
5299 // Check if Ty is a usable substitute for the coercion type.
5300 bool isUsableType(llvm::StructType *Ty) const {
5301 if (Ty->getNumElements() != Elems.size())
5302 return false;
5303 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5304 if (Elems[i] != Ty->getElementType(i))
5305 return false;
5306 return true;
5307 }
5308
5309 // Get the coercion type as a literal struct type.
5310 llvm::Type *getType() const {
5311 if (Elems.size() == 1)
5312 return Elems.front();
5313 else
5314 return llvm::StructType::get(Context, Elems);
5315 }
5316 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005317};
5318} // end anonymous namespace
5319
5320ABIArgInfo
5321SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5322 if (Ty->isVoidType())
5323 return ABIArgInfo::getIgnore();
5324
5325 uint64_t Size = getContext().getTypeSize(Ty);
5326
5327 // Anything too big to fit in registers is passed with an explicit indirect
5328 // pointer / sret pointer.
5329 if (Size > SizeLimit)
5330 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5331
5332 // Treat an enum type as its underlying type.
5333 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5334 Ty = EnumTy->getDecl()->getIntegerType();
5335
5336 // Integer types smaller than a register are extended.
5337 if (Size < 64 && Ty->isIntegerType())
5338 return ABIArgInfo::getExtend();
5339
5340 // Other non-aggregates go in registers.
5341 if (!isAggregateTypeForABI(Ty))
5342 return ABIArgInfo::getDirect();
5343
5344 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005345 // Build a coercion type from the LLVM struct type.
5346 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5347 if (!StrTy)
5348 return ABIArgInfo::getDirect();
5349
5350 CoerceBuilder CB(getVMContext(), getDataLayout());
5351 CB.addStruct(0, StrTy);
5352 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5353
5354 // Try to use the original type for coercion.
5355 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5356
5357 if (CB.InReg)
5358 return ABIArgInfo::getDirectInReg(CoerceTy);
5359 else
5360 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005361}
5362
5363llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5364 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00005365 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5366 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5367 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5368 AI.setCoerceToType(ArgTy);
5369
5370 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5371 CGBuilderTy &Builder = CGF.Builder;
5372 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5373 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5374 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5375 llvm::Value *ArgAddr;
5376 unsigned Stride;
5377
5378 switch (AI.getKind()) {
5379 case ABIArgInfo::Expand:
5380 llvm_unreachable("Unsupported ABI kind for va_arg");
5381
5382 case ABIArgInfo::Extend:
5383 Stride = 8;
5384 ArgAddr = Builder
5385 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5386 "extend");
5387 break;
5388
5389 case ABIArgInfo::Direct:
5390 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5391 ArgAddr = Addr;
5392 break;
5393
5394 case ABIArgInfo::Indirect:
5395 Stride = 8;
5396 ArgAddr = Builder.CreateBitCast(Addr,
5397 llvm::PointerType::getUnqual(ArgPtrTy),
5398 "indirect");
5399 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5400 break;
5401
5402 case ABIArgInfo::Ignore:
5403 return llvm::UndefValue::get(ArgPtrTy);
5404 }
5405
5406 // Update VAList.
5407 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5408 Builder.CreateStore(Addr, VAListAddrAsBPP);
5409
5410 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005411}
5412
5413void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5414 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5415 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5416 it != ie; ++it)
5417 it->info = classifyType(it->type, 16 * 8);
5418}
5419
5420namespace {
5421class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5422public:
5423 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5424 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
5425};
5426} // end anonymous namespace
5427
5428
Robert Lytton0e076492013-08-13 09:43:10 +00005429//===----------------------------------------------------------------------===//
5430// Xcore ABI Implementation
5431//===----------------------------------------------------------------------===//
5432namespace {
Robert Lytton7d1db152013-08-19 09:46:39 +00005433class XCoreABIInfo : public DefaultABIInfo {
5434public:
5435 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
5436 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5437 CodeGenFunction &CGF) const;
5438};
5439
Robert Lytton0e076492013-08-13 09:43:10 +00005440class XcoreTargetCodeGenInfo : public TargetCodeGenInfo {
5441public:
5442 XcoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00005443 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton0e076492013-08-13 09:43:10 +00005444};
Robert Lytton2d196952013-10-11 10:29:34 +00005445} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00005446
Robert Lytton7d1db152013-08-19 09:46:39 +00005447llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5448 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00005449 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00005450
Robert Lytton2d196952013-10-11 10:29:34 +00005451 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00005452 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5453 CGF.Int8PtrPtrTy);
5454 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00005455
Robert Lytton2d196952013-10-11 10:29:34 +00005456 // Handle the argument.
5457 ABIArgInfo AI = classifyArgumentType(Ty);
5458 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5459 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5460 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00005461 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00005462 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00005463 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00005464 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00005465 case ABIArgInfo::Expand:
5466 llvm_unreachable("Unsupported ABI kind for va_arg");
5467 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00005468 Val = llvm::UndefValue::get(ArgPtrTy);
5469 ArgSize = 0;
5470 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005471 case ABIArgInfo::Extend:
5472 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00005473 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5474 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5475 if (ArgSize < 4)
5476 ArgSize = 4;
5477 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005478 case ABIArgInfo::Indirect:
5479 llvm::Value *ArgAddr;
5480 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5481 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00005482 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5483 ArgSize = 4;
5484 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00005485 }
Robert Lytton2d196952013-10-11 10:29:34 +00005486
5487 // Increment the VAList.
5488 if (ArgSize) {
5489 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
5490 Builder.CreateStore(APN, VAListAddrAsBPP);
5491 }
5492 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00005493}
Robert Lytton0e076492013-08-13 09:43:10 +00005494
5495//===----------------------------------------------------------------------===//
5496// Driver code
5497//===----------------------------------------------------------------------===//
5498
Chris Lattner2b037972010-07-29 02:01:43 +00005499const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005500 if (TheTargetCodeGenInfo)
5501 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005502
John McCallc8e01702013-04-16 22:48:15 +00005503 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00005504 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00005505 default:
Chris Lattner2b037972010-07-29 02:01:43 +00005506 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00005507
Derek Schuff09338a22012-09-06 17:37:28 +00005508 case llvm::Triple::le32:
5509 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00005510 case llvm::Triple::mips:
5511 case llvm::Triple::mipsel:
Akira Hatanaka618b2982013-10-29 19:00:35 +00005512 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true,
5513 getTarget()));
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00005514 case llvm::Triple::mips64:
5515 case llvm::Triple::mips64el:
Akira Hatanaka618b2982013-10-29 19:00:35 +00005516 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false,
5517 getTarget()));
Tim Northover9bb857a2013-01-31 12:13:10 +00005518 case llvm::Triple::aarch64:
5519 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5520
Daniel Dunbard59655c2009-09-12 00:59:49 +00005521 case llvm::Triple::arm:
5522 case llvm::Triple::thumb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005523 {
5524 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCallc8e01702013-04-16 22:48:15 +00005525 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005526 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00005527 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00005528 (CodeGenOpts.FloatABI != "soft" &&
5529 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005530 Kind = ARMABIInfo::AAPCS_VFP;
5531
Derek Schuffa2020962012-10-16 22:30:41 +00005532 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00005533 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00005534 return *(TheTargetCodeGenInfo =
5535 new NaClARMTargetCodeGenInfo(Types, Kind));
5536 default:
5537 return *(TheTargetCodeGenInfo =
5538 new ARMTargetCodeGenInfo(Types, Kind));
5539 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00005540 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00005541
John McCallea8d8bb2010-03-11 00:10:12 +00005542 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00005543 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00005544 case llvm::Triple::ppc64:
Bill Schmidt25cb3492012-10-03 19:18:57 +00005545 if (Triple.isOSBinFormatELF())
5546 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5547 else
5548 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidt778d3872013-07-26 01:36:11 +00005549 case llvm::Triple::ppc64le:
5550 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5551 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallea8d8bb2010-03-11 00:10:12 +00005552
Peter Collingbournec947aae2012-05-20 23:28:41 +00005553 case llvm::Triple::nvptx:
5554 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00005555 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005556
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005557 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00005558 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00005559
Ulrich Weigand47445072013-05-06 16:26:41 +00005560 case llvm::Triple::systemz:
5561 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5562
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005563 case llvm::Triple::tce:
5564 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5565
Eli Friedman33465822011-07-08 23:31:17 +00005566 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00005567 bool IsDarwinVectorABI = Triple.isOSDarwin();
5568 bool IsSmallStructInRegABI =
5569 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5570 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005571
John McCall1fe2a8c2013-06-18 02:46:29 +00005572 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00005573 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005574 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00005575 IsDarwinVectorABI, IsSmallStructInRegABI,
5576 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00005577 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00005578 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005579 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00005580 new X86_32TargetCodeGenInfo(Types,
5581 IsDarwinVectorABI, IsSmallStructInRegABI,
5582 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00005583 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005584 }
Eli Friedman33465822011-07-08 23:31:17 +00005585 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005586
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005587 case llvm::Triple::x86_64: {
John McCallc8e01702013-04-16 22:48:15 +00005588 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005589
Chris Lattner04dc9572010-08-31 16:44:54 +00005590 switch (Triple.getOS()) {
5591 case llvm::Triple::Win32:
NAKAMURA Takumi31ea2f12011-02-17 08:51:38 +00005592 case llvm::Triple::MinGW32:
Chris Lattner04dc9572010-08-31 16:44:54 +00005593 case llvm::Triple::Cygwin:
5594 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00005595 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00005596 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5597 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005598 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005599 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5600 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00005601 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00005602 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00005603 case llvm::Triple::hexagon:
5604 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005605 case llvm::Triple::sparcv9:
5606 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00005607 case llvm::Triple::xcore:
5608 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types));
5609
Eli Friedmanbfd5add2011-12-02 00:11:43 +00005610 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005611}