blob: 27e8e2a0f040b6a9d7120ec2415237393d4b4c8f [file] [log] [blame]
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikovc4a59eb2009-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 Korobeynikov82d0a412010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000018#include "CodeGenFunction.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Sandeep Patel34c1af82011-04-05 00:23:47 +000020#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar2c0843f2009-08-24 08:52:16 +000021#include "llvm/ADT/Triple.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Type.h"
Daniel Dunbar28df7a52009-12-03 09:13:49 +000024#include "llvm/Support/raw_ostream.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000025using namespace clang;
26using namespace CodeGen;
27
John McCallaeeb7012010-05-27 06:19:26 +000028static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
29 llvm::Value *Array,
30 llvm::Value *Value,
31 unsigned FirstIndex,
32 unsigned LastIndex) {
33 // Alternatively, we could emit this as a loop in the source.
34 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
35 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
36 Builder.CreateStore(Value, Cell);
37 }
38}
39
John McCalld608cdb2010-08-22 10:59:02 +000040static bool isAggregateTypeForABI(QualType T) {
John McCall9d232c82013-03-07 21:37:08 +000041 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalld608cdb2010-08-22 10:59:02 +000042 T->isMemberFunctionPointerType();
43}
44
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000045ABIInfo::~ABIInfo() {}
46
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000047static bool isRecordReturnIndirect(const RecordType *RT, CodeGen::CodeGenTypes &CGT) {
48 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
49 if (!RD)
50 return false;
Mark Lacey25296602013-10-02 20:35:23 +000051 return CGT.getCXXABI().isReturnTypeIndirect(RD);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000052}
53
54
55static bool isRecordReturnIndirect(QualType T, CodeGen::CodeGenTypes &CGT) {
56 const RecordType *RT = T->getAs<RecordType>();
57 if (!RT)
58 return false;
59 return isRecordReturnIndirect(RT, CGT);
60}
61
62static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
63 CodeGen::CodeGenTypes &CGT) {
64 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
65 if (!RD)
66 return CGCXXABI::RAA_Default;
Mark Lacey25296602013-10-02 20:35:23 +000067 return CGT.getCXXABI().getRecordArgABI(RD);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000068}
69
70static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
71 CodeGen::CodeGenTypes &CGT) {
72 const RecordType *RT = T->getAs<RecordType>();
73 if (!RT)
74 return CGCXXABI::RAA_Default;
75 return getRecordArgABI(RT, CGT);
76}
77
Chris Lattnerea044322010-07-29 02:01:43 +000078ASTContext &ABIInfo::getContext() const {
79 return CGT.getContext();
80}
81
82llvm::LLVMContext &ABIInfo::getVMContext() const {
83 return CGT.getLLVMContext();
84}
85
Micah Villmow25a6a842012-10-08 16:25:52 +000086const llvm::DataLayout &ABIInfo::getDataLayout() const {
87 return CGT.getDataLayout();
Chris Lattnerea044322010-07-29 02:01:43 +000088}
89
John McCall64aa4b32013-04-16 22:48:15 +000090const TargetInfo &ABIInfo::getTarget() const {
91 return CGT.getTarget();
92}
Chris Lattnerea044322010-07-29 02:01:43 +000093
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000094void ABIArgInfo::dump() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +000095 raw_ostream &OS = llvm::errs();
Daniel Dunbar28df7a52009-12-03 09:13:49 +000096 OS << "(ABIArgInfo Kind=";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000097 switch (TheKind) {
98 case Direct:
Chris Lattner800588f2010-07-29 06:26:06 +000099 OS << "Direct Type=";
Chris Lattner2acc6e32011-07-18 04:24:23 +0000100 if (llvm::Type *Ty = getCoerceToType())
Chris Lattner800588f2010-07-29 06:26:06 +0000101 Ty->print(OS);
102 else
103 OS << "null";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000104 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000105 case Extend:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000106 OS << "Extend";
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000107 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000108 case Ignore:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000109 OS << "Ignore";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000110 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000111 case Indirect:
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000112 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenbergere9b5d772011-07-15 18:23:44 +0000113 << " ByVal=" << getIndirectByVal()
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000114 << " Realign=" << getIndirectRealign();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000115 break;
116 case Expand:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000117 OS << "Expand";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000118 break;
119 }
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000120 OS << ")\n";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000121}
122
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000123TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
124
John McCall49e34be2011-08-30 01:42:09 +0000125// If someone can figure out a general rule for this, that would be great.
126// It's probably just doomed to be platform-dependent, though.
127unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
128 // Verified for:
129 // x86-64 FreeBSD, Linux, Darwin
130 // x86-32 FreeBSD, Linux, Darwin
131 // PowerPC Linux, Darwin
132 // ARM Darwin (*not* EABI)
Tim Northoverc264e162013-01-31 12:13:10 +0000133 // AArch64 Linux
John McCall49e34be2011-08-30 01:42:09 +0000134 return 32;
135}
136
John McCallde5d3c72012-02-17 03:33:10 +0000137bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
138 const FunctionNoProtoType *fnType) const {
John McCall01f151e2011-09-21 08:08:30 +0000139 // The following conventions are known to require this to be false:
140 // x86_stdcall
141 // MIPS
142 // For everything else, we just prefer false unless we opt out.
143 return false;
144}
145
Reid Kleckner3190ca92013-05-08 13:44:39 +0000146void
147TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
148 llvm::SmallString<24> &Opt) const {
149 // This assumes the user is passing a library name like "rt" instead of a
150 // filename like "librt.a/so", and that they don't care whether it's static or
151 // dynamic.
152 Opt = "-l";
153 Opt += Lib;
154}
155
Daniel Dunbar98303b92009-09-13 08:03:58 +0000156static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000157
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000158/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000159/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar98303b92009-09-13 08:03:58 +0000160static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
161 bool AllowArrays) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000162 if (FD->isUnnamedBitfield())
163 return true;
164
165 QualType FT = FD->getType();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000166
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000167 // Constant arrays of empty records count as empty, strip them off.
168 // Constant arrays of zero length always count as empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000169 if (AllowArrays)
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000170 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
171 if (AT->getSize() == 0)
172 return true;
Daniel Dunbar98303b92009-09-13 08:03:58 +0000173 FT = AT->getElementType();
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000174 }
Daniel Dunbar98303b92009-09-13 08:03:58 +0000175
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000176 const RecordType *RT = FT->getAs<RecordType>();
177 if (!RT)
178 return false;
179
180 // C++ record fields are never empty, at least in the Itanium ABI.
181 //
182 // FIXME: We should use a predicate for whether this behavior is true in the
183 // current ABI.
184 if (isa<CXXRecordDecl>(RT->getDecl()))
185 return false;
186
Daniel Dunbar98303b92009-09-13 08:03:58 +0000187 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000188}
189
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000190/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000191/// fields. Note that a structure with a flexible array member is not
192/// considered empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000193static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000194 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000195 if (!RT)
196 return 0;
197 const RecordDecl *RD = RT->getDecl();
198 if (RD->hasFlexibleArrayMember())
199 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000200
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000201 // If this is a C++ record, check the bases first.
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000202 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000203 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
204 e = CXXRD->bases_end(); i != e; ++i)
205 if (!isEmptyRecord(Context, i->getType(), true))
206 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000207
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000208 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
209 i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000210 if (!isEmptyField(Context, *i, AllowArrays))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000211 return false;
212 return true;
213}
214
215/// isSingleElementStruct - Determine if a structure is a "single
216/// element struct", i.e. it has exactly one non-empty field or
217/// exactly one field which is itself a single element
218/// struct. Structures with flexible array members are never
219/// considered single element structs.
220///
221/// \return The field declaration for the single non-empty field, if
222/// it exists.
223static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
224 const RecordType *RT = T->getAsStructureType();
225 if (!RT)
226 return 0;
227
228 const RecordDecl *RD = RT->getDecl();
229 if (RD->hasFlexibleArrayMember())
230 return 0;
231
232 const Type *Found = 0;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000233
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000234 // If this is a C++ record, check the bases first.
235 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
236 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
237 e = CXXRD->bases_end(); i != e; ++i) {
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000238 // Ignore empty records.
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000239 if (isEmptyRecord(Context, i->getType(), true))
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000240 continue;
241
242 // If we already found an element then this isn't a single-element struct.
243 if (Found)
244 return 0;
245
246 // If this is non-empty and not a single element struct, the composite
247 // cannot be a single element struct.
248 Found = isSingleElementStruct(i->getType(), Context);
249 if (!Found)
250 return 0;
251 }
252 }
253
254 // Check for single element.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000255 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
256 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000257 const FieldDecl *FD = *i;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000258 QualType FT = FD->getType();
259
260 // Ignore empty fields.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000261 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000262 continue;
263
264 // If we already found an element then this isn't a single-element
265 // struct.
266 if (Found)
267 return 0;
268
269 // Treat single element arrays as the element.
270 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
271 if (AT->getSize().getZExtValue() != 1)
272 break;
273 FT = AT->getElementType();
274 }
275
John McCalld608cdb2010-08-22 10:59:02 +0000276 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000277 Found = FT.getTypePtr();
278 } else {
279 Found = isSingleElementStruct(FT, Context);
280 if (!Found)
281 return 0;
282 }
283 }
284
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000285 // We don't consider a struct a single-element struct if it has
286 // padding beyond the element type.
287 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
288 return 0;
289
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000290 return Found;
291}
292
293static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmandb748a32012-11-29 23:21:04 +0000294 // Treat complex types as the element type.
295 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
296 Ty = CTy->getElementType();
297
298 // Check for a type which we know has a simple scalar argument-passing
299 // convention without any padding. (We're specifically looking for 32
300 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbara1842d32010-05-14 03:40:53 +0000301 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmandb748a32012-11-29 23:21:04 +0000302 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000303 return false;
304
305 uint64_t Size = Context.getTypeSize(Ty);
306 return Size == 32 || Size == 64;
307}
308
Daniel Dunbar53012f42009-11-09 01:33:53 +0000309/// canExpandIndirectArgument - Test whether an argument type which is to be
310/// passed indirectly (on the stack) would have the equivalent layout if it was
311/// expanded into separate arguments. If so, we prefer to do the latter to avoid
312/// inhibiting optimizations.
313///
314// FIXME: This predicate is missing many cases, currently it just follows
315// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
316// should probably make this smarter, or better yet make the LLVM backend
317// capable of handling it.
318static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
319 // We can only expand structure types.
320 const RecordType *RT = Ty->getAs<RecordType>();
321 if (!RT)
322 return false;
323
324 // We can only expand (C) structures.
325 //
326 // FIXME: This needs to be generalized to handle classes as well.
327 const RecordDecl *RD = RT->getDecl();
328 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
329 return false;
330
Eli Friedman506d4e32011-11-18 01:32:26 +0000331 uint64_t Size = 0;
332
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000333 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
334 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000335 const FieldDecl *FD = *i;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000336
337 if (!is32Or64BitBasicType(FD->getType(), Context))
338 return false;
339
340 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
341 // how to expand them yet, and the predicate for telling if a bitfield still
342 // counts as "basic" is more complicated than what we were doing previously.
343 if (FD->isBitField())
344 return false;
Eli Friedman506d4e32011-11-18 01:32:26 +0000345
346 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000347 }
348
Eli Friedman506d4e32011-11-18 01:32:26 +0000349 // Make sure there are not any holes in the struct.
350 if (Size != Context.getTypeSize(Ty))
351 return false;
352
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000353 return true;
354}
355
356namespace {
357/// DefaultABIInfo - The default implementation for ABI specific
358/// details. This implementation provides information which results in
359/// self-consistent and sensible LLVM IR generation, but does not
360/// conform to any particular ABI.
361class DefaultABIInfo : public ABIInfo {
Chris Lattnerea044322010-07-29 02:01:43 +0000362public:
363 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000364
Chris Lattnera3c109b2010-07-29 02:16:43 +0000365 ABIArgInfo classifyReturnType(QualType RetTy) const;
366 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000367
Chris Lattneree5dcd02010-07-29 02:31:05 +0000368 virtual void computeInfo(CGFunctionInfo &FI) const {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000369 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000370 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
371 it != ie; ++it)
Chris Lattnera3c109b2010-07-29 02:16:43 +0000372 it->info = classifyArgumentType(it->type);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000373 }
374
375 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
376 CodeGenFunction &CGF) const;
377};
378
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000379class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
380public:
Chris Lattnerea044322010-07-29 02:01:43 +0000381 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
382 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000383};
384
385llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
386 CodeGenFunction &CGF) const {
387 return 0;
388}
389
Chris Lattnera3c109b2010-07-29 02:16:43 +0000390ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Jan Wen Voung90306932011-11-03 00:59:44 +0000391 if (isAggregateTypeForABI(Ty)) {
392 // Records with non trivial destructors/constructors should not be passed
393 // by value.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000394 if (isRecordReturnIndirect(Ty, CGT))
Jan Wen Voung90306932011-11-03 00:59:44 +0000395 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
396
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000397 return ABIArgInfo::getIndirect(0);
Jan Wen Voung90306932011-11-03 00:59:44 +0000398 }
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000399
Chris Lattnera14db752010-03-11 18:19:55 +0000400 // Treat an enum type as its underlying type.
401 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
402 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000403
Chris Lattnera14db752010-03-11 18:19:55 +0000404 return (Ty->isPromotableIntegerType() ?
405 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000406}
407
Bob Wilson0024f942011-01-10 23:54:17 +0000408ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
409 if (RetTy->isVoidType())
410 return ABIArgInfo::getIgnore();
411
412 if (isAggregateTypeForABI(RetTy))
413 return ABIArgInfo::getIndirect(0);
414
415 // Treat an enum type as its underlying type.
416 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
417 RetTy = EnumTy->getDecl()->getIntegerType();
418
419 return (RetTy->isPromotableIntegerType() ?
420 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
421}
422
Derek Schuff9ed63f82012-09-06 17:37:28 +0000423//===----------------------------------------------------------------------===//
424// le32/PNaCl bitcode ABI Implementation
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000425//
426// This is a simplified version of the x86_32 ABI. Arguments and return values
427// are always passed on the stack.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000428//===----------------------------------------------------------------------===//
429
430class PNaClABIInfo : public ABIInfo {
431 public:
432 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
433
434 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000435 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff9ed63f82012-09-06 17:37:28 +0000436
437 virtual void computeInfo(CGFunctionInfo &FI) const;
438 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
439 CodeGenFunction &CGF) const;
440};
441
442class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
443 public:
444 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
445 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
446};
447
448void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
449 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
450
Derek Schuff9ed63f82012-09-06 17:37:28 +0000451 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
452 it != ie; ++it)
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000453 it->info = classifyArgumentType(it->type);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000454 }
455
456llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
457 CodeGenFunction &CGF) const {
458 return 0;
459}
460
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000461/// \brief Classify argument of given type \p Ty.
462ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff9ed63f82012-09-06 17:37:28 +0000463 if (isAggregateTypeForABI(Ty)) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000464 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
465 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000466 return ABIArgInfo::getIndirect(0);
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000467 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
468 // Treat an enum type as its underlying type.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000469 Ty = EnumTy->getDecl()->getIntegerType();
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000470 } else if (Ty->isFloatingType()) {
471 // Floating-point types don't go inreg.
472 return ABIArgInfo::getDirect();
Derek Schuff9ed63f82012-09-06 17:37:28 +0000473 }
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000474
475 return (Ty->isPromotableIntegerType() ?
476 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff9ed63f82012-09-06 17:37:28 +0000477}
478
479ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
480 if (RetTy->isVoidType())
481 return ABIArgInfo::getIgnore();
482
Eli Benderskye45dfd12013-04-04 22:49:35 +0000483 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000484 if (isAggregateTypeForABI(RetTy))
485 return ABIArgInfo::getIndirect(0);
486
487 // Treat an enum type as its underlying type.
488 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
489 RetTy = EnumTy->getDecl()->getIntegerType();
490
491 return (RetTy->isPromotableIntegerType() ?
492 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
493}
494
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000495/// IsX86_MMXType - Return true if this is an MMX type.
496bool IsX86_MMXType(llvm::Type *IRType) {
497 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendlingbb465d72010-10-18 03:41:31 +0000498 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
499 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
500 IRType->getScalarSizeInBits() != 64;
501}
502
Jay Foadef6de3d2011-07-11 09:56:20 +0000503static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000504 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000505 llvm::Type* Ty) {
Tim Northover1bea6532013-06-07 00:04:50 +0000506 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
507 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
508 // Invalid MMX constraint
509 return 0;
510 }
511
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000512 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover1bea6532013-06-07 00:04:50 +0000513 }
514
515 // No operation needed
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000516 return Ty;
517}
518
Chris Lattnerdce5ad02010-06-28 20:05:43 +0000519//===----------------------------------------------------------------------===//
520// X86-32 ABI Implementation
521//===----------------------------------------------------------------------===//
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000522
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000523/// X86_32ABIInfo - The X86-32 ABI information.
524class X86_32ABIInfo : public ABIInfo {
Rafael Espindolab48280b2012-07-31 02:44:24 +0000525 enum Class {
526 Integer,
527 Float
528 };
529
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000530 static const unsigned MinABIStackAlignInBytes = 4;
531
David Chisnall1e4249c2009-08-17 23:08:21 +0000532 bool IsDarwinVectorABI;
533 bool IsSmallStructInRegABI;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000534 bool IsWin32StructABI;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000535 unsigned DefaultNumRegisterParameters;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000536
537 static bool isRegisterSize(unsigned Size) {
538 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
539 }
540
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000541 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
542 unsigned callingConvention);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000543
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000544 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
545 /// such that the argument will be passed in memory.
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000546 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal,
547 unsigned &FreeRegs) const;
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000548
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000549 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbare59d8582010-09-16 20:42:06 +0000550 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000551
Rafael Espindolab48280b2012-07-31 02:44:24 +0000552 Class classify(QualType Ty) const;
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000553 ABIArgInfo classifyReturnType(QualType RetTy,
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000554 unsigned callingConvention) const;
Rafael Espindolab6932692012-10-24 01:58:58 +0000555 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs,
556 bool IsFastCall) const;
557 bool shouldUseInReg(QualType Ty, unsigned &FreeRegs,
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000558 bool IsFastCall, bool &NeedsPadding) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000559
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000560public:
561
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000562 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000563 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
564 CodeGenFunction &CGF) const;
565
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000566 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindolab48280b2012-07-31 02:44:24 +0000567 unsigned r)
Eli Friedmanc3e0fb42011-07-08 23:31:17 +0000568 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000569 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000570};
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000571
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000572class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
573public:
Eli Friedman55fc7e22012-01-25 22:46:34 +0000574 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000575 bool d, bool p, bool w, unsigned r)
576 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis74f72932010-02-13 15:54:06 +0000577
John McCallb8b52972013-06-18 02:46:29 +0000578 static bool isStructReturnInRegABI(
579 const llvm::Triple &Triple, const CodeGenOptions &Opts);
580
Charles Davis74f72932010-02-13 15:54:06 +0000581 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
582 CodeGen::CodeGenModule &CGM) const;
John McCall6374c332010-03-06 00:35:14 +0000583
584 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
585 // Darwin uses different dwarf register numbers for EH.
John McCall64aa4b32013-04-16 22:48:15 +0000586 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCall6374c332010-03-06 00:35:14 +0000587 return 4;
588 }
589
590 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
591 llvm::Value *Address) const;
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000592
Jay Foadef6de3d2011-07-11 09:56:20 +0000593 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000594 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000595 llvm::Type* Ty) const {
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000596 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
597 }
598
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000599};
600
601}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000602
603/// shouldReturnTypeInRegister - Determine if the given type should be
604/// passed in a register (for the Darwin ABI).
605bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000606 ASTContext &Context,
607 unsigned callingConvention) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000608 uint64_t Size = Context.getTypeSize(Ty);
609
610 // Type must be register sized.
611 if (!isRegisterSize(Size))
612 return false;
613
614 if (Ty->isVectorType()) {
615 // 64- and 128- bit vectors inside structures are not returned in
616 // registers.
617 if (Size == 64 || Size == 128)
618 return false;
619
620 return true;
621 }
622
Daniel Dunbar77115232010-05-15 00:00:30 +0000623 // If this is a builtin, pointer, enum, complex type, member pointer, or
624 // member function pointer it is ok.
Daniel Dunbara1842d32010-05-14 03:40:53 +0000625 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbar55e59e12009-09-24 05:12:36 +0000626 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar77115232010-05-15 00:00:30 +0000627 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000628 return true;
629
630 // Arrays are treated like records.
631 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000632 return shouldReturnTypeInRegister(AT->getElementType(), Context,
633 callingConvention);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000634
635 // Otherwise, it must be a record type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000636 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000637 if (!RT) return false;
638
Anders Carlssona8874232010-01-27 03:25:19 +0000639 // FIXME: Traverse bases here too.
640
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000641 // For thiscall conventions, structures will never be returned in
642 // a register. This is for compatibility with the MSVC ABI
643 if (callingConvention == llvm::CallingConv::X86_ThisCall &&
644 RT->isStructureType()) {
645 return false;
646 }
647
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000648 // Structure types are passed in register if all fields would be
649 // passed in a register.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000650 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
651 e = RT->getDecl()->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000652 const FieldDecl *FD = *i;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000653
654 // Empty fields are ignored.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000655 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000656 continue;
657
658 // Check fields recursively.
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000659 if (!shouldReturnTypeInRegister(FD->getType(), Context,
660 callingConvention))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000661 return false;
662 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000663 return true;
664}
665
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000666ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
667 unsigned callingConvention) const {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000668 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000669 return ABIArgInfo::getIgnore();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000670
Chris Lattnera3c109b2010-07-29 02:16:43 +0000671 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000672 // On Darwin, some vectors are returned in registers.
David Chisnall1e4249c2009-08-17 23:08:21 +0000673 if (IsDarwinVectorABI) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000674 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000675
676 // 128-bit vectors are a special case; they are returned in
677 // registers and we need to make sure to pick a type the LLVM
678 // backend will like.
679 if (Size == 128)
Chris Lattner800588f2010-07-29 06:26:06 +0000680 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattnera3c109b2010-07-29 02:16:43 +0000681 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000682
683 // Always return in register if it fits in a general purpose
684 // register, or if it is 64 bits and has a single element.
685 if ((Size == 8 || Size == 16 || Size == 32) ||
686 (Size == 64 && VT->getNumElements() == 1))
Chris Lattner800588f2010-07-29 06:26:06 +0000687 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +0000688 Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000689
690 return ABIArgInfo::getIndirect(0);
691 }
692
693 return ABIArgInfo::getDirect();
Chris Lattnera3c109b2010-07-29 02:16:43 +0000694 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000695
John McCalld608cdb2010-08-22 10:59:02 +0000696 if (isAggregateTypeForABI(RetTy)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000697 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000698 if (isRecordReturnIndirect(RT, CGT))
Anders Carlsson40092972009-10-20 22:07:59 +0000699 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000700
Anders Carlsson40092972009-10-20 22:07:59 +0000701 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000702 if (RT->getDecl()->hasFlexibleArrayMember())
703 return ABIArgInfo::getIndirect(0);
Anders Carlsson40092972009-10-20 22:07:59 +0000704 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000705
David Chisnall1e4249c2009-08-17 23:08:21 +0000706 // If specified, structs and unions are always indirect.
707 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000708 return ABIArgInfo::getIndirect(0);
709
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000710 // Small structures which are register sized are generally returned
711 // in a register.
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000712 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(),
713 callingConvention)) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000714 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000715
716 // As a special-case, if the struct is a "single-element" struct, and
717 // the field is of type "float" or "double", return it in a
Eli Friedman55fc7e22012-01-25 22:46:34 +0000718 // floating-point register. (MSVC does not apply this special case.)
719 // We apply a similar transformation for pointer types to improve the
720 // quality of the generated IR.
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000721 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000722 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedman55fc7e22012-01-25 22:46:34 +0000723 || SeltTy->hasPointerRepresentation())
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000724 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
725
726 // FIXME: We should be able to narrow this integer in cases with dead
727 // padding.
Chris Lattner800588f2010-07-29 06:26:06 +0000728 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000729 }
730
731 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000732 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000733
Chris Lattnera3c109b2010-07-29 02:16:43 +0000734 // Treat an enum type as its underlying type.
735 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
736 RetTy = EnumTy->getDecl()->getIntegerType();
737
738 return (RetTy->isPromotableIntegerType() ?
739 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000740}
741
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000742static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
743 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
744}
745
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000746static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
747 const RecordType *RT = Ty->getAs<RecordType>();
748 if (!RT)
749 return 0;
750 const RecordDecl *RD = RT->getDecl();
751
752 // If this is a C++ record, check the bases first.
753 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
754 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
755 e = CXXRD->bases_end(); i != e; ++i)
756 if (!isRecordWithSSEVectorType(Context, i->getType()))
757 return false;
758
759 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
760 i != e; ++i) {
761 QualType FT = i->getType();
762
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000763 if (isSSEVectorType(Context, FT))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000764 return true;
765
766 if (isRecordWithSSEVectorType(Context, FT))
767 return true;
768 }
769
770 return false;
771}
772
Daniel Dunbare59d8582010-09-16 20:42:06 +0000773unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
774 unsigned Align) const {
775 // Otherwise, if the alignment is less than or equal to the minimum ABI
776 // alignment, just use the default; the backend will handle this.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000777 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbare59d8582010-09-16 20:42:06 +0000778 return 0; // Use default alignment.
779
780 // On non-Darwin, the stack type alignment is always 4.
781 if (!IsDarwinVectorABI) {
782 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000783 return MinABIStackAlignInBytes;
Daniel Dunbare59d8582010-09-16 20:42:06 +0000784 }
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000785
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000786 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000787 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
788 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000789 return 16;
790
791 return MinABIStackAlignInBytes;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000792}
793
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000794ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
795 unsigned &FreeRegs) const {
796 if (!ByVal) {
797 if (FreeRegs) {
798 --FreeRegs; // Non byval indirects just use one pointer.
799 return ABIArgInfo::getIndirectInReg(0, false);
800 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000801 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000802 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000803
Daniel Dunbare59d8582010-09-16 20:42:06 +0000804 // Compute the byval alignment.
805 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
806 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
807 if (StackAlign == 0)
Chris Lattnerde92d732011-05-22 23:35:00 +0000808 return ABIArgInfo::getIndirect(4);
Daniel Dunbare59d8582010-09-16 20:42:06 +0000809
810 // If the stack alignment is less than the type alignment, realign the
811 // argument.
812 if (StackAlign < TypeAlign)
813 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
814 /*Realign=*/true);
815
816 return ABIArgInfo::getIndirect(StackAlign);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000817}
818
Rafael Espindolab48280b2012-07-31 02:44:24 +0000819X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
820 const Type *T = isSingleElementStruct(Ty, getContext());
821 if (!T)
822 T = Ty.getTypePtr();
823
824 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
825 BuiltinType::Kind K = BT->getKind();
826 if (K == BuiltinType::Float || K == BuiltinType::Double)
827 return Float;
828 }
829 return Integer;
830}
831
Rafael Espindolab6932692012-10-24 01:58:58 +0000832bool X86_32ABIInfo::shouldUseInReg(QualType Ty, unsigned &FreeRegs,
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000833 bool IsFastCall, bool &NeedsPadding) const {
834 NeedsPadding = false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000835 Class C = classify(Ty);
836 if (C == Float)
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000837 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000838
Rafael Espindolab6932692012-10-24 01:58:58 +0000839 unsigned Size = getContext().getTypeSize(Ty);
840 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindola5f14fcb2012-10-23 02:04:01 +0000841
842 if (SizeInRegs == 0)
843 return false;
844
Rafael Espindolab48280b2012-07-31 02:44:24 +0000845 if (SizeInRegs > FreeRegs) {
846 FreeRegs = 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000847 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000848 }
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000849
Rafael Espindolab48280b2012-07-31 02:44:24 +0000850 FreeRegs -= SizeInRegs;
Rafael Espindolab6932692012-10-24 01:58:58 +0000851
852 if (IsFastCall) {
853 if (Size > 32)
854 return false;
855
856 if (Ty->isIntegralOrEnumerationType())
857 return true;
858
859 if (Ty->isPointerType())
860 return true;
861
862 if (Ty->isReferenceType())
863 return true;
864
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000865 if (FreeRegs)
866 NeedsPadding = true;
867
Rafael Espindolab6932692012-10-24 01:58:58 +0000868 return false;
869 }
870
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000871 return true;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000872}
873
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000874ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Rafael Espindolab6932692012-10-24 01:58:58 +0000875 unsigned &FreeRegs,
876 bool IsFastCall) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000877 // FIXME: Set alignment on indirect arguments.
John McCalld608cdb2010-08-22 10:59:02 +0000878 if (isAggregateTypeForABI(Ty)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000879 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000880 if (IsWin32StructABI)
881 return getIndirectResult(Ty, true, FreeRegs);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000882
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000883 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, CGT))
884 return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory, FreeRegs);
885
886 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000887 if (RT->getDecl()->hasFlexibleArrayMember())
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000888 return getIndirectResult(Ty, true, FreeRegs);
Anders Carlssona8874232010-01-27 03:25:19 +0000889 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000890
Eli Friedman5a4d3522011-11-18 00:28:11 +0000891 // Ignore empty structs/unions.
Eli Friedman5a1ac892011-11-18 04:01:36 +0000892 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000893 return ABIArgInfo::getIgnore();
894
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000895 llvm::LLVMContext &LLVMContext = getVMContext();
896 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
897 bool NeedsPadding;
898 if (shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding)) {
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000899 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperb9bad792013-07-08 04:47:18 +0000900 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000901 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
902 return ABIArgInfo::getDirectInReg(Result);
903 }
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000904 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000905
Daniel Dunbar53012f42009-11-09 01:33:53 +0000906 // Expand small (<= 128-bit) record types when we know that the stack layout
907 // of those arguments will match the struct. This is important because the
908 // LLVM backend isn't smart enough to remove byval, which inhibits many
909 // optimizations.
Chris Lattnera3c109b2010-07-29 02:16:43 +0000910 if (getContext().getTypeSize(Ty) <= 4*32 &&
911 canExpandIndirectArgument(Ty, getContext()))
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000912 return ABIArgInfo::getExpandWithPadding(IsFastCall, PaddingType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000913
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000914 return getIndirectResult(Ty, true, FreeRegs);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000915 }
916
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000917 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner7b733502010-08-26 20:08:43 +0000918 // On Darwin, some vectors are passed in memory, we handle this by passing
919 // it as an i8/i16/i32/i64.
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000920 if (IsDarwinVectorABI) {
921 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000922 if ((Size == 8 || Size == 16 || Size == 32) ||
923 (Size == 64 && VT->getNumElements() == 1))
924 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
925 Size));
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000926 }
Bill Wendlingbb465d72010-10-18 03:41:31 +0000927
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000928 if (IsX86_MMXType(CGT.ConvertType(Ty)))
929 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000930
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000931 return ABIArgInfo::getDirect();
932 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000933
934
Chris Lattnera3c109b2010-07-29 02:16:43 +0000935 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
936 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000937
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000938 bool NeedsPadding;
939 bool InReg = shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000940
941 if (Ty->isPromotableIntegerType()) {
942 if (InReg)
943 return ABIArgInfo::getExtendInReg();
944 return ABIArgInfo::getExtend();
945 }
946 if (InReg)
947 return ABIArgInfo::getDirectInReg();
948 return ABIArgInfo::getDirect();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000949}
950
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000951void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
952 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
953 FI.getCallingConvention());
Rafael Espindolab48280b2012-07-31 02:44:24 +0000954
Rafael Espindolab6932692012-10-24 01:58:58 +0000955 unsigned CC = FI.getCallingConvention();
956 bool IsFastCall = CC == llvm::CallingConv::X86_FastCall;
957 unsigned FreeRegs;
958 if (IsFastCall)
959 FreeRegs = 2;
960 else if (FI.getHasRegParm())
961 FreeRegs = FI.getRegParm();
962 else
963 FreeRegs = DefaultNumRegisterParameters;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000964
965 // If the return value is indirect, then the hidden argument is consuming one
966 // integer register.
967 if (FI.getReturnInfo().isIndirect() && FreeRegs) {
968 --FreeRegs;
969 ABIArgInfo &Old = FI.getReturnInfo();
970 Old = ABIArgInfo::getIndirectInReg(Old.getIndirectAlign(),
971 Old.getIndirectByVal(),
972 Old.getIndirectRealign());
973 }
974
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000975 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
976 it != ie; ++it)
Rafael Espindolab6932692012-10-24 01:58:58 +0000977 it->info = classifyArgumentType(it->type, FreeRegs, IsFastCall);
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000978}
979
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000980llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
981 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +0000982 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000983
984 CGBuilderTy &Builder = CGF.Builder;
985 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
986 "ap");
987 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman7b1fb812011-11-18 02:12:09 +0000988
989 // Compute if the address needs to be aligned
990 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
991 Align = getTypeStackAlignInBytes(Ty, Align);
992 Align = std::max(Align, 4U);
993 if (Align > 4) {
994 // addr = (addr + align - 1) & -align;
995 llvm::Value *Offset =
996 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
997 Addr = CGF.Builder.CreateGEP(Addr, Offset);
998 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
999 CGF.Int32Ty);
1000 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1001 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1002 Addr->getType(),
1003 "ap.cur.aligned");
1004 }
1005
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001006 llvm::Type *PTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001007 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001008 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1009
1010 uint64_t Offset =
Eli Friedman7b1fb812011-11-18 02:12:09 +00001011 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001012 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00001013 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001014 "ap.next");
1015 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1016
1017 return AddrTyped;
1018}
1019
Charles Davis74f72932010-02-13 15:54:06 +00001020void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1021 llvm::GlobalValue *GV,
1022 CodeGen::CodeGenModule &CGM) const {
1023 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1024 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1025 // Get the LLVM function.
1026 llvm::Function *Fn = cast<llvm::Function>(GV);
1027
1028 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendling0d583392012-10-15 20:36:26 +00001029 llvm::AttrBuilder B;
Bill Wendlinge91e9ec2012-10-14 03:28:14 +00001030 B.addStackAlignmentAttr(16);
Bill Wendling909b6de2013-01-23 00:21:06 +00001031 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1032 llvm::AttributeSet::get(CGM.getLLVMContext(),
1033 llvm::AttributeSet::FunctionIndex,
1034 B));
Charles Davis74f72932010-02-13 15:54:06 +00001035 }
1036 }
1037}
1038
John McCall6374c332010-03-06 00:35:14 +00001039bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1040 CodeGen::CodeGenFunction &CGF,
1041 llvm::Value *Address) const {
1042 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCall6374c332010-03-06 00:35:14 +00001043
Chris Lattner8b418682012-02-07 00:39:47 +00001044 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001045
John McCall6374c332010-03-06 00:35:14 +00001046 // 0-7 are the eight integer registers; the order is different
1047 // on Darwin (for EH), but the range is the same.
1048 // 8 is %eip.
John McCallaeeb7012010-05-27 06:19:26 +00001049 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCall6374c332010-03-06 00:35:14 +00001050
John McCall64aa4b32013-04-16 22:48:15 +00001051 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCall6374c332010-03-06 00:35:14 +00001052 // 12-16 are st(0..4). Not sure why we stop at 4.
1053 // These have size 16, which is sizeof(long double) on
1054 // platforms with 8-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001055 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCallaeeb7012010-05-27 06:19:26 +00001056 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001057
John McCall6374c332010-03-06 00:35:14 +00001058 } else {
1059 // 9 is %eflags, which doesn't get a size on Darwin for some
1060 // reason.
1061 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1062
1063 // 11-16 are st(0..5). Not sure why we stop at 5.
1064 // These have size 12, which is sizeof(long double) on
1065 // platforms with 4-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001066 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCallaeeb7012010-05-27 06:19:26 +00001067 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1068 }
John McCall6374c332010-03-06 00:35:14 +00001069
1070 return false;
1071}
1072
Chris Lattnerdce5ad02010-06-28 20:05:43 +00001073//===----------------------------------------------------------------------===//
1074// X86-64 ABI Implementation
1075//===----------------------------------------------------------------------===//
1076
1077
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001078namespace {
1079/// X86_64ABIInfo - The X86_64 ABI information.
1080class X86_64ABIInfo : public ABIInfo {
1081 enum Class {
1082 Integer = 0,
1083 SSE,
1084 SSEUp,
1085 X87,
1086 X87Up,
1087 ComplexX87,
1088 NoClass,
1089 Memory
1090 };
1091
1092 /// merge - Implement the X86_64 ABI merging algorithm.
1093 ///
1094 /// Merge an accumulating classification \arg Accum with a field
1095 /// classification \arg Field.
1096 ///
1097 /// \param Accum - The accumulating classification. This should
1098 /// always be either NoClass or the result of a previous merge
1099 /// call. In addition, this should never be Memory (the caller
1100 /// should just return Memory for the aggregate).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001101 static Class merge(Class Accum, Class Field);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001102
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001103 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1104 ///
1105 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1106 /// final MEMORY or SSE classes when necessary.
1107 ///
1108 /// \param AggregateSize - The size of the current aggregate in
1109 /// the classification process.
1110 ///
1111 /// \param Lo - The classification for the parts of the type
1112 /// residing in the low word of the containing object.
1113 ///
1114 /// \param Hi - The classification for the parts of the type
1115 /// residing in the higher words of the containing object.
1116 ///
1117 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1118
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001119 /// classify - Determine the x86_64 register classes in which the
1120 /// given type T should be passed.
1121 ///
1122 /// \param Lo - The classification for the parts of the type
1123 /// residing in the low word of the containing object.
1124 ///
1125 /// \param Hi - The classification for the parts of the type
1126 /// residing in the high word of the containing object.
1127 ///
1128 /// \param OffsetBase - The bit offset of this type in the
1129 /// containing object. Some parameters are classified different
1130 /// depending on whether they straddle an eightbyte boundary.
1131 ///
Eli Friedman7a1b5862013-06-12 00:13:45 +00001132 /// \param isNamedArg - Whether the argument in question is a "named"
1133 /// argument, as used in AMD64-ABI 3.5.7.
1134 ///
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001135 /// If a word is unused its result will be NoClass; if a type should
1136 /// be passed in Memory then at least the classification of \arg Lo
1137 /// will be Memory.
1138 ///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001139 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001140 ///
1141 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1142 /// also be ComplexX87.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001143 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1144 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001145
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001146 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001147 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1148 unsigned IROffset, QualType SourceTy,
1149 unsigned SourceOffset) const;
1150 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1151 unsigned IROffset, QualType SourceTy,
1152 unsigned SourceOffset) const;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001153
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001154 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001155 /// such that the argument will be returned in memory.
Chris Lattner9c254f02010-06-29 06:01:59 +00001156 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001157
1158 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001159 /// such that the argument will be passed in memory.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001160 ///
1161 /// \param freeIntRegs - The number of free integer registers remaining
1162 /// available.
1163 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001164
Chris Lattnera3c109b2010-07-29 02:16:43 +00001165 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001166
Bill Wendlingbb465d72010-10-18 03:41:31 +00001167 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbaredfac032012-03-10 01:03:58 +00001168 unsigned freeIntRegs,
Bill Wendlingbb465d72010-10-18 03:41:31 +00001169 unsigned &neededInt,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001170 unsigned &neededSSE,
1171 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001172
Eli Friedmanee1ad992011-12-02 00:11:43 +00001173 bool IsIllegalVectorType(QualType Ty) const;
1174
John McCall67a57732011-04-21 01:20:55 +00001175 /// The 0.98 ABI revision clarified a lot of ambiguities,
1176 /// unfortunately in ways that were not always consistent with
1177 /// certain previous compilers. In particular, platforms which
1178 /// required strict binary compatibility with older versions of GCC
1179 /// may need to exempt themselves.
1180 bool honorsRevision0_98() const {
John McCall64aa4b32013-04-16 22:48:15 +00001181 return !getTarget().getTriple().isOSDarwin();
John McCall67a57732011-04-21 01:20:55 +00001182 }
1183
Eli Friedmanee1ad992011-12-02 00:11:43 +00001184 bool HasAVX;
Derek Schuffbabaf312012-10-11 15:52:22 +00001185 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1186 // 64-bit hardware.
1187 bool Has64BitPointers;
Eli Friedmanee1ad992011-12-02 00:11:43 +00001188
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001189public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001190 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffbabaf312012-10-11 15:52:22 +00001191 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff90da80c2012-10-11 18:21:13 +00001192 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001193 }
Chris Lattner9c254f02010-06-29 06:01:59 +00001194
John McCallde5d3c72012-02-17 03:33:10 +00001195 bool isPassedUsingAVXType(QualType type) const {
1196 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00001197 // The freeIntRegs argument doesn't matter here.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001198 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1199 /*isNamedArg*/true);
John McCallde5d3c72012-02-17 03:33:10 +00001200 if (info.isDirect()) {
1201 llvm::Type *ty = info.getCoerceToType();
1202 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1203 return (vectorTy->getBitWidth() > 128);
1204 }
1205 return false;
1206 }
1207
Chris Lattneree5dcd02010-07-29 02:31:05 +00001208 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001209
1210 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1211 CodeGenFunction &CGF) const;
1212};
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001213
Chris Lattnerf13721d2010-08-31 16:44:54 +00001214/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001215class WinX86_64ABIInfo : public ABIInfo {
1216
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001217 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001218
Chris Lattnerf13721d2010-08-31 16:44:54 +00001219public:
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001220 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1221
1222 virtual void computeInfo(CGFunctionInfo &FI) const;
Chris Lattnerf13721d2010-08-31 16:44:54 +00001223
1224 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1225 CodeGenFunction &CGF) const;
1226};
1227
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001228class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1229public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001230 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffbabaf312012-10-11 15:52:22 +00001231 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCall6374c332010-03-06 00:35:14 +00001232
John McCallde5d3c72012-02-17 03:33:10 +00001233 const X86_64ABIInfo &getABIInfo() const {
1234 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1235 }
1236
John McCall6374c332010-03-06 00:35:14 +00001237 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1238 return 7;
1239 }
1240
1241 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1242 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001243 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001244
John McCallaeeb7012010-05-27 06:19:26 +00001245 // 0-15 are the 16 integer registers.
1246 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001247 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCall6374c332010-03-06 00:35:14 +00001248 return false;
1249 }
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001250
Jay Foadef6de3d2011-07-11 09:56:20 +00001251 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001252 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +00001253 llvm::Type* Ty) const {
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001254 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1255 }
1256
John McCallde5d3c72012-02-17 03:33:10 +00001257 bool isNoProtoCallVariadic(const CallArgList &args,
1258 const FunctionNoProtoType *fnType) const {
John McCall01f151e2011-09-21 08:08:30 +00001259 // The default CC on x86-64 sets %al to the number of SSA
1260 // registers used, and GCC sets this when calling an unprototyped
Eli Friedman3ed79032011-12-01 04:53:19 +00001261 // function, so we override the default behavior. However, don't do
Eli Friedman68805fe2011-12-06 03:08:26 +00001262 // that when AVX types are involved: the ABI explicitly states it is
1263 // undefined, and it doesn't work in practice because of how the ABI
1264 // defines varargs anyway.
Reid Kleckneref072032013-08-27 23:08:25 +00001265 if (fnType->getCallConv() == CC_C) {
Eli Friedman3ed79032011-12-01 04:53:19 +00001266 bool HasAVXType = false;
John McCallde5d3c72012-02-17 03:33:10 +00001267 for (CallArgList::const_iterator
1268 it = args.begin(), ie = args.end(); it != ie; ++it) {
1269 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1270 HasAVXType = true;
1271 break;
Eli Friedman3ed79032011-12-01 04:53:19 +00001272 }
1273 }
John McCallde5d3c72012-02-17 03:33:10 +00001274
Eli Friedman3ed79032011-12-01 04:53:19 +00001275 if (!HasAVXType)
1276 return true;
1277 }
John McCall01f151e2011-09-21 08:08:30 +00001278
John McCallde5d3c72012-02-17 03:33:10 +00001279 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCall01f151e2011-09-21 08:08:30 +00001280 }
1281
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001282};
1283
Aaron Ballman89735b92013-05-24 15:06:56 +00001284static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1285 // If the argument does not end in .lib, automatically add the suffix. This
1286 // matches the behavior of MSVC.
1287 std::string ArgStr = Lib;
1288 if (Lib.size() <= 4 ||
1289 Lib.substr(Lib.size() - 4).compare_lower(".lib") != 0) {
1290 ArgStr += ".lib";
1291 }
1292 return ArgStr;
1293}
1294
Reid Kleckner3190ca92013-05-08 13:44:39 +00001295class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1296public:
John McCallb8b52972013-06-18 02:46:29 +00001297 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1298 bool d, bool p, bool w, unsigned RegParms)
1299 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Kleckner3190ca92013-05-08 13:44:39 +00001300
1301 void getDependentLibraryOption(llvm::StringRef Lib,
1302 llvm::SmallString<24> &Opt) const {
1303 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001304 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001305 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001306
1307 void getDetectMismatchOption(llvm::StringRef Name,
1308 llvm::StringRef Value,
1309 llvm::SmallString<32> &Opt) const {
Eli Friedman572ac322013-06-07 22:42:22 +00001310 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001311 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001312};
1313
Chris Lattnerf13721d2010-08-31 16:44:54 +00001314class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1315public:
1316 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1317 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1318
1319 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1320 return 7;
1321 }
1322
1323 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1324 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001325 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001326
Chris Lattnerf13721d2010-08-31 16:44:54 +00001327 // 0-15 are the 16 integer registers.
1328 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001329 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattnerf13721d2010-08-31 16:44:54 +00001330 return false;
1331 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001332
1333 void getDependentLibraryOption(llvm::StringRef Lib,
1334 llvm::SmallString<24> &Opt) const {
1335 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001336 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001337 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001338
1339 void getDetectMismatchOption(llvm::StringRef Name,
1340 llvm::StringRef Value,
1341 llvm::SmallString<32> &Opt) const {
Eli Friedman572ac322013-06-07 22:42:22 +00001342 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001343 }
Chris Lattnerf13721d2010-08-31 16:44:54 +00001344};
1345
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001346}
1347
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001348void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1349 Class &Hi) const {
1350 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1351 //
1352 // (a) If one of the classes is Memory, the whole argument is passed in
1353 // memory.
1354 //
1355 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1356 // memory.
1357 //
1358 // (c) If the size of the aggregate exceeds two eightbytes and the first
1359 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1360 // argument is passed in memory. NOTE: This is necessary to keep the
1361 // ABI working for processors that don't support the __m256 type.
1362 //
1363 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1364 //
1365 // Some of these are enforced by the merging logic. Others can arise
1366 // only with unions; for example:
1367 // union { _Complex double; unsigned; }
1368 //
1369 // Note that clauses (b) and (c) were added in 0.98.
1370 //
1371 if (Hi == Memory)
1372 Lo = Memory;
1373 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1374 Lo = Memory;
1375 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1376 Lo = Memory;
1377 if (Hi == SSEUp && Lo != SSE)
1378 Hi = SSE;
1379}
1380
Chris Lattner1090a9b2010-06-28 21:43:59 +00001381X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001382 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1383 // classified recursively so that always two fields are
1384 // considered. The resulting class is calculated according to
1385 // the classes of the fields in the eightbyte:
1386 //
1387 // (a) If both classes are equal, this is the resulting class.
1388 //
1389 // (b) If one of the classes is NO_CLASS, the resulting class is
1390 // the other class.
1391 //
1392 // (c) If one of the classes is MEMORY, the result is the MEMORY
1393 // class.
1394 //
1395 // (d) If one of the classes is INTEGER, the result is the
1396 // INTEGER.
1397 //
1398 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1399 // MEMORY is used as class.
1400 //
1401 // (f) Otherwise class SSE is used.
1402
1403 // Accum should never be memory (we should have returned) or
1404 // ComplexX87 (because this cannot be passed in a structure).
1405 assert((Accum != Memory && Accum != ComplexX87) &&
1406 "Invalid accumulated classification during merge.");
1407 if (Accum == Field || Field == NoClass)
1408 return Accum;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001409 if (Field == Memory)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001410 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001411 if (Accum == NoClass)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001412 return Field;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001413 if (Accum == Integer || Field == Integer)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001414 return Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001415 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1416 Accum == X87 || Accum == X87Up)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001417 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001418 return SSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001419}
1420
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001421void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001422 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001423 // FIXME: This code can be simplified by introducing a simple value class for
1424 // Class pairs with appropriate constructor methods for the various
1425 // situations.
1426
1427 // FIXME: Some of the split computations are wrong; unaligned vectors
1428 // shouldn't be passed in registers for example, so there is no chance they
1429 // can straddle an eightbyte. Verify & simplify.
1430
1431 Lo = Hi = NoClass;
1432
1433 Class &Current = OffsetBase < 64 ? Lo : Hi;
1434 Current = Memory;
1435
John McCall183700f2009-09-21 23:43:11 +00001436 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001437 BuiltinType::Kind k = BT->getKind();
1438
1439 if (k == BuiltinType::Void) {
1440 Current = NoClass;
1441 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1442 Lo = Integer;
1443 Hi = Integer;
1444 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1445 Current = Integer;
Derek Schuff7da46f92012-10-11 16:55:58 +00001446 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1447 (k == BuiltinType::LongDouble &&
Cameron Esfahani57b1da12013-09-14 01:09:11 +00001448 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001449 Current = SSE;
1450 } else if (k == BuiltinType::LongDouble) {
1451 Lo = X87;
1452 Hi = X87Up;
1453 }
1454 // FIXME: _Decimal32 and _Decimal64 are SSE.
1455 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001456 return;
1457 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001458
Chris Lattner1090a9b2010-06-28 21:43:59 +00001459 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001460 // Classify the underlying integer type.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001461 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattner1090a9b2010-06-28 21:43:59 +00001462 return;
1463 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001464
Chris Lattner1090a9b2010-06-28 21:43:59 +00001465 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001466 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001467 return;
1468 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001469
Chris Lattner1090a9b2010-06-28 21:43:59 +00001470 if (Ty->isMemberPointerType()) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001471 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar67d438d2010-05-15 00:00:37 +00001472 Lo = Hi = Integer;
1473 else
1474 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001475 return;
1476 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001477
Chris Lattner1090a9b2010-06-28 21:43:59 +00001478 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001479 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001480 if (Size == 32) {
1481 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1482 // float> as integer.
1483 Current = Integer;
1484
1485 // If this type crosses an eightbyte boundary, it should be
1486 // split.
1487 uint64_t EB_Real = (OffsetBase) / 64;
1488 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1489 if (EB_Real != EB_Imag)
1490 Hi = Lo;
1491 } else if (Size == 64) {
1492 // gcc passes <1 x double> in memory. :(
1493 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1494 return;
1495
1496 // gcc passes <1 x long long> as INTEGER.
Chris Lattner473f8e72010-08-26 18:03:20 +00001497 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner0fefa412010-08-26 18:13:50 +00001498 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1499 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1500 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001501 Current = Integer;
1502 else
1503 Current = SSE;
1504
1505 // If this type crosses an eightbyte boundary, it should be
1506 // split.
1507 if (OffsetBase && OffsetBase != 64)
1508 Hi = Lo;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001509 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001510 // Arguments of 256-bits are split into four eightbyte chunks. The
1511 // least significant one belongs to class SSE and all the others to class
1512 // SSEUP. The original Lo and Hi design considers that types can't be
1513 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1514 // This design isn't correct for 256-bits, but since there're no cases
1515 // where the upper parts would need to be inspected, avoid adding
1516 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001517 //
1518 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1519 // registers if they are "named", i.e. not part of the "..." of a
1520 // variadic function.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001521 Lo = SSE;
1522 Hi = SSEUp;
1523 }
Chris Lattner1090a9b2010-06-28 21:43:59 +00001524 return;
1525 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001526
Chris Lattner1090a9b2010-06-28 21:43:59 +00001527 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001528 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001529
Chris Lattnerea044322010-07-29 02:01:43 +00001530 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001531 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001532 if (Size <= 64)
1533 Current = Integer;
1534 else if (Size <= 128)
1535 Lo = Hi = Integer;
Chris Lattnerea044322010-07-29 02:01:43 +00001536 } else if (ET == getContext().FloatTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001537 Current = SSE;
Derek Schuff7da46f92012-10-11 16:55:58 +00001538 else if (ET == getContext().DoubleTy ||
1539 (ET == getContext().LongDoubleTy &&
Cameron Esfahani57b1da12013-09-14 01:09:11 +00001540 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001541 Lo = Hi = SSE;
Chris Lattnerea044322010-07-29 02:01:43 +00001542 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001543 Current = ComplexX87;
1544
1545 // If this complex type crosses an eightbyte boundary then it
1546 // should be split.
1547 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattnerea044322010-07-29 02:01:43 +00001548 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001549 if (Hi == NoClass && EB_Real != EB_Imag)
1550 Hi = Lo;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001551
Chris Lattner1090a9b2010-06-28 21:43:59 +00001552 return;
1553 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001554
Chris Lattnerea044322010-07-29 02:01:43 +00001555 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001556 // Arrays are treated like structures.
1557
Chris Lattnerea044322010-07-29 02:01:43 +00001558 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001559
1560 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001561 // than four eightbytes, ..., it has class MEMORY.
1562 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001563 return;
1564
1565 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1566 // fields, it has class MEMORY.
1567 //
1568 // Only need to check alignment of array base.
Chris Lattnerea044322010-07-29 02:01:43 +00001569 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001570 return;
1571
1572 // Otherwise implement simplified merge. We could be smarter about
1573 // this, but it isn't worth it and would be harder to verify.
1574 Current = NoClass;
Chris Lattnerea044322010-07-29 02:01:43 +00001575 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001576 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes089d8922011-07-12 01:27:38 +00001577
1578 // The only case a 256-bit wide vector could be used is when the array
1579 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1580 // to work for sizes wider than 128, early check and fallback to memory.
1581 if (Size > 128 && EltSize != 256)
1582 return;
1583
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001584 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1585 Class FieldLo, FieldHi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001586 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001587 Lo = merge(Lo, FieldLo);
1588 Hi = merge(Hi, FieldHi);
1589 if (Lo == Memory || Hi == Memory)
1590 break;
1591 }
1592
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001593 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001594 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattner1090a9b2010-06-28 21:43:59 +00001595 return;
1596 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001597
Chris Lattner1090a9b2010-06-28 21:43:59 +00001598 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001599 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001600
1601 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001602 // than four eightbytes, ..., it has class MEMORY.
1603 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001604 return;
1605
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001606 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1607 // copy constructor or a non-trivial destructor, it is passed by invisible
1608 // reference.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001609 if (getRecordArgABI(RT, CGT))
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001610 return;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001611
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001612 const RecordDecl *RD = RT->getDecl();
1613
1614 // Assume variable sized types are passed in memory.
1615 if (RD->hasFlexibleArrayMember())
1616 return;
1617
Chris Lattnerea044322010-07-29 02:01:43 +00001618 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001619
1620 // Reset Lo class, this will be recomputed.
1621 Current = NoClass;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001622
1623 // If this is a C++ record, classify the bases first.
1624 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1625 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1626 e = CXXRD->bases_end(); i != e; ++i) {
1627 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1628 "Unexpected base class!");
1629 const CXXRecordDecl *Base =
1630 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1631
1632 // Classify this field.
1633 //
1634 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1635 // single eightbyte, each is classified separately. Each eightbyte gets
1636 // initialized to class NO_CLASS.
1637 Class FieldLo, FieldHi;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001638 uint64_t Offset =
1639 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Eli Friedman7a1b5862013-06-12 00:13:45 +00001640 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001641 Lo = merge(Lo, FieldLo);
1642 Hi = merge(Hi, FieldHi);
1643 if (Lo == Memory || Hi == Memory)
1644 break;
1645 }
1646 }
1647
1648 // Classify the fields one at a time, merging the results.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001649 unsigned idx = 0;
Bruno Cardoso Lopes548e4782011-07-12 22:30:58 +00001650 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001651 i != e; ++i, ++idx) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001652 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1653 bool BitField = i->isBitField();
1654
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001655 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1656 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001657 //
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001658 // The only case a 256-bit wide vector could be used is when the struct
1659 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1660 // to work for sizes wider than 128, early check and fallback to memory.
1661 //
1662 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1663 Lo = Memory;
1664 return;
1665 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001666 // Note, skip this test for bit-fields, see below.
Chris Lattnerea044322010-07-29 02:01:43 +00001667 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001668 Lo = Memory;
1669 return;
1670 }
1671
1672 // Classify this field.
1673 //
1674 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1675 // exceeds a single eightbyte, each is classified
1676 // separately. Each eightbyte gets initialized to class
1677 // NO_CLASS.
1678 Class FieldLo, FieldHi;
1679
1680 // Bit-fields require special handling, they do not force the
1681 // structure to be passed in memory even if unaligned, and
1682 // therefore they can straddle an eightbyte.
1683 if (BitField) {
1684 // Ignore padding bit-fields.
1685 if (i->isUnnamedBitfield())
1686 continue;
1687
1688 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001689 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001690
1691 uint64_t EB_Lo = Offset / 64;
1692 uint64_t EB_Hi = (Offset + Size - 1) / 64;
1693 FieldLo = FieldHi = NoClass;
1694 if (EB_Lo) {
1695 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1696 FieldLo = NoClass;
1697 FieldHi = Integer;
1698 } else {
1699 FieldLo = Integer;
1700 FieldHi = EB_Hi ? Integer : NoClass;
1701 }
1702 } else
Eli Friedman7a1b5862013-06-12 00:13:45 +00001703 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001704 Lo = merge(Lo, FieldLo);
1705 Hi = merge(Hi, FieldHi);
1706 if (Lo == Memory || Hi == Memory)
1707 break;
1708 }
1709
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001710 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001711 }
1712}
1713
Chris Lattner9c254f02010-06-29 06:01:59 +00001714ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001715 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1716 // place naturally.
John McCalld608cdb2010-08-22 10:59:02 +00001717 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001718 // Treat an enum type as its underlying type.
1719 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1720 Ty = EnumTy->getDecl()->getIntegerType();
1721
1722 return (Ty->isPromotableIntegerType() ?
1723 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1724 }
1725
1726 return ABIArgInfo::getIndirect(0);
1727}
1728
Eli Friedmanee1ad992011-12-02 00:11:43 +00001729bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1730 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1731 uint64_t Size = getContext().getTypeSize(VecTy);
1732 unsigned LargestVector = HasAVX ? 256 : 128;
1733 if (Size <= 64 || Size > LargestVector)
1734 return true;
1735 }
1736
1737 return false;
1738}
1739
Daniel Dunbaredfac032012-03-10 01:03:58 +00001740ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1741 unsigned freeIntRegs) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001742 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1743 // place naturally.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001744 //
1745 // This assumption is optimistic, as there could be free registers available
1746 // when we need to pass this argument in memory, and LLVM could try to pass
1747 // the argument in the free register. This does not seem to happen currently,
1748 // but this code would be much safer if we could mark the argument with
1749 // 'onstack'. See PR12193.
Eli Friedmanee1ad992011-12-02 00:11:43 +00001750 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001751 // Treat an enum type as its underlying type.
1752 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1753 Ty = EnumTy->getDecl()->getIntegerType();
1754
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001755 return (Ty->isPromotableIntegerType() ?
1756 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001757 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001758
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001759 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
1760 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001761
Chris Lattner855d2272011-05-22 23:21:23 +00001762 // Compute the byval alignment. We specify the alignment of the byval in all
1763 // cases so that the mid-level optimizer knows the alignment of the byval.
1764 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbaredfac032012-03-10 01:03:58 +00001765
1766 // Attempt to avoid passing indirect results using byval when possible. This
1767 // is important for good codegen.
1768 //
1769 // We do this by coercing the value into a scalar type which the backend can
1770 // handle naturally (i.e., without using byval).
1771 //
1772 // For simplicity, we currently only do this when we have exhausted all of the
1773 // free integer registers. Doing this when there are free integer registers
1774 // would require more care, as we would have to ensure that the coerced value
1775 // did not claim the unused register. That would require either reording the
1776 // arguments to the function (so that any subsequent inreg values came first),
1777 // or only doing this optimization when there were no following arguments that
1778 // might be inreg.
1779 //
1780 // We currently expect it to be rare (particularly in well written code) for
1781 // arguments to be passed on the stack when there are still free integer
1782 // registers available (this would typically imply large structs being passed
1783 // by value), so this seems like a fair tradeoff for now.
1784 //
1785 // We can revisit this if the backend grows support for 'onstack' parameter
1786 // attributes. See PR12193.
1787 if (freeIntRegs == 0) {
1788 uint64_t Size = getContext().getTypeSize(Ty);
1789
1790 // If this type fits in an eightbyte, coerce it into the matching integral
1791 // type, which will end up on the stack (with alignment 8).
1792 if (Align == 8 && Size <= 64)
1793 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1794 Size));
1795 }
1796
Chris Lattner855d2272011-05-22 23:21:23 +00001797 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001798}
1799
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001800/// GetByteVectorType - The ABI specifies that a value should be passed in an
1801/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner0f408f52010-07-29 04:56:46 +00001802/// vector register.
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001803llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001804 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001805
Chris Lattner15842bd2010-07-29 05:02:29 +00001806 // Wrapper structs that just contain vectors are passed just like vectors,
1807 // strip them off if present.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001808 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner15842bd2010-07-29 05:02:29 +00001809 while (STy && STy->getNumElements() == 1) {
1810 IRType = STy->getElementType(0);
1811 STy = dyn_cast<llvm::StructType>(IRType);
1812 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001813
Bruno Cardoso Lopes528a8c72011-07-08 22:57:35 +00001814 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001815 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1816 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001817 unsigned BitWidth = VT->getBitWidth();
Tanya Lattnerce275672011-11-28 23:18:11 +00001818 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner0f408f52010-07-29 04:56:46 +00001819 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1820 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1821 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1822 EltTy->isIntegerTy(128)))
1823 return VT;
1824 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001825
Chris Lattner0f408f52010-07-29 04:56:46 +00001826 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1827}
1828
Chris Lattnere2962be2010-07-29 07:30:00 +00001829/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1830/// is known to either be off the end of the specified type or being in
1831/// alignment padding. The user type specified is known to be at most 128 bits
1832/// in size, and have passed through X86_64ABIInfo::classify with a successful
1833/// classification that put one of the two halves in the INTEGER class.
1834///
1835/// It is conservatively correct to return false.
1836static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1837 unsigned EndBit, ASTContext &Context) {
1838 // If the bytes being queried are off the end of the type, there is no user
1839 // data hiding here. This handles analysis of builtins, vectors and other
1840 // types that don't contain interesting padding.
1841 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1842 if (TySize <= StartBit)
1843 return true;
1844
Chris Lattner021c3a32010-07-29 07:43:55 +00001845 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1846 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1847 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1848
1849 // Check each element to see if the element overlaps with the queried range.
1850 for (unsigned i = 0; i != NumElts; ++i) {
1851 // If the element is after the span we care about, then we're done..
1852 unsigned EltOffset = i*EltSize;
1853 if (EltOffset >= EndBit) break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001854
Chris Lattner021c3a32010-07-29 07:43:55 +00001855 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1856 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1857 EndBit-EltOffset, Context))
1858 return false;
1859 }
1860 // If it overlaps no elements, then it is safe to process as padding.
1861 return true;
1862 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001863
Chris Lattnere2962be2010-07-29 07:30:00 +00001864 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1865 const RecordDecl *RD = RT->getDecl();
1866 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001867
Chris Lattnere2962be2010-07-29 07:30:00 +00001868 // If this is a C++ record, check the bases first.
1869 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1870 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1871 e = CXXRD->bases_end(); i != e; ++i) {
1872 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1873 "Unexpected base class!");
1874 const CXXRecordDecl *Base =
1875 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001876
Chris Lattnere2962be2010-07-29 07:30:00 +00001877 // If the base is after the span we care about, ignore it.
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001878 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnere2962be2010-07-29 07:30:00 +00001879 if (BaseOffset >= EndBit) continue;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001880
Chris Lattnere2962be2010-07-29 07:30:00 +00001881 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1882 if (!BitsContainNoUserData(i->getType(), BaseStart,
1883 EndBit-BaseOffset, Context))
1884 return false;
1885 }
1886 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001887
Chris Lattnere2962be2010-07-29 07:30:00 +00001888 // Verify that no field has data that overlaps the region of interest. Yes
1889 // this could be sped up a lot by being smarter about queried fields,
1890 // however we're only looking at structs up to 16 bytes, so we don't care
1891 // much.
1892 unsigned idx = 0;
1893 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1894 i != e; ++i, ++idx) {
1895 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001896
Chris Lattnere2962be2010-07-29 07:30:00 +00001897 // If we found a field after the region we care about, then we're done.
1898 if (FieldOffset >= EndBit) break;
1899
1900 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1901 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1902 Context))
1903 return false;
1904 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001905
Chris Lattnere2962be2010-07-29 07:30:00 +00001906 // If nothing in this record overlapped the area of interest, then we're
1907 // clean.
1908 return true;
1909 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001910
Chris Lattnere2962be2010-07-29 07:30:00 +00001911 return false;
1912}
1913
Chris Lattner0b362002010-07-29 18:39:32 +00001914/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1915/// float member at the specified offset. For example, {int,{float}} has a
1916/// float at offset 4. It is conservatively correct for this routine to return
1917/// false.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001918static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmow25a6a842012-10-08 16:25:52 +00001919 const llvm::DataLayout &TD) {
Chris Lattner0b362002010-07-29 18:39:32 +00001920 // Base case if we find a float.
1921 if (IROffset == 0 && IRType->isFloatTy())
1922 return true;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001923
Chris Lattner0b362002010-07-29 18:39:32 +00001924 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001925 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner0b362002010-07-29 18:39:32 +00001926 const llvm::StructLayout *SL = TD.getStructLayout(STy);
1927 unsigned Elt = SL->getElementContainingOffset(IROffset);
1928 IROffset -= SL->getElementOffset(Elt);
1929 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1930 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001931
Chris Lattner0b362002010-07-29 18:39:32 +00001932 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001933 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1934 llvm::Type *EltTy = ATy->getElementType();
Chris Lattner0b362002010-07-29 18:39:32 +00001935 unsigned EltSize = TD.getTypeAllocSize(EltTy);
1936 IROffset -= IROffset/EltSize*EltSize;
1937 return ContainsFloatAtOffset(EltTy, IROffset, TD);
1938 }
1939
1940 return false;
1941}
1942
Chris Lattnerf47c9442010-07-29 18:13:09 +00001943
1944/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1945/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001946llvm::Type *X86_64ABIInfo::
1947GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattnerf47c9442010-07-29 18:13:09 +00001948 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnercba8d312010-07-29 18:19:50 +00001949 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattnerf47c9442010-07-29 18:13:09 +00001950 // pass as float if the last 4 bytes is just padding. This happens for
1951 // structs that contain 3 floats.
1952 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1953 SourceOffset*8+64, getContext()))
1954 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001955
Chris Lattner0b362002010-07-29 18:39:32 +00001956 // We want to pass as <2 x float> if the LLVM IR type contains a float at
1957 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
1958 // case.
Micah Villmow25a6a842012-10-08 16:25:52 +00001959 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
1960 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner22fd4ba2010-08-25 23:39:14 +00001961 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001962
Chris Lattnerf47c9442010-07-29 18:13:09 +00001963 return llvm::Type::getDoubleTy(getVMContext());
1964}
1965
1966
Chris Lattner0d2656d2010-07-29 17:40:35 +00001967/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1968/// an 8-byte GPR. This means that we either have a scalar or we are talking
1969/// about the high or low part of an up-to-16-byte struct. This routine picks
1970/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattner49382de2010-07-28 22:44:07 +00001971/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1972/// etc).
1973///
1974/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1975/// the source type. IROffset is an offset in bytes into the LLVM IR type that
1976/// the 8-byte value references. PrefType may be null.
1977///
1978/// SourceTy is the source level type for the entire argument. SourceOffset is
1979/// an offset into this that we're processing (which is always either 0 or 8).
1980///
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001981llvm::Type *X86_64ABIInfo::
1982GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner0d2656d2010-07-29 17:40:35 +00001983 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnere2962be2010-07-29 07:30:00 +00001984 // If we're dealing with an un-offset LLVM IR type, then it means that we're
1985 // returning an 8-byte unit starting with it. See if we can safely use it.
1986 if (IROffset == 0) {
1987 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffbabaf312012-10-11 15:52:22 +00001988 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
1989 IRType->isIntegerTy(64))
Chris Lattnere2962be2010-07-29 07:30:00 +00001990 return IRType;
Chris Lattner49382de2010-07-28 22:44:07 +00001991
Chris Lattnere2962be2010-07-29 07:30:00 +00001992 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1993 // goodness in the source type is just tail padding. This is allowed to
1994 // kick in for struct {double,int} on the int, but not on
1995 // struct{double,int,int} because we wouldn't return the second int. We
1996 // have to do this analysis on the source type because we can't depend on
1997 // unions being lowered a specific way etc.
1998 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffbabaf312012-10-11 15:52:22 +00001999 IRType->isIntegerTy(32) ||
2000 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2001 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2002 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002003
Chris Lattnere2962be2010-07-29 07:30:00 +00002004 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2005 SourceOffset*8+64, getContext()))
2006 return IRType;
2007 }
2008 }
Chris Lattner49382de2010-07-28 22:44:07 +00002009
Chris Lattner2acc6e32011-07-18 04:24:23 +00002010 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner49382de2010-07-28 22:44:07 +00002011 // If this is a struct, recurse into the field at the specified offset.
Micah Villmow25a6a842012-10-08 16:25:52 +00002012 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattner49382de2010-07-28 22:44:07 +00002013 if (IROffset < SL->getSizeInBytes()) {
2014 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2015 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002016
Chris Lattner0d2656d2010-07-29 17:40:35 +00002017 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2018 SourceTy, SourceOffset);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002019 }
Chris Lattner49382de2010-07-28 22:44:07 +00002020 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002021
Chris Lattner2acc6e32011-07-18 04:24:23 +00002022 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002023 llvm::Type *EltTy = ATy->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00002024 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner021c3a32010-07-29 07:43:55 +00002025 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner0d2656d2010-07-29 17:40:35 +00002026 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2027 SourceOffset);
Chris Lattner021c3a32010-07-29 07:43:55 +00002028 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002029
Chris Lattner49382de2010-07-28 22:44:07 +00002030 // Okay, we don't have any better idea of what to pass, so we pass this in an
2031 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002032 unsigned TySizeInBytes =
2033 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattner49382de2010-07-28 22:44:07 +00002034
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002035 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002036
Chris Lattner49382de2010-07-28 22:44:07 +00002037 // It is always safe to classify this as an integer type up to i64 that
2038 // isn't larger than the structure.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002039 return llvm::IntegerType::get(getVMContext(),
2040 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner9c254f02010-06-29 06:01:59 +00002041}
2042
Chris Lattner66e7b682010-09-01 00:50:20 +00002043
2044/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2045/// be used as elements of a two register pair to pass or return, return a
2046/// first class aggregate to represent them. For example, if the low part of
2047/// a by-value argument should be passed as i32* and the high part as float,
2048/// return {i32*, float}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002049static llvm::Type *
Jay Foadef6de3d2011-07-11 09:56:20 +00002050GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmow25a6a842012-10-08 16:25:52 +00002051 const llvm::DataLayout &TD) {
Chris Lattner66e7b682010-09-01 00:50:20 +00002052 // In order to correctly satisfy the ABI, we need to the high part to start
2053 // at offset 8. If the high and low parts we inferred are both 4-byte types
2054 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2055 // the second element at offset 8. Check for this:
2056 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2057 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmow25a6a842012-10-08 16:25:52 +00002058 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattner66e7b682010-09-01 00:50:20 +00002059 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002060
Chris Lattner66e7b682010-09-01 00:50:20 +00002061 // To handle this, we have to increase the size of the low part so that the
2062 // second element will start at an 8 byte offset. We can't increase the size
2063 // of the second element because it might make us access off the end of the
2064 // struct.
2065 if (HiStart != 8) {
2066 // There are only two sorts of types the ABI generation code can produce for
2067 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2068 // Promote these to a larger type.
2069 if (Lo->isFloatTy())
2070 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2071 else {
2072 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2073 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2074 }
2075 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002076
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002077 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002078
2079
Chris Lattner66e7b682010-09-01 00:50:20 +00002080 // Verify that the second element is at an 8-byte offset.
2081 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2082 "Invalid x86-64 argument pair!");
2083 return Result;
2084}
2085
Chris Lattner519f68c2010-07-28 23:06:14 +00002086ABIArgInfo X86_64ABIInfo::
Chris Lattnera3c109b2010-07-29 02:16:43 +00002087classifyReturnType(QualType RetTy) const {
Chris Lattner519f68c2010-07-28 23:06:14 +00002088 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2089 // classification algorithm.
2090 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002091 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner519f68c2010-07-28 23:06:14 +00002092
2093 // Check some invariants.
2094 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002095 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2096
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002097 llvm::Type *ResType = 0;
Chris Lattner519f68c2010-07-28 23:06:14 +00002098 switch (Lo) {
2099 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002100 if (Hi == NoClass)
2101 return ABIArgInfo::getIgnore();
2102 // If the low part is just padding, it takes no register, leave ResType
2103 // null.
2104 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2105 "Unknown missing lo part");
2106 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002107
2108 case SSEUp:
2109 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002110 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002111
2112 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2113 // hidden argument.
2114 case Memory:
2115 return getIndirectReturnResult(RetTy);
2116
2117 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2118 // available register of the sequence %rax, %rdx is used.
2119 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002120 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002121
Chris Lattnereb518b42010-07-29 21:42:50 +00002122 // If we have a sign or zero extended integer, make sure to return Extend
2123 // so that the parameter gets the right LLVM IR attributes.
2124 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2125 // Treat an enum type as its underlying type.
2126 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2127 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002128
Chris Lattnereb518b42010-07-29 21:42:50 +00002129 if (RetTy->isIntegralOrEnumerationType() &&
2130 RetTy->isPromotableIntegerType())
2131 return ABIArgInfo::getExtend();
2132 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002133 break;
2134
2135 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2136 // available SSE register of the sequence %xmm0, %xmm1 is used.
2137 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002138 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattner0b30c672010-07-28 23:12:33 +00002139 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002140
2141 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2142 // returned on the X87 stack in %st0 as 80-bit x87 number.
2143 case X87:
Chris Lattnerea044322010-07-29 02:01:43 +00002144 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattner0b30c672010-07-28 23:12:33 +00002145 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002146
2147 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2148 // part of the value is returned in %st0 and the imaginary part in
2149 // %st1.
2150 case ComplexX87:
2151 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner7650d952011-06-18 22:49:11 +00002152 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattnerea044322010-07-29 02:01:43 +00002153 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner519f68c2010-07-28 23:06:14 +00002154 NULL);
2155 break;
2156 }
2157
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002158 llvm::Type *HighPart = 0;
Chris Lattner519f68c2010-07-28 23:06:14 +00002159 switch (Hi) {
2160 // Memory was handled previously and X87 should
2161 // never occur as a hi class.
2162 case Memory:
2163 case X87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002164 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002165
2166 case ComplexX87: // Previously handled.
Chris Lattner0b30c672010-07-28 23:12:33 +00002167 case NoClass:
2168 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002169
Chris Lattner3db4dde2010-09-01 00:20:33 +00002170 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002171 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002172 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2173 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002174 break;
Chris Lattner3db4dde2010-09-01 00:20:33 +00002175 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002176 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002177 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2178 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002179 break;
2180
2181 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002182 // is passed in the next available eightbyte chunk if the last used
2183 // vector register.
Chris Lattner519f68c2010-07-28 23:06:14 +00002184 //
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002185 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner519f68c2010-07-28 23:06:14 +00002186 case SSEUp:
2187 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002188 ResType = GetByteVectorType(RetTy);
Chris Lattner519f68c2010-07-28 23:06:14 +00002189 break;
2190
2191 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2192 // returned together with the previous X87 value in %st0.
2193 case X87Up:
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002194 // If X87Up is preceded by X87, we don't need to do
Chris Lattner519f68c2010-07-28 23:06:14 +00002195 // anything. However, in some cases with unions it may not be
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002196 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner519f68c2010-07-28 23:06:14 +00002197 // extra bits in an SSE reg.
Chris Lattner603519d2010-07-29 17:49:08 +00002198 if (Lo != X87) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002199 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002200 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2201 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner603519d2010-07-29 17:49:08 +00002202 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002203 break;
2204 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002205
Chris Lattner3db4dde2010-09-01 00:20:33 +00002206 // If a high part was specified, merge it together with the low part. It is
Chris Lattner645406a2010-09-01 00:24:35 +00002207 // known to pass in the high eightbyte of the result. We do this by forming a
2208 // first class struct aggregate with the high and low part: {low, high}
Chris Lattner66e7b682010-09-01 00:50:20 +00002209 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002210 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner519f68c2010-07-28 23:06:14 +00002211
Chris Lattnereb518b42010-07-29 21:42:50 +00002212 return ABIArgInfo::getDirect(ResType);
Chris Lattner519f68c2010-07-28 23:06:14 +00002213}
2214
Daniel Dunbaredfac032012-03-10 01:03:58 +00002215ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman7a1b5862013-06-12 00:13:45 +00002216 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2217 bool isNamedArg)
Daniel Dunbaredfac032012-03-10 01:03:58 +00002218 const
2219{
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002220 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002221 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002222
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002223 // Check some invariants.
2224 // FIXME: Enforce these by construction.
2225 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002226 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2227
2228 neededInt = 0;
2229 neededSSE = 0;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002230 llvm::Type *ResType = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002231 switch (Lo) {
2232 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002233 if (Hi == NoClass)
2234 return ABIArgInfo::getIgnore();
2235 // If the low part is just padding, it takes no register, leave ResType
2236 // null.
2237 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2238 "Unknown missing lo part");
2239 break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002240
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002241 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2242 // on the stack.
2243 case Memory:
2244
2245 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2246 // COMPLEX_X87, it is passed in memory.
2247 case X87:
2248 case ComplexX87:
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002249 if (getRecordArgABI(Ty, CGT) == CGCXXABI::RAA_Indirect)
Eli Friedmanded137f2011-06-29 07:04:55 +00002250 ++neededInt;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002251 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002252
2253 case SSEUp:
2254 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002255 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002256
2257 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2258 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2259 // and %r9 is used.
2260 case Integer:
Chris Lattner9c254f02010-06-29 06:01:59 +00002261 ++neededInt;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002262
Chris Lattner49382de2010-07-28 22:44:07 +00002263 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002264 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattnereb518b42010-07-29 21:42:50 +00002265
2266 // If we have a sign or zero extended integer, make sure to return Extend
2267 // so that the parameter gets the right LLVM IR attributes.
2268 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2269 // Treat an enum type as its underlying type.
2270 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2271 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002272
Chris Lattnereb518b42010-07-29 21:42:50 +00002273 if (Ty->isIntegralOrEnumerationType() &&
2274 Ty->isPromotableIntegerType())
2275 return ABIArgInfo::getExtend();
2276 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002277
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002278 break;
2279
2280 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2281 // available SSE register is used, the registers are taken in the
2282 // order from %xmm0 to %xmm7.
Bill Wendlingbb465d72010-10-18 03:41:31 +00002283 case SSE: {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002284 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman14508ff2011-07-02 00:57:27 +00002285 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling99aaae82010-10-18 23:51:38 +00002286 ++neededSSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002287 break;
2288 }
Bill Wendlingbb465d72010-10-18 03:41:31 +00002289 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002290
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002291 llvm::Type *HighPart = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002292 switch (Hi) {
2293 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002294 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002295 // which is passed in memory.
2296 case Memory:
2297 case X87:
2298 case ComplexX87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002299 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002300
2301 case NoClass: break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002302
Chris Lattner645406a2010-09-01 00:24:35 +00002303 case Integer:
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002304 ++neededInt;
Chris Lattner49382de2010-07-28 22:44:07 +00002305 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002306 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002307
Chris Lattner645406a2010-09-01 00:24:35 +00002308 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2309 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002310 break;
2311
2312 // X87Up generally doesn't occur here (long double is passed in
2313 // memory), except in situations involving unions.
2314 case X87Up:
Chris Lattner645406a2010-09-01 00:24:35 +00002315 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002316 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002317
Chris Lattner645406a2010-09-01 00:24:35 +00002318 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2319 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner117e3f42010-07-30 04:02:24 +00002320
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002321 ++neededSSE;
2322 break;
2323
2324 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2325 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002326 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002327 case SSEUp:
Chris Lattnerab5722e2010-07-28 23:47:21 +00002328 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002329 ResType = GetByteVectorType(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002330 break;
2331 }
2332
Chris Lattner645406a2010-09-01 00:24:35 +00002333 // If a high part was specified, merge it together with the low part. It is
2334 // known to pass in the high eightbyte of the result. We do this by forming a
2335 // first class struct aggregate with the high and low part: {low, high}
2336 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002337 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002338
Chris Lattnereb518b42010-07-29 21:42:50 +00002339 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002340}
2341
Chris Lattneree5dcd02010-07-29 02:31:05 +00002342void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002343
Chris Lattnera3c109b2010-07-29 02:16:43 +00002344 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002345
2346 // Keep track of the number of assigned registers.
Bill Wendling99aaae82010-10-18 23:51:38 +00002347 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002348
2349 // If the return value is indirect, then the hidden argument is consuming one
2350 // integer register.
2351 if (FI.getReturnInfo().isIndirect())
2352 --freeIntRegs;
2353
Eli Friedman7a1b5862013-06-12 00:13:45 +00002354 bool isVariadic = FI.isVariadic();
2355 unsigned numRequiredArgs = 0;
2356 if (isVariadic)
2357 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2358
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002359 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2360 // get assigned (in left-to-right order) for passing as follows...
2361 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2362 it != ie; ++it) {
Eli Friedman7a1b5862013-06-12 00:13:45 +00002363 bool isNamedArg = true;
2364 if (isVariadic)
Aaron Ballmaneba7d2f2013-06-12 15:03:45 +00002365 isNamedArg = (it - FI.arg_begin()) <
2366 static_cast<signed>(numRequiredArgs);
Eli Friedman7a1b5862013-06-12 00:13:45 +00002367
Bill Wendling99aaae82010-10-18 23:51:38 +00002368 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002369 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman7a1b5862013-06-12 00:13:45 +00002370 neededSSE, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002371
2372 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2373 // eightbyte of an argument, the whole argument is passed on the
2374 // stack. If registers have already been assigned for some
2375 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling99aaae82010-10-18 23:51:38 +00002376 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002377 freeIntRegs -= neededInt;
2378 freeSSERegs -= neededSSE;
2379 } else {
Daniel Dunbaredfac032012-03-10 01:03:58 +00002380 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002381 }
2382 }
2383}
2384
2385static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2386 QualType Ty,
2387 CodeGenFunction &CGF) {
2388 llvm::Value *overflow_arg_area_p =
2389 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2390 llvm::Value *overflow_arg_area =
2391 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2392
2393 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2394 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedman8d2fe422011-11-18 02:44:19 +00002395 // It isn't stated explicitly in the standard, but in practice we use
2396 // alignment greater than 16 where necessary.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002397 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2398 if (Align > 8) {
Eli Friedman8d2fe422011-11-18 02:44:19 +00002399 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson0032b272009-08-13 21:57:51 +00002400 llvm::Value *Offset =
Eli Friedman8d2fe422011-11-18 02:44:19 +00002401 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002402 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2403 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner77b89b82010-06-27 07:15:29 +00002404 CGF.Int64Ty);
Eli Friedman8d2fe422011-11-18 02:44:19 +00002405 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002406 overflow_arg_area =
2407 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2408 overflow_arg_area->getType(),
2409 "overflow_arg_area.align");
2410 }
2411
2412 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002413 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002414 llvm::Value *Res =
2415 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002416 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002417
2418 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2419 // l->overflow_arg_area + sizeof(type).
2420 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2421 // an 8 byte boundary.
2422
2423 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson0032b272009-08-13 21:57:51 +00002424 llvm::Value *Offset =
Chris Lattner77b89b82010-06-27 07:15:29 +00002425 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002426 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2427 "overflow_arg_area.next");
2428 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2429
2430 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2431 return Res;
2432}
2433
2434llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2435 CodeGenFunction &CGF) const {
2436 // Assume that va_list type is correct; should be pointer to LLVM type:
2437 // struct {
2438 // i32 gp_offset;
2439 // i32 fp_offset;
2440 // i8* overflow_arg_area;
2441 // i8* reg_save_area;
2442 // };
Bill Wendling99aaae82010-10-18 23:51:38 +00002443 unsigned neededInt, neededSSE;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002444
Chris Lattnera14db752010-03-11 18:19:55 +00002445 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman7a1b5862013-06-12 00:13:45 +00002446 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2447 /*isNamedArg*/false);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002448
2449 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2450 // in the registers. If not go to step 7.
2451 if (!neededInt && !neededSSE)
2452 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2453
2454 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2455 // general purpose registers needed to pass type and num_fp to hold
2456 // the number of floating point registers needed.
2457
2458 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2459 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2460 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2461 //
2462 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2463 // register save space).
2464
2465 llvm::Value *InRegs = 0;
2466 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2467 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2468 if (neededInt) {
2469 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2470 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattner1090a9b2010-06-28 21:43:59 +00002471 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2472 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002473 }
2474
2475 if (neededSSE) {
2476 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2477 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2478 llvm::Value *FitsInFP =
Chris Lattner1090a9b2010-06-28 21:43:59 +00002479 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2480 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002481 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2482 }
2483
2484 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2485 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2486 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2487 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2488
2489 // Emit code to load the value if it was passed in registers.
2490
2491 CGF.EmitBlock(InRegBlock);
2492
2493 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2494 // an offset of l->gp_offset and/or l->fp_offset. This may require
2495 // copying to a temporary location in case the parameter is passed
2496 // in different register classes or requires an alignment greater
2497 // than 8 for general purpose registers and 16 for XMM registers.
2498 //
2499 // FIXME: This really results in shameful code when we end up needing to
2500 // collect arguments from different places; often what should result in a
2501 // simple assembling of a structure from scattered addresses has many more
2502 // loads than necessary. Can we clean this up?
Chris Lattner2acc6e32011-07-18 04:24:23 +00002503 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002504 llvm::Value *RegAddr =
2505 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2506 "reg_save_area");
2507 if (neededInt && neededSSE) {
2508 // FIXME: Cleanup.
Chris Lattner800588f2010-07-29 06:26:06 +00002509 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002510 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmaneeb00622013-06-07 23:20:55 +00002511 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2512 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002513 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002514 llvm::Type *TyLo = ST->getElementType(0);
2515 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattnera8b7a7d2010-08-26 06:28:35 +00002516 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002517 "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002518 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2519 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002520 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2521 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002522 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2523 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002524 llvm::Value *V =
2525 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2526 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2527 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2528 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2529
Owen Andersona1cf15f2009-07-14 23:10:40 +00002530 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002531 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002532 } else if (neededInt) {
2533 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2534 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002535 llvm::PointerType::getUnqual(LTy));
Eli Friedmaneeb00622013-06-07 23:20:55 +00002536
2537 // Copy to a temporary if necessary to ensure the appropriate alignment.
2538 std::pair<CharUnits, CharUnits> SizeAlign =
2539 CGF.getContext().getTypeInfoInChars(Ty);
2540 uint64_t TySize = SizeAlign.first.getQuantity();
2541 unsigned TyAlign = SizeAlign.second.getQuantity();
2542 if (TyAlign > 8) {
Eli Friedmaneeb00622013-06-07 23:20:55 +00002543 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2544 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2545 RegAddr = Tmp;
2546 }
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002547 } else if (neededSSE == 1) {
2548 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2549 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2550 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002551 } else {
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002552 assert(neededSSE == 2 && "Invalid number of needed registers!");
2553 // SSE registers are spaced 16 bytes apart in the register save
2554 // area, we need to collect the two eightbytes together.
2555 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattner1090a9b2010-06-28 21:43:59 +00002556 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattner8b418682012-02-07 00:39:47 +00002557 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002558 llvm::Type *DblPtrTy =
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002559 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmaneeb00622013-06-07 23:20:55 +00002560 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2561 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2562 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002563 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2564 DblPtrTy));
2565 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2566 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2567 DblPtrTy));
2568 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2569 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2570 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002571 }
2572
2573 // AMD64-ABI 3.5.7p5: Step 5. Set:
2574 // l->gp_offset = l->gp_offset + num_gp * 8
2575 // l->fp_offset = l->fp_offset + num_fp * 16.
2576 if (neededInt) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002577 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002578 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2579 gp_offset_p);
2580 }
2581 if (neededSSE) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002582 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002583 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2584 fp_offset_p);
2585 }
2586 CGF.EmitBranch(ContBlock);
2587
2588 // Emit code to load the value if it was passed in memory.
2589
2590 CGF.EmitBlock(InMemBlock);
2591 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2592
2593 // Return the appropriate result.
2594
2595 CGF.EmitBlock(ContBlock);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002596 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002597 "vaarg.addr");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002598 ResAddr->addIncoming(RegAddr, InRegBlock);
2599 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002600 return ResAddr;
2601}
2602
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002603ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002604
2605 if (Ty->isVoidType())
2606 return ABIArgInfo::getIgnore();
2607
2608 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2609 Ty = EnumTy->getDecl()->getIntegerType();
2610
2611 uint64_t Size = getContext().getTypeSize(Ty);
2612
2613 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002614 if (IsReturnType) {
2615 if (isRecordReturnIndirect(RT, CGT))
2616 return ABIArgInfo::getIndirect(0, false);
2617 } else {
2618 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, CGT))
2619 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2620 }
2621
2622 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002623 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2624
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002625 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCall64aa4b32013-04-16 22:48:15 +00002626 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002627 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2628 Size));
2629
2630 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2631 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2632 if (Size <= 64 &&
NAKAMURA Takumiff8be0e2011-01-19 00:11:33 +00002633 (Size & (Size - 1)) == 0)
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002634 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2635 Size));
2636
2637 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2638 }
2639
2640 if (Ty->isPromotableIntegerType())
2641 return ABIArgInfo::getExtend();
2642
2643 return ABIArgInfo::getDirect();
2644}
2645
2646void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2647
2648 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002649 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002650
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002651 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2652 it != ie; ++it)
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002653 it->info = classify(it->type, false);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002654}
2655
Chris Lattnerf13721d2010-08-31 16:44:54 +00002656llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2657 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00002658 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002659
Chris Lattnerf13721d2010-08-31 16:44:54 +00002660 CGBuilderTy &Builder = CGF.Builder;
2661 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2662 "ap");
2663 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2664 llvm::Type *PTy =
2665 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2666 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2667
2668 uint64_t Offset =
2669 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2670 llvm::Value *NextAddr =
2671 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2672 "ap.next");
2673 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2674
2675 return AddrTyped;
2676}
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002677
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00002678namespace {
2679
Derek Schuff263366f2012-10-16 22:30:41 +00002680class NaClX86_64ABIInfo : public ABIInfo {
2681 public:
2682 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2683 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2684 virtual void computeInfo(CGFunctionInfo &FI) const;
2685 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2686 CodeGenFunction &CGF) const;
2687 private:
2688 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2689 X86_64ABIInfo NInfo; // Used for everything else.
2690};
2691
2692class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2693 public:
2694 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2695 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2696};
2697
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00002698}
2699
Derek Schuff263366f2012-10-16 22:30:41 +00002700void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2701 if (FI.getASTCallingConvention() == CC_PnaclCall)
2702 PInfo.computeInfo(FI);
2703 else
2704 NInfo.computeInfo(FI);
2705}
2706
2707llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2708 CodeGenFunction &CGF) const {
2709 // Always use the native convention; calling pnacl-style varargs functions
2710 // is unuspported.
2711 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2712}
2713
2714
John McCallec853ba2010-03-11 00:10:12 +00002715// PowerPC-32
2716
2717namespace {
2718class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2719public:
Chris Lattnerea044322010-07-29 02:01:43 +00002720 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002721
John McCallec853ba2010-03-11 00:10:12 +00002722 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2723 // This is recovered from gcc output.
2724 return 1; // r1 is the dedicated stack pointer
2725 }
2726
2727 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002728 llvm::Value *Address) const;
John McCallec853ba2010-03-11 00:10:12 +00002729};
2730
2731}
2732
2733bool
2734PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2735 llvm::Value *Address) const {
2736 // This is calculated from the LLVM and GCC tables and verified
2737 // against gcc output. AFAIK all ABIs use the same encoding.
2738
2739 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallec853ba2010-03-11 00:10:12 +00002740
Chris Lattner8b418682012-02-07 00:39:47 +00002741 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallec853ba2010-03-11 00:10:12 +00002742 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2743 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2744 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2745
2746 // 0-31: r0-31, the 4-byte general-purpose registers
John McCallaeeb7012010-05-27 06:19:26 +00002747 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallec853ba2010-03-11 00:10:12 +00002748
2749 // 32-63: fp0-31, the 8-byte floating-point registers
John McCallaeeb7012010-05-27 06:19:26 +00002750 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallec853ba2010-03-11 00:10:12 +00002751
2752 // 64-76 are various 4-byte special-purpose registers:
2753 // 64: mq
2754 // 65: lr
2755 // 66: ctr
2756 // 67: ap
2757 // 68-75 cr0-7
2758 // 76: xer
John McCallaeeb7012010-05-27 06:19:26 +00002759 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallec853ba2010-03-11 00:10:12 +00002760
2761 // 77-108: v0-31, the 16-byte vector registers
John McCallaeeb7012010-05-27 06:19:26 +00002762 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallec853ba2010-03-11 00:10:12 +00002763
2764 // 109: vrsave
2765 // 110: vscr
2766 // 111: spe_acc
2767 // 112: spefscr
2768 // 113: sfp
John McCallaeeb7012010-05-27 06:19:26 +00002769 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallec853ba2010-03-11 00:10:12 +00002770
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002771 return false;
John McCallec853ba2010-03-11 00:10:12 +00002772}
2773
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002774// PowerPC-64
2775
2776namespace {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002777/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2778class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2779
2780public:
2781 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2782
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002783 bool isPromotableTypeForABI(QualType Ty) const;
2784
2785 ABIArgInfo classifyReturnType(QualType RetTy) const;
2786 ABIArgInfo classifyArgumentType(QualType Ty) const;
2787
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002788 // TODO: We can add more logic to computeInfo to improve performance.
2789 // Example: For aggregate arguments that fit in a register, we could
2790 // use getDirectInReg (as is done below for structs containing a single
2791 // floating-point value) to avoid pushing them to memory on function
2792 // entry. This would require changing the logic in PPCISelLowering
2793 // when lowering the parameters in the caller and args in the callee.
2794 virtual void computeInfo(CGFunctionInfo &FI) const {
2795 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2796 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2797 it != ie; ++it) {
2798 // We rely on the default argument classification for the most part.
2799 // One exception: An aggregate containing a single floating-point
Bill Schmidtb1993102013-07-23 22:15:57 +00002800 // or vector item must be passed in a register if one is available.
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002801 const Type *T = isSingleElementStruct(it->type, getContext());
2802 if (T) {
2803 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidtb1993102013-07-23 22:15:57 +00002804 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002805 QualType QT(T, 0);
2806 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2807 continue;
2808 }
2809 }
2810 it->info = classifyArgumentType(it->type);
2811 }
2812 }
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002813
2814 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2815 QualType Ty,
2816 CodeGenFunction &CGF) const;
2817};
2818
2819class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2820public:
2821 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2822 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2823
2824 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2825 // This is recovered from gcc output.
2826 return 1; // r1 is the dedicated stack pointer
2827 }
2828
2829 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2830 llvm::Value *Address) const;
2831};
2832
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002833class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2834public:
2835 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2836
2837 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2838 // This is recovered from gcc output.
2839 return 1; // r1 is the dedicated stack pointer
2840 }
2841
2842 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2843 llvm::Value *Address) const;
2844};
2845
2846}
2847
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002848// Return true if the ABI requires Ty to be passed sign- or zero-
2849// extended to 64 bits.
2850bool
2851PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2852 // Treat an enum type as its underlying type.
2853 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2854 Ty = EnumTy->getDecl()->getIntegerType();
2855
2856 // Promotable integer types are required to be promoted by the ABI.
2857 if (Ty->isPromotableIntegerType())
2858 return true;
2859
2860 // In addition to the usual promotable integer types, we also need to
2861 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2862 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2863 switch (BT->getKind()) {
2864 case BuiltinType::Int:
2865 case BuiltinType::UInt:
2866 return true;
2867 default:
2868 break;
2869 }
2870
2871 return false;
2872}
2873
2874ABIArgInfo
2875PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidtc9715fc2012-11-27 02:46:43 +00002876 if (Ty->isAnyComplexType())
2877 return ABIArgInfo::getDirect();
2878
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002879 if (isAggregateTypeForABI(Ty)) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002880 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
2881 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002882
2883 return ABIArgInfo::getIndirect(0);
2884 }
2885
2886 return (isPromotableTypeForABI(Ty) ?
2887 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2888}
2889
2890ABIArgInfo
2891PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
2892 if (RetTy->isVoidType())
2893 return ABIArgInfo::getIgnore();
2894
Bill Schmidt9e6111a2012-12-17 04:20:17 +00002895 if (RetTy->isAnyComplexType())
2896 return ABIArgInfo::getDirect();
2897
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002898 if (isAggregateTypeForABI(RetTy))
2899 return ABIArgInfo::getIndirect(0);
2900
2901 return (isPromotableTypeForABI(RetTy) ?
2902 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2903}
2904
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002905// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
2906llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2907 QualType Ty,
2908 CodeGenFunction &CGF) const {
2909 llvm::Type *BP = CGF.Int8PtrTy;
2910 llvm::Type *BPP = CGF.Int8PtrPtrTy;
2911
2912 CGBuilderTy &Builder = CGF.Builder;
2913 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2914 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2915
Bill Schmidt19f8e852013-01-14 17:45:36 +00002916 // Update the va_list pointer. The pointer should be bumped by the
2917 // size of the object. We can trust getTypeSize() except for a complex
2918 // type whose base type is smaller than a doubleword. For these, the
2919 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002920 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt19f8e852013-01-14 17:45:36 +00002921 QualType BaseTy;
2922 unsigned CplxBaseSize = 0;
2923
2924 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
2925 BaseTy = CTy->getElementType();
2926 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
2927 if (CplxBaseSize < 8)
2928 SizeInBytes = 16;
2929 }
2930
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002931 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
2932 llvm::Value *NextAddr =
2933 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
2934 "ap.next");
2935 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2936
Bill Schmidt19f8e852013-01-14 17:45:36 +00002937 // If we have a complex type and the base type is smaller than 8 bytes,
2938 // the ABI calls for the real and imaginary parts to be right-adjusted
2939 // in separate doublewords. However, Clang expects us to produce a
2940 // pointer to a structure with the two parts packed tightly. So generate
2941 // loads of the real and imaginary parts relative to the va_list pointer,
2942 // and store them to a temporary structure.
2943 if (CplxBaseSize && CplxBaseSize < 8) {
2944 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2945 llvm::Value *ImagAddr = RealAddr;
2946 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
2947 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
2948 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
2949 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
2950 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
2951 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
2952 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
2953 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
2954 "vacplx");
2955 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
2956 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
2957 Builder.CreateStore(Real, RealPtr, false);
2958 Builder.CreateStore(Imag, ImagPtr, false);
2959 return Ptr;
2960 }
2961
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002962 // If the argument is smaller than 8 bytes, it is right-adjusted in
2963 // its doubleword slot. Adjust the pointer to pick it up from the
2964 // correct offset.
2965 if (SizeInBytes < 8) {
2966 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2967 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
2968 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2969 }
2970
2971 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2972 return Builder.CreateBitCast(Addr, PTy);
2973}
2974
2975static bool
2976PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2977 llvm::Value *Address) {
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002978 // This is calculated from the LLVM and GCC tables and verified
2979 // against gcc output. AFAIK all ABIs use the same encoding.
2980
2981 CodeGen::CGBuilderTy &Builder = CGF.Builder;
2982
2983 llvm::IntegerType *i8 = CGF.Int8Ty;
2984 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2985 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2986 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2987
2988 // 0-31: r0-31, the 8-byte general-purpose registers
2989 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
2990
2991 // 32-63: fp0-31, the 8-byte floating-point registers
2992 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2993
2994 // 64-76 are various 4-byte special-purpose registers:
2995 // 64: mq
2996 // 65: lr
2997 // 66: ctr
2998 // 67: ap
2999 // 68-75 cr0-7
3000 // 76: xer
3001 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3002
3003 // 77-108: v0-31, the 16-byte vector registers
3004 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3005
3006 // 109: vrsave
3007 // 110: vscr
3008 // 111: spe_acc
3009 // 112: spefscr
3010 // 113: sfp
3011 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3012
3013 return false;
3014}
John McCallec853ba2010-03-11 00:10:12 +00003015
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003016bool
3017PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3018 CodeGen::CodeGenFunction &CGF,
3019 llvm::Value *Address) const {
3020
3021 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3022}
3023
3024bool
3025PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3026 llvm::Value *Address) const {
3027
3028 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3029}
3030
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003031//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003032// ARM ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003033//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003034
3035namespace {
3036
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003037class ARMABIInfo : public ABIInfo {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003038public:
3039 enum ABIKind {
3040 APCS = 0,
3041 AAPCS = 1,
3042 AAPCS_VFP
3043 };
3044
3045private:
3046 ABIKind Kind;
3047
3048public:
John McCallbd7370a2013-02-28 19:01:20 +00003049 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
3050 setRuntimeCC();
3051 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003052
John McCall49e34be2011-08-30 01:42:09 +00003053 bool isEABI() const {
John McCall64aa4b32013-04-16 22:48:15 +00003054 StringRef Env = getTarget().getTriple().getEnvironmentName();
Logan Chien94a71422012-09-02 09:30:11 +00003055 return (Env == "gnueabi" || Env == "eabi" ||
3056 Env == "android" || Env == "androideabi");
John McCall49e34be2011-08-30 01:42:09 +00003057 }
3058
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003059 ABIKind getABIKind() const { return Kind; }
3060
Tim Northover64eac852013-10-01 14:34:25 +00003061private:
Chris Lattnera3c109b2010-07-29 02:16:43 +00003062 ABIArgInfo classifyReturnType(QualType RetTy) const;
Manman Ren710c5172012-10-31 19:02:26 +00003063 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs,
3064 unsigned &AllocatedVFP,
Manman Renb3fa55f2012-10-30 23:21:41 +00003065 bool &IsHA) const;
Manman Ren97f81572012-10-16 19:18:39 +00003066 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003067
Chris Lattneree5dcd02010-07-29 02:31:05 +00003068 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003069
3070 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3071 CodeGenFunction &CGF) const;
John McCallbd7370a2013-02-28 19:01:20 +00003072
3073 llvm::CallingConv::ID getLLVMDefaultCC() const;
3074 llvm::CallingConv::ID getABIDefaultCC() const;
3075 void setRuntimeCC();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003076};
3077
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00003078class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3079public:
Chris Lattnerea044322010-07-29 02:01:43 +00003080 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3081 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCall6374c332010-03-06 00:35:14 +00003082
John McCall49e34be2011-08-30 01:42:09 +00003083 const ARMABIInfo &getABIInfo() const {
3084 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3085 }
3086
John McCall6374c332010-03-06 00:35:14 +00003087 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3088 return 13;
3089 }
Roman Divacky09345d12011-05-18 19:36:54 +00003090
Chris Lattner5f9e2722011-07-23 10:55:15 +00003091 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
John McCallf85e1932011-06-15 23:02:42 +00003092 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3093 }
3094
Roman Divacky09345d12011-05-18 19:36:54 +00003095 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3096 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00003097 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divacky09345d12011-05-18 19:36:54 +00003098
3099 // 0-15 are the 16 integer registers.
Chris Lattner8b418682012-02-07 00:39:47 +00003100 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divacky09345d12011-05-18 19:36:54 +00003101 return false;
3102 }
John McCall49e34be2011-08-30 01:42:09 +00003103
3104 unsigned getSizeOfUnwindException() const {
3105 if (getABIInfo().isEABI()) return 88;
3106 return TargetCodeGenInfo::getSizeOfUnwindException();
3107 }
Tim Northover64eac852013-10-01 14:34:25 +00003108
3109 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3110 CodeGen::CodeGenModule &CGM) const {
3111 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3112 if (!FD)
3113 return;
3114
3115 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3116 if (!Attr)
3117 return;
3118
3119 const char *Kind;
3120 switch (Attr->getInterrupt()) {
3121 case ARMInterruptAttr::Generic: Kind = ""; break;
3122 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3123 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3124 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3125 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3126 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3127 }
3128
3129 llvm::Function *Fn = cast<llvm::Function>(GV);
3130
3131 Fn->addFnAttr("interrupt", Kind);
3132
3133 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3134 return;
3135
3136 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3137 // however this is not necessarily true on taking any interrupt. Instruct
3138 // the backend to perform a realignment as part of the function prologue.
3139 llvm::AttrBuilder B;
3140 B.addStackAlignmentAttr(8);
3141 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3142 llvm::AttributeSet::get(CGM.getLLVMContext(),
3143 llvm::AttributeSet::FunctionIndex,
3144 B));
3145 }
3146
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00003147};
3148
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003149}
3150
Chris Lattneree5dcd02010-07-29 02:31:05 +00003151void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Renb3fa55f2012-10-30 23:21:41 +00003152 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Ren710c5172012-10-31 19:02:26 +00003153 // VFP registers allocated so far.
Manman Renb3fa55f2012-10-30 23:21:41 +00003154 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3155 // VFP registers of the appropriate type unallocated then the argument is
3156 // allocated to the lowest-numbered sequence of such registers.
3157 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3158 // unallocated are marked as unavailable.
3159 unsigned AllocatedVFP = 0;
Manman Ren710c5172012-10-31 19:02:26 +00003160 int VFPRegs[16] = { 0 };
Chris Lattnera3c109b2010-07-29 02:16:43 +00003161 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003162 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Manman Renb3fa55f2012-10-30 23:21:41 +00003163 it != ie; ++it) {
3164 unsigned PreAllocation = AllocatedVFP;
3165 bool IsHA = false;
3166 // 6.1.2.3 There is one VFP co-processor register class using registers
3167 // s0-s15 (d0-d7) for passing arguments.
3168 const unsigned NumVFPs = 16;
Manman Ren710c5172012-10-31 19:02:26 +00003169 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA);
Manman Renb3fa55f2012-10-30 23:21:41 +00003170 // If we do not have enough VFP registers for the HA, any VFP registers
3171 // that are unallocated are marked as unavailable. To achieve this, we add
3172 // padding of (NumVFPs - PreAllocation) floats.
3173 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3174 llvm::Type *PaddingTy = llvm::ArrayType::get(
3175 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3176 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3177 }
3178 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003179
Anton Korobeynikov414d8962011-04-14 20:06:49 +00003180 // Always honor user-specified calling convention.
3181 if (FI.getCallingConvention() != llvm::CallingConv::C)
3182 return;
3183
John McCallbd7370a2013-02-28 19:01:20 +00003184 llvm::CallingConv::ID cc = getRuntimeCC();
3185 if (cc != llvm::CallingConv::C)
3186 FI.setEffectiveCallingConvention(cc);
3187}
Rafael Espindola25117ab2010-06-16 16:13:39 +00003188
John McCallbd7370a2013-02-28 19:01:20 +00003189/// Return the default calling convention that LLVM will use.
3190llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3191 // The default calling convention that LLVM will infer.
John McCall64aa4b32013-04-16 22:48:15 +00003192 if (getTarget().getTriple().getEnvironmentName()=="gnueabihf")
John McCallbd7370a2013-02-28 19:01:20 +00003193 return llvm::CallingConv::ARM_AAPCS_VFP;
3194 else if (isEABI())
3195 return llvm::CallingConv::ARM_AAPCS;
3196 else
3197 return llvm::CallingConv::ARM_APCS;
3198}
3199
3200/// Return the calling convention that our ABI would like us to use
3201/// as the C calling convention.
3202llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003203 switch (getABIKind()) {
John McCallbd7370a2013-02-28 19:01:20 +00003204 case APCS: return llvm::CallingConv::ARM_APCS;
3205 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3206 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003207 }
John McCallbd7370a2013-02-28 19:01:20 +00003208 llvm_unreachable("bad ABI kind");
3209}
3210
3211void ARMABIInfo::setRuntimeCC() {
3212 assert(getRuntimeCC() == llvm::CallingConv::C);
3213
3214 // Don't muddy up the IR with a ton of explicit annotations if
3215 // they'd just match what LLVM will infer from the triple.
3216 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3217 if (abiCC != getLLVMDefaultCC())
3218 RuntimeCC = abiCC;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003219}
3220
Bob Wilson194f06a2011-08-03 05:58:22 +00003221/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3222/// aggregate. If HAMembers is non-null, the number of base elements
3223/// contained in the type is returned through it; this is used for the
3224/// recursive calls that check aggregate component types.
3225static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3226 ASTContext &Context,
3227 uint64_t *HAMembers = 0) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003228 uint64_t Members = 0;
Bob Wilson194f06a2011-08-03 05:58:22 +00003229 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3230 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3231 return false;
3232 Members *= AT->getSize().getZExtValue();
3233 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3234 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003235 if (RD->hasFlexibleArrayMember())
Bob Wilson194f06a2011-08-03 05:58:22 +00003236 return false;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003237
Bob Wilson194f06a2011-08-03 05:58:22 +00003238 Members = 0;
3239 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3240 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003241 const FieldDecl *FD = *i;
Bob Wilson194f06a2011-08-03 05:58:22 +00003242 uint64_t FldMembers;
3243 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3244 return false;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003245
3246 Members = (RD->isUnion() ?
3247 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilson194f06a2011-08-03 05:58:22 +00003248 }
3249 } else {
3250 Members = 1;
3251 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3252 Members = 2;
3253 Ty = CT->getElementType();
3254 }
3255
3256 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3257 // double, or 64-bit or 128-bit vectors.
3258 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3259 if (BT->getKind() != BuiltinType::Float &&
Tim Northoveradfa45f2012-07-20 22:29:29 +00003260 BT->getKind() != BuiltinType::Double &&
3261 BT->getKind() != BuiltinType::LongDouble)
Bob Wilson194f06a2011-08-03 05:58:22 +00003262 return false;
3263 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3264 unsigned VecSize = Context.getTypeSize(VT);
3265 if (VecSize != 64 && VecSize != 128)
3266 return false;
3267 } else {
3268 return false;
3269 }
3270
3271 // The base type must be the same for all members. Vector types of the
3272 // same total size are treated as being equivalent here.
3273 const Type *TyPtr = Ty.getTypePtr();
3274 if (!Base)
3275 Base = TyPtr;
3276 if (Base != TyPtr &&
3277 (!Base->isVectorType() || !TyPtr->isVectorType() ||
3278 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
3279 return false;
3280 }
3281
3282 // Homogeneous Aggregates can have at most 4 members of the base type.
3283 if (HAMembers)
3284 *HAMembers = Members;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003285
3286 return (Members > 0 && Members <= 4);
Bob Wilson194f06a2011-08-03 05:58:22 +00003287}
3288
Manman Ren710c5172012-10-31 19:02:26 +00003289/// markAllocatedVFPs - update VFPRegs according to the alignment and
3290/// number of VFP registers (unit is S register) requested.
3291static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP,
3292 unsigned Alignment,
3293 unsigned NumRequired) {
3294 // Early Exit.
3295 if (AllocatedVFP >= 16)
3296 return;
3297 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3298 // VFP registers of the appropriate type unallocated then the argument is
3299 // allocated to the lowest-numbered sequence of such registers.
3300 for (unsigned I = 0; I < 16; I += Alignment) {
3301 bool FoundSlot = true;
3302 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3303 if (J >= 16 || VFPRegs[J]) {
3304 FoundSlot = false;
3305 break;
3306 }
3307 if (FoundSlot) {
3308 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3309 VFPRegs[J] = 1;
3310 AllocatedVFP += NumRequired;
3311 return;
3312 }
3313 }
3314 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3315 // unallocated are marked as unavailable.
3316 for (unsigned I = 0; I < 16; I++)
3317 VFPRegs[I] = 1;
3318 AllocatedVFP = 17; // We do not have enough VFP registers.
3319}
3320
3321ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
3322 unsigned &AllocatedVFP,
Manman Renb3fa55f2012-10-30 23:21:41 +00003323 bool &IsHA) const {
3324 // We update number of allocated VFPs according to
3325 // 6.1.2.1 The following argument types are VFP CPRCs:
3326 // A single-precision floating-point type (including promoted
3327 // half-precision types); A double-precision floating-point type;
3328 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3329 // with a Base Type of a single- or double-precision floating-point type,
3330 // 64-bit containerized vectors or 128-bit containerized vectors with one
3331 // to four Elements.
3332
Manman Ren97f81572012-10-16 19:18:39 +00003333 // Handle illegal vector types here.
3334 if (isIllegalVectorType(Ty)) {
3335 uint64_t Size = getContext().getTypeSize(Ty);
3336 if (Size <= 32) {
3337 llvm::Type *ResType =
3338 llvm::Type::getInt32Ty(getVMContext());
3339 return ABIArgInfo::getDirect(ResType);
3340 }
3341 if (Size == 64) {
3342 llvm::Type *ResType = llvm::VectorType::get(
3343 llvm::Type::getInt32Ty(getVMContext()), 2);
Manman Ren710c5172012-10-31 19:02:26 +00003344 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Ren97f81572012-10-16 19:18:39 +00003345 return ABIArgInfo::getDirect(ResType);
3346 }
3347 if (Size == 128) {
3348 llvm::Type *ResType = llvm::VectorType::get(
3349 llvm::Type::getInt32Ty(getVMContext()), 4);
Manman Ren710c5172012-10-31 19:02:26 +00003350 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4);
Manman Ren97f81572012-10-16 19:18:39 +00003351 return ABIArgInfo::getDirect(ResType);
3352 }
3353 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3354 }
Manman Ren710c5172012-10-31 19:02:26 +00003355 // Update VFPRegs for legal vector types.
Manman Renb3fa55f2012-10-30 23:21:41 +00003356 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3357 uint64_t Size = getContext().getTypeSize(VT);
3358 // Size of a legal vector should be power of 2 and above 64.
Manman Ren710c5172012-10-31 19:02:26 +00003359 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32);
Manman Renb3fa55f2012-10-30 23:21:41 +00003360 }
Manman Ren710c5172012-10-31 19:02:26 +00003361 // Update VFPRegs for floating point types.
Manman Renb3fa55f2012-10-30 23:21:41 +00003362 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3363 if (BT->getKind() == BuiltinType::Half ||
3364 BT->getKind() == BuiltinType::Float)
Manman Ren710c5172012-10-31 19:02:26 +00003365 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1);
Manman Renb3fa55f2012-10-30 23:21:41 +00003366 if (BT->getKind() == BuiltinType::Double ||
Manman Ren710c5172012-10-31 19:02:26 +00003367 BT->getKind() == BuiltinType::LongDouble)
3368 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Renb3fa55f2012-10-30 23:21:41 +00003369 }
Manman Ren97f81572012-10-16 19:18:39 +00003370
John McCalld608cdb2010-08-22 10:59:02 +00003371 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003372 // Treat an enum type as its underlying type.
3373 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3374 Ty = EnumTy->getDecl()->getIntegerType();
3375
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00003376 return (Ty->isPromotableIntegerType() ?
3377 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003378 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003379
Tim Northoverf5c3a252013-06-21 22:49:34 +00003380 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
3381 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3382
Daniel Dunbar42025572009-09-14 21:54:03 +00003383 // Ignore empty records.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003384 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar42025572009-09-14 21:54:03 +00003385 return ABIArgInfo::getIgnore();
3386
Bob Wilson194f06a2011-08-03 05:58:22 +00003387 if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
Manman Renb3fa55f2012-10-30 23:21:41 +00003388 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3389 // into VFP registers.
Bob Wilson194f06a2011-08-03 05:58:22 +00003390 const Type *Base = 0;
Manman Renb3fa55f2012-10-30 23:21:41 +00003391 uint64_t Members = 0;
3392 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003393 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Renb3fa55f2012-10-30 23:21:41 +00003394 // Base can be a floating-point or a vector.
3395 if (Base->isVectorType()) {
3396 // ElementSize is in number of floats.
3397 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Manman Rencb489dd2012-11-06 19:05:29 +00003398 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize,
3399 Members * ElementSize);
Manman Renb3fa55f2012-10-30 23:21:41 +00003400 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Manman Ren710c5172012-10-31 19:02:26 +00003401 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members);
Manman Renb3fa55f2012-10-30 23:21:41 +00003402 else {
3403 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3404 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Manman Ren710c5172012-10-31 19:02:26 +00003405 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2);
Manman Renb3fa55f2012-10-30 23:21:41 +00003406 }
3407 IsHA = true;
Bob Wilson194f06a2011-08-03 05:58:22 +00003408 return ABIArgInfo::getExpand();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003409 }
Bob Wilson194f06a2011-08-03 05:58:22 +00003410 }
3411
Manman Ren634b3d22012-08-13 21:23:55 +00003412 // Support byval for ARM.
Manman Rencb489dd2012-11-06 19:05:29 +00003413 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3414 // most 8-byte. We realign the indirect argument if type alignment is bigger
3415 // than ABI alignment.
Manman Renfd1ba912012-11-05 22:42:46 +00003416 uint64_t ABIAlign = 4;
3417 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3418 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3419 getABIKind() == ARMABIInfo::AAPCS)
3420 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren885ad692012-11-06 04:58:01 +00003421 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
3422 return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
Manman Rencb489dd2012-11-06 19:05:29 +00003423 /*Realign=*/TyAlign > ABIAlign);
Eli Friedman79f30982012-08-09 00:31:40 +00003424 }
3425
Daniel Dunbar8aa87c72010-09-23 01:54:28 +00003426 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003427 llvm::Type* ElemTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003428 unsigned SizeRegs;
Eli Friedman79f30982012-08-09 00:31:40 +00003429 // FIXME: Try to match the types of the arguments more accurately where
3430 // we can.
3431 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson53fc1a62011-08-01 23:39:04 +00003432 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3433 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren78eb76e2012-06-25 22:04:00 +00003434 } else {
Manman Ren78eb76e2012-06-25 22:04:00 +00003435 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3436 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastings67d097e2011-04-27 17:24:02 +00003437 }
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00003438
Chris Lattner9cbe4f02011-07-09 17:41:47 +00003439 llvm::Type *STy =
Chris Lattner7650d952011-06-18 22:49:11 +00003440 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00003441 return ABIArgInfo::getDirect(STy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003442}
3443
Chris Lattnera3c109b2010-07-29 02:16:43 +00003444static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar98303b92009-09-13 08:03:58 +00003445 llvm::LLVMContext &VMContext) {
3446 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3447 // is called integer-like if its size is less than or equal to one word, and
3448 // the offset of each of its addressable sub-fields is zero.
3449
3450 uint64_t Size = Context.getTypeSize(Ty);
3451
3452 // Check that the type fits in a word.
3453 if (Size > 32)
3454 return false;
3455
3456 // FIXME: Handle vector types!
3457 if (Ty->isVectorType())
3458 return false;
3459
Daniel Dunbarb0d58192009-09-14 02:20:34 +00003460 // Float types are never treated as "integer like".
3461 if (Ty->isRealFloatingType())
3462 return false;
3463
Daniel Dunbar98303b92009-09-13 08:03:58 +00003464 // If this is a builtin or pointer type then it is ok.
John McCall183700f2009-09-21 23:43:11 +00003465 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar98303b92009-09-13 08:03:58 +00003466 return true;
3467
Daniel Dunbar45815812010-02-01 23:31:26 +00003468 // Small complex integer types are "integer like".
3469 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3470 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar98303b92009-09-13 08:03:58 +00003471
3472 // Single element and zero sized arrays should be allowed, by the definition
3473 // above, but they are not.
3474
3475 // Otherwise, it must be a record type.
3476 const RecordType *RT = Ty->getAs<RecordType>();
3477 if (!RT) return false;
3478
3479 // Ignore records with flexible arrays.
3480 const RecordDecl *RD = RT->getDecl();
3481 if (RD->hasFlexibleArrayMember())
3482 return false;
3483
3484 // Check that all sub-fields are at offset 0, and are themselves "integer
3485 // like".
3486 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3487
3488 bool HadField = false;
3489 unsigned idx = 0;
3490 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3491 i != e; ++i, ++idx) {
David Blaikie581deb32012-06-06 20:45:41 +00003492 const FieldDecl *FD = *i;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003493
Daniel Dunbar679855a2010-01-29 03:22:29 +00003494 // Bit-fields are not addressable, we only need to verify they are "integer
3495 // like". We still have to disallow a subsequent non-bitfield, for example:
3496 // struct { int : 0; int x }
3497 // is non-integer like according to gcc.
3498 if (FD->isBitField()) {
3499 if (!RD->isUnion())
3500 HadField = true;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003501
Daniel Dunbar679855a2010-01-29 03:22:29 +00003502 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3503 return false;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003504
Daniel Dunbar679855a2010-01-29 03:22:29 +00003505 continue;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003506 }
3507
Daniel Dunbar679855a2010-01-29 03:22:29 +00003508 // Check if this field is at offset 0.
3509 if (Layout.getFieldOffset(idx) != 0)
3510 return false;
3511
Daniel Dunbar98303b92009-09-13 08:03:58 +00003512 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3513 return false;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00003514
Daniel Dunbar679855a2010-01-29 03:22:29 +00003515 // Only allow at most one field in a structure. This doesn't match the
3516 // wording above, but follows gcc in situations with a field following an
3517 // empty structure.
Daniel Dunbar98303b92009-09-13 08:03:58 +00003518 if (!RD->isUnion()) {
3519 if (HadField)
3520 return false;
3521
3522 HadField = true;
3523 }
3524 }
3525
3526 return true;
3527}
3528
Chris Lattnera3c109b2010-07-29 02:16:43 +00003529ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
Daniel Dunbar98303b92009-09-13 08:03:58 +00003530 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003531 return ABIArgInfo::getIgnore();
Daniel Dunbar98303b92009-09-13 08:03:58 +00003532
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00003533 // Large vector types should be returned via memory.
3534 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3535 return ABIArgInfo::getIndirect(0);
3536
John McCalld608cdb2010-08-22 10:59:02 +00003537 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003538 // Treat an enum type as its underlying type.
3539 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3540 RetTy = EnumTy->getDecl()->getIntegerType();
3541
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00003542 return (RetTy->isPromotableIntegerType() ?
3543 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003544 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003545
Rafael Espindola0eb1d972010-06-08 02:42:08 +00003546 // Structures with either a non-trivial destructor or a non-trivial
3547 // copy constructor are always indirect.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003548 if (isRecordReturnIndirect(RetTy, CGT))
Rafael Espindola0eb1d972010-06-08 02:42:08 +00003549 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3550
Daniel Dunbar98303b92009-09-13 08:03:58 +00003551 // Are we following APCS?
3552 if (getABIKind() == APCS) {
Chris Lattnera3c109b2010-07-29 02:16:43 +00003553 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar98303b92009-09-13 08:03:58 +00003554 return ABIArgInfo::getIgnore();
3555
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00003556 // Complex types are all returned as packed integers.
3557 //
3558 // FIXME: Consider using 2 x vector types if the back end handles them
3559 // correctly.
3560 if (RetTy->isAnyComplexType())
Chris Lattner800588f2010-07-29 06:26:06 +00003561 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +00003562 getContext().getTypeSize(RetTy)));
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00003563
Daniel Dunbar98303b92009-09-13 08:03:58 +00003564 // Integer like structures are returned in r0.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003565 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar98303b92009-09-13 08:03:58 +00003566 // Return in the smallest viable integer type.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003567 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar98303b92009-09-13 08:03:58 +00003568 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00003569 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00003570 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00003571 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3572 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00003573 }
3574
3575 // Otherwise return in memory.
3576 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003577 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003578
3579 // Otherwise this is an AAPCS variant.
3580
Chris Lattnera3c109b2010-07-29 02:16:43 +00003581 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar16a08082009-09-14 00:56:55 +00003582 return ABIArgInfo::getIgnore();
3583
Bob Wilson3b694fa2011-11-02 04:51:36 +00003584 // Check for homogeneous aggregates with AAPCS-VFP.
3585 if (getABIKind() == AAPCS_VFP) {
3586 const Type *Base = 0;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003587 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3588 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson3b694fa2011-11-02 04:51:36 +00003589 // Homogeneous Aggregates are returned directly.
3590 return ABIArgInfo::getDirect();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003591 }
Bob Wilson3b694fa2011-11-02 04:51:36 +00003592 }
3593
Daniel Dunbar98303b92009-09-13 08:03:58 +00003594 // Aggregates <= 4 bytes are returned in r0; other aggregates
3595 // are returned indirectly.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003596 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar16a08082009-09-14 00:56:55 +00003597 if (Size <= 32) {
3598 // Return in the smallest viable integer type.
3599 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00003600 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00003601 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00003602 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3603 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00003604 }
3605
Daniel Dunbar98303b92009-09-13 08:03:58 +00003606 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003607}
3608
Manman Ren97f81572012-10-16 19:18:39 +00003609/// isIllegalVector - check whether Ty is an illegal vector type.
3610bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3611 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3612 // Check whether VT is legal.
3613 unsigned NumElements = VT->getNumElements();
3614 uint64_t Size = getContext().getTypeSize(VT);
3615 // NumElements should be power of 2.
3616 if ((NumElements & (NumElements - 1)) != 0)
3617 return true;
3618 // Size should be greater than 32 bits.
3619 return Size <= 32;
3620 }
3621 return false;
3622}
3623
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003624llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner77b89b82010-06-27 07:15:29 +00003625 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00003626 llvm::Type *BP = CGF.Int8PtrTy;
3627 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003628
3629 CGBuilderTy &Builder = CGF.Builder;
Chris Lattner8b418682012-02-07 00:39:47 +00003630 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003631 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rend105e732012-10-16 19:01:37 +00003632
Tim Northover373ac0a2013-06-21 23:05:33 +00003633 if (isEmptyRecord(getContext(), Ty, true)) {
3634 // These are ignored for parameter passing purposes.
3635 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3636 return Builder.CreateBitCast(Addr, PTy);
3637 }
3638
Manman Rend105e732012-10-16 19:01:37 +00003639 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindolae164c182011-08-02 22:33:37 +00003640 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Ren97f81572012-10-16 19:18:39 +00003641 bool IsIndirect = false;
Manman Rend105e732012-10-16 19:01:37 +00003642
3643 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3644 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren93371022012-10-16 19:51:48 +00003645 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3646 getABIKind() == ARMABIInfo::AAPCS)
3647 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3648 else
3649 TyAlign = 4;
Manman Ren97f81572012-10-16 19:18:39 +00003650 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3651 if (isIllegalVectorType(Ty) && Size > 16) {
3652 IsIndirect = true;
3653 Size = 4;
3654 TyAlign = 4;
3655 }
Manman Rend105e732012-10-16 19:01:37 +00003656
3657 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindolae164c182011-08-02 22:33:37 +00003658 if (TyAlign > 4) {
3659 assert((TyAlign & (TyAlign - 1)) == 0 &&
3660 "Alignment is not power of 2!");
3661 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3662 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3663 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rend105e732012-10-16 19:01:37 +00003664 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindolae164c182011-08-02 22:33:37 +00003665 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003666
3667 uint64_t Offset =
Manman Rend105e732012-10-16 19:01:37 +00003668 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003669 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00003670 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003671 "ap.next");
3672 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3673
Manman Ren97f81572012-10-16 19:18:39 +00003674 if (IsIndirect)
3675 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren93371022012-10-16 19:51:48 +00003676 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rend105e732012-10-16 19:01:37 +00003677 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3678 // may not be correctly aligned for the vector type. We create an aligned
3679 // temporary space and copy the content over from ap.cur to the temporary
3680 // space. This is necessary if the natural alignment of the type is greater
3681 // than the ABI alignment.
3682 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3683 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3684 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3685 "var.align");
3686 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3687 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3688 Builder.CreateMemCpy(Dst, Src,
3689 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3690 TyAlign, false);
3691 Addr = AlignedTemp; //The content is in aligned location.
3692 }
3693 llvm::Type *PTy =
3694 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3695 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3696
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003697 return AddrTyped;
3698}
3699
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00003700namespace {
3701
Derek Schuff263366f2012-10-16 22:30:41 +00003702class NaClARMABIInfo : public ABIInfo {
3703 public:
3704 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3705 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3706 virtual void computeInfo(CGFunctionInfo &FI) const;
3707 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3708 CodeGenFunction &CGF) const;
3709 private:
3710 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3711 ARMABIInfo NInfo; // Used for everything else.
3712};
3713
3714class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3715 public:
3716 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3717 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3718};
3719
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00003720}
3721
Derek Schuff263366f2012-10-16 22:30:41 +00003722void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3723 if (FI.getASTCallingConvention() == CC_PnaclCall)
3724 PInfo.computeInfo(FI);
3725 else
3726 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3727}
3728
3729llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3730 CodeGenFunction &CGF) const {
3731 // Always use the native convention; calling pnacl-style varargs functions
3732 // is unsupported.
3733 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3734}
3735
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003736//===----------------------------------------------------------------------===//
Tim Northoverc264e162013-01-31 12:13:10 +00003737// AArch64 ABI Implementation
3738//===----------------------------------------------------------------------===//
3739
3740namespace {
3741
3742class AArch64ABIInfo : public ABIInfo {
3743public:
3744 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3745
3746private:
3747 // The AArch64 PCS is explicit about return types and argument types being
3748 // handled identically, so we don't need to draw a distinction between
3749 // Argument and Return classification.
3750 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3751 int &FreeVFPRegs) const;
3752
3753 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3754 llvm::Type *DirectTy = 0) const;
3755
3756 virtual void computeInfo(CGFunctionInfo &FI) const;
3757
3758 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3759 CodeGenFunction &CGF) const;
3760};
3761
3762class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3763public:
3764 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3765 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3766
3767 const AArch64ABIInfo &getABIInfo() const {
3768 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3769 }
3770
3771 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3772 return 31;
3773 }
3774
3775 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3776 llvm::Value *Address) const {
3777 // 0-31 are x0-x30 and sp: 8 bytes each
3778 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
3779 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
3780
3781 // 64-95 are v0-v31: 16 bytes each
3782 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
3783 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
3784
3785 return false;
3786 }
3787
3788};
3789
3790}
3791
3792void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3793 int FreeIntRegs = 8, FreeVFPRegs = 8;
3794
3795 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
3796 FreeIntRegs, FreeVFPRegs);
3797
3798 FreeIntRegs = FreeVFPRegs = 8;
3799 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3800 it != ie; ++it) {
3801 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
3802
3803 }
3804}
3805
3806ABIArgInfo
3807AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
3808 bool IsInt, llvm::Type *DirectTy) const {
3809 if (FreeRegs >= RegsNeeded) {
3810 FreeRegs -= RegsNeeded;
3811 return ABIArgInfo::getDirect(DirectTy);
3812 }
3813
3814 llvm::Type *Padding = 0;
3815
3816 // We need padding so that later arguments don't get filled in anyway. That
3817 // wouldn't happen if only ByVal arguments followed in the same category, but
3818 // a large structure will simply seem to be a pointer as far as LLVM is
3819 // concerned.
3820 if (FreeRegs > 0) {
3821 if (IsInt)
3822 Padding = llvm::Type::getInt64Ty(getVMContext());
3823 else
3824 Padding = llvm::Type::getFloatTy(getVMContext());
3825
3826 // Either [N x i64] or [N x float].
3827 Padding = llvm::ArrayType::get(Padding, FreeRegs);
3828 FreeRegs = 0;
3829 }
3830
3831 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
3832 /*IsByVal=*/ true, /*Realign=*/ false,
3833 Padding);
3834}
3835
3836
3837ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
3838 int &FreeIntRegs,
3839 int &FreeVFPRegs) const {
3840 // Can only occurs for return, but harmless otherwise.
3841 if (Ty->isVoidType())
3842 return ABIArgInfo::getIgnore();
3843
3844 // Large vector types should be returned via memory. There's no such concept
3845 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
3846 // classified they'd go into memory (see B.3).
3847 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
3848 if (FreeIntRegs > 0)
3849 --FreeIntRegs;
3850 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3851 }
3852
3853 // All non-aggregate LLVM types have a concrete ABI representation so they can
3854 // be passed directly. After this block we're guaranteed to be in a
3855 // complicated case.
3856 if (!isAggregateTypeForABI(Ty)) {
3857 // Treat an enum type as its underlying type.
3858 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3859 Ty = EnumTy->getDecl()->getIntegerType();
3860
3861 if (Ty->isFloatingType() || Ty->isVectorType())
3862 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
3863
3864 assert(getContext().getTypeSize(Ty) <= 128 &&
3865 "unexpectedly large scalar type");
3866
3867 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3868
3869 // If the type may need padding registers to ensure "alignment", we must be
3870 // careful when this is accounted for. Increasing the effective size covers
3871 // all cases.
3872 if (getContext().getTypeAlign(Ty) == 128)
3873 RegsNeeded += FreeIntRegs % 2 != 0;
3874
3875 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
3876 }
3877
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003878 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT)) {
3879 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northoverc264e162013-01-31 12:13:10 +00003880 --FreeIntRegs;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003881 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northoverc264e162013-01-31 12:13:10 +00003882 }
3883
3884 if (isEmptyRecord(getContext(), Ty, true)) {
3885 if (!getContext().getLangOpts().CPlusPlus) {
3886 // Empty structs outside C++ mode are a GNU extension, so no ABI can
3887 // possibly tell us what to do. It turns out (I believe) that GCC ignores
3888 // the object for parameter-passsing purposes.
3889 return ABIArgInfo::getIgnore();
3890 }
3891
3892 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
3893 // description of va_arg in the PCS require that an empty struct does
3894 // actually occupy space for parameter-passing. I'm hoping for a
3895 // clarification giving an explicit paragraph to point to in future.
3896 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
3897 llvm::Type::getInt8Ty(getVMContext()));
3898 }
3899
3900 // Homogeneous vector aggregates get passed in registers or on the stack.
3901 const Type *Base = 0;
3902 uint64_t NumMembers = 0;
3903 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
3904 assert(Base && "Base class should be set for homogeneous aggregate");
3905 // Homogeneous aggregates are passed and returned directly.
3906 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
3907 /*IsInt=*/ false);
3908 }
3909
3910 uint64_t Size = getContext().getTypeSize(Ty);
3911 if (Size <= 128) {
3912 // Small structs can use the same direct type whether they're in registers
3913 // or on the stack.
3914 llvm::Type *BaseTy;
3915 unsigned NumBases;
3916 int SizeInRegs = (Size + 63) / 64;
3917
3918 if (getContext().getTypeAlign(Ty) == 128) {
3919 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
3920 NumBases = 1;
3921
3922 // If the type may need padding registers to ensure "alignment", we must
3923 // be careful when this is accounted for. Increasing the effective size
3924 // covers all cases.
3925 SizeInRegs += FreeIntRegs % 2 != 0;
3926 } else {
3927 BaseTy = llvm::Type::getInt64Ty(getVMContext());
3928 NumBases = SizeInRegs;
3929 }
3930 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
3931
3932 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
3933 /*IsInt=*/ true, DirectTy);
3934 }
3935
3936 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
3937 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
3938 --FreeIntRegs;
3939 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
3940}
3941
3942llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3943 CodeGenFunction &CGF) const {
3944 // The AArch64 va_list type and handling is specified in the Procedure Call
3945 // Standard, section B.4:
3946 //
3947 // struct {
3948 // void *__stack;
3949 // void *__gr_top;
3950 // void *__vr_top;
3951 // int __gr_offs;
3952 // int __vr_offs;
3953 // };
3954
3955 assert(!CGF.CGM.getDataLayout().isBigEndian()
3956 && "va_arg not implemented for big-endian AArch64");
3957
3958 int FreeIntRegs = 8, FreeVFPRegs = 8;
3959 Ty = CGF.getContext().getCanonicalType(Ty);
3960 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
3961
3962 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3963 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3964 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3965 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3966
3967 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
3968 int reg_top_index;
3969 int RegSize;
3970 if (FreeIntRegs < 8) {
3971 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
3972 // 3 is the field number of __gr_offs
3973 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3974 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3975 reg_top_index = 1; // field number for __gr_top
3976 RegSize = 8 * (8 - FreeIntRegs);
3977 } else {
3978 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
3979 // 4 is the field number of __vr_offs.
3980 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3981 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3982 reg_top_index = 2; // field number for __vr_top
3983 RegSize = 16 * (8 - FreeVFPRegs);
3984 }
3985
3986 //=======================================
3987 // Find out where argument was passed
3988 //=======================================
3989
3990 // If reg_offs >= 0 we're already using the stack for this type of
3991 // argument. We don't want to keep updating reg_offs (in case it overflows,
3992 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3993 // whatever they get).
3994 llvm::Value *UsingStack = 0;
3995 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
3996 llvm::ConstantInt::get(CGF.Int32Ty, 0));
3997
3998 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3999
4000 // Otherwise, at least some kind of argument could go in these registers, the
4001 // quesiton is whether this particular type is too big.
4002 CGF.EmitBlock(MaybeRegBlock);
4003
4004 // Integer arguments may need to correct register alignment (for example a
4005 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4006 // align __gr_offs to calculate the potential address.
4007 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4008 int Align = getContext().getTypeAlign(Ty) / 8;
4009
4010 reg_offs = CGF.Builder.CreateAdd(reg_offs,
4011 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4012 "align_regoffs");
4013 reg_offs = CGF.Builder.CreateAnd(reg_offs,
4014 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4015 "aligned_regoffs");
4016 }
4017
4018 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4019 llvm::Value *NewOffset = 0;
4020 NewOffset = CGF.Builder.CreateAdd(reg_offs,
4021 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4022 "new_reg_offs");
4023 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4024
4025 // Now we're in a position to decide whether this argument really was in
4026 // registers or not.
4027 llvm::Value *InRegs = 0;
4028 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4029 llvm::ConstantInt::get(CGF.Int32Ty, 0),
4030 "inreg");
4031
4032 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4033
4034 //=======================================
4035 // Argument was in registers
4036 //=======================================
4037
4038 // Now we emit the code for if the argument was originally passed in
4039 // registers. First start the appropriate block:
4040 CGF.EmitBlock(InRegBlock);
4041
4042 llvm::Value *reg_top_p = 0, *reg_top = 0;
4043 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4044 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4045 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4046 llvm::Value *RegAddr = 0;
4047 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4048
4049 if (!AI.isDirect()) {
4050 // If it's been passed indirectly (actually a struct), whatever we find from
4051 // stored registers or on the stack will actually be a struct **.
4052 MemTy = llvm::PointerType::getUnqual(MemTy);
4053 }
4054
4055 const Type *Base = 0;
4056 uint64_t NumMembers;
4057 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4058 && NumMembers > 1) {
4059 // Homogeneous aggregates passed in registers will have their elements split
4060 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4061 // qN+1, ...). We reload and store into a temporary local variable
4062 // contiguously.
4063 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4064 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4065 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4066 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4067
4068 for (unsigned i = 0; i < NumMembers; ++i) {
4069 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
4070 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4071 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4072 llvm::PointerType::getUnqual(BaseTy));
4073 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4074
4075 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4076 CGF.Builder.CreateStore(Elem, StoreAddr);
4077 }
4078
4079 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4080 } else {
4081 // Otherwise the object is contiguous in memory
4082 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4083 }
4084
4085 CGF.EmitBranch(ContBlock);
4086
4087 //=======================================
4088 // Argument was on the stack
4089 //=======================================
4090 CGF.EmitBlock(OnStackBlock);
4091
4092 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4093 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4094 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4095
4096 // Again, stack arguments may need realigmnent. In this case both integer and
4097 // floating-point ones might be affected.
4098 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4099 int Align = getContext().getTypeAlign(Ty) / 8;
4100
4101 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4102
4103 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4104 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4105 "align_stack");
4106 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4107 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4108 "align_stack");
4109
4110 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4111 }
4112
4113 uint64_t StackSize;
4114 if (AI.isDirect())
4115 StackSize = getContext().getTypeSize(Ty) / 8;
4116 else
4117 StackSize = 8;
4118
4119 // All stack slots are 8 bytes
4120 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4121
4122 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4123 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4124 "new_stack");
4125
4126 // Write the new value of __stack for the next call to va_arg
4127 CGF.Builder.CreateStore(NewStack, stack_p);
4128
4129 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4130
4131 CGF.EmitBranch(ContBlock);
4132
4133 //=======================================
4134 // Tidy up
4135 //=======================================
4136 CGF.EmitBlock(ContBlock);
4137
4138 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4139 ResAddr->addIncoming(RegAddr, InRegBlock);
4140 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4141
4142 if (AI.isDirect())
4143 return ResAddr;
4144
4145 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4146}
4147
4148//===----------------------------------------------------------------------===//
Justin Holewinski2c585b92012-05-24 17:43:12 +00004149// NVPTX ABI Implementation
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004150//===----------------------------------------------------------------------===//
4151
4152namespace {
4153
Justin Holewinski2c585b92012-05-24 17:43:12 +00004154class NVPTXABIInfo : public ABIInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004155public:
Justin Holewinskidca8f332013-03-30 14:38:24 +00004156 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004157
4158 ABIArgInfo classifyReturnType(QualType RetTy) const;
4159 ABIArgInfo classifyArgumentType(QualType Ty) const;
4160
4161 virtual void computeInfo(CGFunctionInfo &FI) const;
4162 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4163 CodeGenFunction &CFG) const;
4164};
4165
Justin Holewinski2c585b92012-05-24 17:43:12 +00004166class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004167public:
Justin Holewinski2c585b92012-05-24 17:43:12 +00004168 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4169 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Justin Holewinski818eafb2011-10-05 17:58:44 +00004170
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004171 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4172 CodeGen::CodeGenModule &M) const;
Justin Holewinskidca8f332013-03-30 14:38:24 +00004173private:
4174 static void addKernelMetadata(llvm::Function *F);
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004175};
4176
Justin Holewinski2c585b92012-05-24 17:43:12 +00004177ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004178 if (RetTy->isVoidType())
4179 return ABIArgInfo::getIgnore();
4180 if (isAggregateTypeForABI(RetTy))
4181 return ABIArgInfo::getIndirect(0);
4182 return ABIArgInfo::getDirect();
4183}
4184
Justin Holewinski2c585b92012-05-24 17:43:12 +00004185ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004186 if (isAggregateTypeForABI(Ty))
4187 return ABIArgInfo::getIndirect(0);
4188
4189 return ABIArgInfo::getDirect();
4190}
4191
Justin Holewinski2c585b92012-05-24 17:43:12 +00004192void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004193 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4194 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4195 it != ie; ++it)
4196 it->info = classifyArgumentType(it->type);
4197
4198 // Always honor user-specified calling convention.
4199 if (FI.getCallingConvention() != llvm::CallingConv::C)
4200 return;
4201
John McCallbd7370a2013-02-28 19:01:20 +00004202 FI.setEffectiveCallingConvention(getRuntimeCC());
4203}
4204
Justin Holewinski2c585b92012-05-24 17:43:12 +00004205llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4206 CodeGenFunction &CFG) const {
4207 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004208}
4209
Justin Holewinski2c585b92012-05-24 17:43:12 +00004210void NVPTXTargetCodeGenInfo::
4211SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4212 CodeGen::CodeGenModule &M) const{
Justin Holewinski818eafb2011-10-05 17:58:44 +00004213 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4214 if (!FD) return;
4215
4216 llvm::Function *F = cast<llvm::Function>(GV);
4217
4218 // Perform special handling in OpenCL mode
David Blaikie4e4d0842012-03-11 07:00:24 +00004219 if (M.getLangOpts().OpenCL) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004220 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00004221 // By default, all functions are device functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00004222 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004223 // OpenCL __kernel functions get kernel metadata
4224 addKernelMetadata(F);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004225 // And kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00004226 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004227 }
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004228 }
Justin Holewinski818eafb2011-10-05 17:58:44 +00004229
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004230 // Perform special handling in CUDA mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00004231 if (M.getLangOpts().CUDA) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004232 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004233 // __global__ functions cannot be called from the device, we do not
4234 // need to set the noinline attribute.
4235 if (FD->getAttr<CUDAGlobalAttr>())
Justin Holewinskidca8f332013-03-30 14:38:24 +00004236 addKernelMetadata(F);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004237 }
4238}
4239
Justin Holewinskidca8f332013-03-30 14:38:24 +00004240void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4241 llvm::Module *M = F->getParent();
4242 llvm::LLVMContext &Ctx = M->getContext();
4243
4244 // Get "nvvm.annotations" metadata node
4245 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4246
4247 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4248 llvm::SmallVector<llvm::Value *, 3> MDVals;
4249 MDVals.push_back(F);
4250 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4251 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4252
4253 // Append metadata to nvvm.annotations
4254 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4255}
4256
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004257}
4258
4259//===----------------------------------------------------------------------===//
Ulrich Weigandb8409212013-05-06 16:26:41 +00004260// SystemZ ABI Implementation
4261//===----------------------------------------------------------------------===//
4262
4263namespace {
4264
4265class SystemZABIInfo : public ABIInfo {
4266public:
4267 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4268
4269 bool isPromotableIntegerType(QualType Ty) const;
4270 bool isCompoundType(QualType Ty) const;
4271 bool isFPArgumentType(QualType Ty) const;
4272
4273 ABIArgInfo classifyReturnType(QualType RetTy) const;
4274 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4275
4276 virtual void computeInfo(CGFunctionInfo &FI) const {
4277 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4278 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4279 it != ie; ++it)
4280 it->info = classifyArgumentType(it->type);
4281 }
4282
4283 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4284 CodeGenFunction &CGF) const;
4285};
4286
4287class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4288public:
4289 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4290 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4291};
4292
4293}
4294
4295bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4296 // Treat an enum type as its underlying type.
4297 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4298 Ty = EnumTy->getDecl()->getIntegerType();
4299
4300 // Promotable integer types are required to be promoted by the ABI.
4301 if (Ty->isPromotableIntegerType())
4302 return true;
4303
4304 // 32-bit values must also be promoted.
4305 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4306 switch (BT->getKind()) {
4307 case BuiltinType::Int:
4308 case BuiltinType::UInt:
4309 return true;
4310 default:
4311 return false;
4312 }
4313 return false;
4314}
4315
4316bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4317 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4318}
4319
4320bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4321 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4322 switch (BT->getKind()) {
4323 case BuiltinType::Float:
4324 case BuiltinType::Double:
4325 return true;
4326 default:
4327 return false;
4328 }
4329
4330 if (const RecordType *RT = Ty->getAsStructureType()) {
4331 const RecordDecl *RD = RT->getDecl();
4332 bool Found = false;
4333
4334 // If this is a C++ record, check the bases first.
4335 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4336 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4337 E = CXXRD->bases_end(); I != E; ++I) {
4338 QualType Base = I->getType();
4339
4340 // Empty bases don't affect things either way.
4341 if (isEmptyRecord(getContext(), Base, true))
4342 continue;
4343
4344 if (Found)
4345 return false;
4346 Found = isFPArgumentType(Base);
4347 if (!Found)
4348 return false;
4349 }
4350
4351 // Check the fields.
4352 for (RecordDecl::field_iterator I = RD->field_begin(),
4353 E = RD->field_end(); I != E; ++I) {
4354 const FieldDecl *FD = *I;
4355
4356 // Empty bitfields don't affect things either way.
4357 // Unlike isSingleElementStruct(), empty structure and array fields
4358 // do count. So do anonymous bitfields that aren't zero-sized.
4359 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4360 return true;
4361
4362 // Unlike isSingleElementStruct(), arrays do not count.
4363 // Nested isFPArgumentType structures still do though.
4364 if (Found)
4365 return false;
4366 Found = isFPArgumentType(FD->getType());
4367 if (!Found)
4368 return false;
4369 }
4370
4371 // Unlike isSingleElementStruct(), trailing padding is allowed.
4372 // An 8-byte aligned struct s { float f; } is passed as a double.
4373 return Found;
4374 }
4375
4376 return false;
4377}
4378
4379llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4380 CodeGenFunction &CGF) const {
4381 // Assume that va_list type is correct; should be pointer to LLVM type:
4382 // struct {
4383 // i64 __gpr;
4384 // i64 __fpr;
4385 // i8 *__overflow_arg_area;
4386 // i8 *__reg_save_area;
4387 // };
4388
4389 // Every argument occupies 8 bytes and is passed by preference in either
4390 // GPRs or FPRs.
4391 Ty = CGF.getContext().getCanonicalType(Ty);
4392 ABIArgInfo AI = classifyArgumentType(Ty);
4393 bool InFPRs = isFPArgumentType(Ty);
4394
4395 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4396 bool IsIndirect = AI.isIndirect();
4397 unsigned UnpaddedBitSize;
4398 if (IsIndirect) {
4399 APTy = llvm::PointerType::getUnqual(APTy);
4400 UnpaddedBitSize = 64;
4401 } else
4402 UnpaddedBitSize = getContext().getTypeSize(Ty);
4403 unsigned PaddedBitSize = 64;
4404 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4405
4406 unsigned PaddedSize = PaddedBitSize / 8;
4407 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4408
4409 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4410 if (InFPRs) {
4411 MaxRegs = 4; // Maximum of 4 FPR arguments
4412 RegCountField = 1; // __fpr
4413 RegSaveIndex = 16; // save offset for f0
4414 RegPadding = 0; // floats are passed in the high bits of an FPR
4415 } else {
4416 MaxRegs = 5; // Maximum of 5 GPR arguments
4417 RegCountField = 0; // __gpr
4418 RegSaveIndex = 2; // save offset for r2
4419 RegPadding = Padding; // values are passed in the low bits of a GPR
4420 }
4421
4422 llvm::Value *RegCountPtr =
4423 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4424 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4425 llvm::Type *IndexTy = RegCount->getType();
4426 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4427 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
4428 "fits_in_regs");
4429
4430 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4431 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4432 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4433 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4434
4435 // Emit code to load the value if it was passed in registers.
4436 CGF.EmitBlock(InRegBlock);
4437
4438 // Work out the address of an argument register.
4439 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4440 llvm::Value *ScaledRegCount =
4441 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4442 llvm::Value *RegBase =
4443 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4444 llvm::Value *RegOffset =
4445 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4446 llvm::Value *RegSaveAreaPtr =
4447 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4448 llvm::Value *RegSaveArea =
4449 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4450 llvm::Value *RawRegAddr =
4451 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4452 llvm::Value *RegAddr =
4453 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4454
4455 // Update the register count
4456 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4457 llvm::Value *NewRegCount =
4458 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4459 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4460 CGF.EmitBranch(ContBlock);
4461
4462 // Emit code to load the value if it was passed in memory.
4463 CGF.EmitBlock(InMemBlock);
4464
4465 // Work out the address of a stack argument.
4466 llvm::Value *OverflowArgAreaPtr =
4467 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4468 llvm::Value *OverflowArgArea =
4469 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4470 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4471 llvm::Value *RawMemAddr =
4472 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4473 llvm::Value *MemAddr =
4474 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4475
4476 // Update overflow_arg_area_ptr pointer
4477 llvm::Value *NewOverflowArgArea =
4478 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4479 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4480 CGF.EmitBranch(ContBlock);
4481
4482 // Return the appropriate result.
4483 CGF.EmitBlock(ContBlock);
4484 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4485 ResAddr->addIncoming(RegAddr, InRegBlock);
4486 ResAddr->addIncoming(MemAddr, InMemBlock);
4487
4488 if (IsIndirect)
4489 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4490
4491 return ResAddr;
4492}
4493
John McCallb8b52972013-06-18 02:46:29 +00004494bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4495 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4496 assert(Triple.getArch() == llvm::Triple::x86);
4497
4498 switch (Opts.getStructReturnConvention()) {
4499 case CodeGenOptions::SRCK_Default:
4500 break;
4501 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4502 return false;
4503 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4504 return true;
4505 }
4506
4507 if (Triple.isOSDarwin())
4508 return true;
4509
4510 switch (Triple.getOS()) {
4511 case llvm::Triple::Cygwin:
4512 case llvm::Triple::MinGW32:
4513 case llvm::Triple::AuroraUX:
4514 case llvm::Triple::DragonFly:
4515 case llvm::Triple::FreeBSD:
4516 case llvm::Triple::OpenBSD:
4517 case llvm::Triple::Bitrig:
4518 case llvm::Triple::Win32:
4519 return true;
4520 default:
4521 return false;
4522 }
4523}
Ulrich Weigandb8409212013-05-06 16:26:41 +00004524
4525ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4526 if (RetTy->isVoidType())
4527 return ABIArgInfo::getIgnore();
4528 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4529 return ABIArgInfo::getIndirect(0);
4530 return (isPromotableIntegerType(RetTy) ?
4531 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4532}
4533
4534ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4535 // Handle the generic C++ ABI.
4536 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
4537 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4538
4539 // Integers and enums are extended to full register width.
4540 if (isPromotableIntegerType(Ty))
4541 return ABIArgInfo::getExtend();
4542
4543 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4544 uint64_t Size = getContext().getTypeSize(Ty);
4545 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
4546 return ABIArgInfo::getIndirect(0);
4547
4548 // Handle small structures.
4549 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4550 // Structures with flexible arrays have variable length, so really
4551 // fail the size test above.
4552 const RecordDecl *RD = RT->getDecl();
4553 if (RD->hasFlexibleArrayMember())
4554 return ABIArgInfo::getIndirect(0);
4555
4556 // The structure is passed as an unextended integer, a float, or a double.
4557 llvm::Type *PassTy;
4558 if (isFPArgumentType(Ty)) {
4559 assert(Size == 32 || Size == 64);
4560 if (Size == 32)
4561 PassTy = llvm::Type::getFloatTy(getVMContext());
4562 else
4563 PassTy = llvm::Type::getDoubleTy(getVMContext());
4564 } else
4565 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4566 return ABIArgInfo::getDirect(PassTy);
4567 }
4568
4569 // Non-structure compounds are passed indirectly.
4570 if (isCompoundType(Ty))
4571 return ABIArgInfo::getIndirect(0);
4572
4573 return ABIArgInfo::getDirect(0);
4574}
4575
4576//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004577// MSP430 ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004578//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004579
4580namespace {
4581
4582class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4583public:
Chris Lattnerea044322010-07-29 02:01:43 +00004584 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4585 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004586 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4587 CodeGen::CodeGenModule &M) const;
4588};
4589
4590}
4591
4592void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4593 llvm::GlobalValue *GV,
4594 CodeGen::CodeGenModule &M) const {
4595 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4596 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4597 // Handle 'interrupt' attribute:
4598 llvm::Function *F = cast<llvm::Function>(GV);
4599
4600 // Step 1: Set ISR calling convention.
4601 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4602
4603 // Step 2: Add attributes goodness.
Bill Wendling72390b32012-12-20 19:27:06 +00004604 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004605
4606 // Step 3: Emit ISR vector alias.
Anton Korobeynikovf419a852012-11-26 18:59:10 +00004607 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004608 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovf419a852012-11-26 18:59:10 +00004609 "__isr_" + Twine(Num),
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004610 GV, &M.getModule());
4611 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004612 }
4613}
4614
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004615//===----------------------------------------------------------------------===//
John McCallaeeb7012010-05-27 06:19:26 +00004616// MIPS ABI Implementation. This works for both little-endian and
4617// big-endian variants.
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004618//===----------------------------------------------------------------------===//
4619
John McCallaeeb7012010-05-27 06:19:26 +00004620namespace {
Akira Hatanaka619e8872011-06-02 00:09:17 +00004621class MipsABIInfo : public ABIInfo {
Akira Hatanakac0e3b662011-11-02 23:14:57 +00004622 bool IsO32;
Akira Hatanakac359f202012-07-03 19:24:06 +00004623 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4624 void CoerceToIntArgs(uint64_t TySize,
Craig Topper6b9240e2013-07-05 19:34:19 +00004625 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004626 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004627 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004628 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004629public:
Akira Hatanakab551dd32011-11-03 00:05:50 +00004630 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakac359f202012-07-03 19:24:06 +00004631 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
4632 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanaka619e8872011-06-02 00:09:17 +00004633
4634 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004635 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004636 virtual void computeInfo(CGFunctionInfo &FI) const;
4637 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4638 CodeGenFunction &CGF) const;
4639};
4640
John McCallaeeb7012010-05-27 06:19:26 +00004641class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanakae624fa02011-09-20 18:23:28 +00004642 unsigned SizeOfUnwindException;
John McCallaeeb7012010-05-27 06:19:26 +00004643public:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00004644 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
4645 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
4646 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCallaeeb7012010-05-27 06:19:26 +00004647
4648 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4649 return 29;
4650 }
4651
Reed Kotler7dfd1822013-01-16 17:10:28 +00004652 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4653 CodeGen::CodeGenModule &CGM) const {
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004654 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4655 if (!FD) return;
Rafael Espindolad8e6d6d2013-03-19 14:32:23 +00004656 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004657 if (FD->hasAttr<Mips16Attr>()) {
4658 Fn->addFnAttr("mips16");
4659 }
4660 else if (FD->hasAttr<NoMips16Attr>()) {
4661 Fn->addFnAttr("nomips16");
4662 }
Reed Kotler7dfd1822013-01-16 17:10:28 +00004663 }
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004664
John McCallaeeb7012010-05-27 06:19:26 +00004665 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00004666 llvm::Value *Address) const;
John McCall49e34be2011-08-30 01:42:09 +00004667
4668 unsigned getSizeOfUnwindException() const {
Akira Hatanakae624fa02011-09-20 18:23:28 +00004669 return SizeOfUnwindException;
John McCall49e34be2011-08-30 01:42:09 +00004670 }
John McCallaeeb7012010-05-27 06:19:26 +00004671};
4672}
4673
Akira Hatanakac359f202012-07-03 19:24:06 +00004674void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper6b9240e2013-07-05 19:34:19 +00004675 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00004676 llvm::IntegerType *IntTy =
4677 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004678
4679 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4680 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4681 ArgList.push_back(IntTy);
4682
4683 // If necessary, add one more integer type to ArgList.
4684 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4685
4686 if (R)
4687 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004688}
4689
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004690// In N32/64, an aligned double precision floating point field is passed in
4691// a register.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004692llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00004693 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4694
4695 if (IsO32) {
4696 CoerceToIntArgs(TySize, ArgList);
4697 return llvm::StructType::get(getVMContext(), ArgList);
4698 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004699
Akira Hatanaka2afd23d2012-01-12 00:52:17 +00004700 if (Ty->isComplexType())
4701 return CGT.ConvertType(Ty);
Akira Hatanaka6d1080f2012-01-10 23:12:19 +00004702
Akira Hatanakaa34e9212012-02-09 19:54:16 +00004703 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004704
Akira Hatanakac359f202012-07-03 19:24:06 +00004705 // Unions/vectors are passed in integer registers.
4706 if (!RT || !RT->isStructureOrClassType()) {
4707 CoerceToIntArgs(TySize, ArgList);
4708 return llvm::StructType::get(getVMContext(), ArgList);
4709 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004710
4711 const RecordDecl *RD = RT->getDecl();
4712 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004713 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004714
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004715 uint64_t LastOffset = 0;
4716 unsigned idx = 0;
4717 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4718
Akira Hatanakaa34e9212012-02-09 19:54:16 +00004719 // Iterate over fields in the struct/class and check if there are any aligned
4720 // double fields.
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004721 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4722 i != e; ++i, ++idx) {
David Blaikie262bc182012-04-30 02:36:29 +00004723 const QualType Ty = i->getType();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004724 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4725
4726 if (!BT || BT->getKind() != BuiltinType::Double)
4727 continue;
4728
4729 uint64_t Offset = Layout.getFieldOffset(idx);
4730 if (Offset % 64) // Ignore doubles that are not aligned.
4731 continue;
4732
4733 // Add ((Offset - LastOffset) / 64) args of type i64.
4734 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4735 ArgList.push_back(I64);
4736
4737 // Add double type.
4738 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4739 LastOffset = Offset + 64;
4740 }
4741
Akira Hatanakac359f202012-07-03 19:24:06 +00004742 CoerceToIntArgs(TySize - LastOffset, IntArgList);
4743 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004744
4745 return llvm::StructType::get(getVMContext(), ArgList);
4746}
4747
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004748llvm::Type *MipsABIInfo::getPaddingType(uint64_t Align, uint64_t Offset) const {
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004749 assert((Offset % MinABIStackAlignInBytes) == 0);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004750
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004751 if ((Align - 1) & Offset)
4752 return llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
4753
4754 return 0;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004755}
Akira Hatanaka9659d592012-01-10 22:44:52 +00004756
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004757ABIArgInfo
4758MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004759 uint64_t OrigOffset = Offset;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004760 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004761 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004762
Akira Hatanakac359f202012-07-03 19:24:06 +00004763 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
4764 (uint64_t)StackAlignInBytes);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004765 Offset = llvm::RoundUpToAlignment(Offset, Align);
4766 Offset += llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004767
Akira Hatanakac359f202012-07-03 19:24:06 +00004768 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanaka619e8872011-06-02 00:09:17 +00004769 // Ignore empty aggregates.
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004770 if (TySize == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00004771 return ABIArgInfo::getIgnore();
4772
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004773 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT)) {
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004774 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004775 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004776 }
Akira Hatanaka511949b2011-08-01 18:09:58 +00004777
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004778 // If we have reached here, aggregates are passed directly by coercing to
4779 // another structure type. Padding is inserted if the offset of the
4780 // aggregate is unaligned.
4781 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
4782 getPaddingType(Align, OrigOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00004783 }
4784
4785 // Treat an enum type as its underlying type.
4786 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4787 Ty = EnumTy->getDecl()->getIntegerType();
4788
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004789 if (Ty->isPromotableIntegerType())
4790 return ABIArgInfo::getExtend();
4791
Akira Hatanaka4055cfc2013-01-24 21:47:33 +00004792 return ABIArgInfo::getDirect(0, 0,
4793 IsO32 ? 0 : getPaddingType(Align, OrigOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00004794}
4795
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004796llvm::Type*
4797MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakada54ff32012-02-09 18:49:26 +00004798 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakac359f202012-07-03 19:24:06 +00004799 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004800
Akira Hatanakada54ff32012-02-09 18:49:26 +00004801 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004802 const RecordDecl *RD = RT->getDecl();
Akira Hatanakada54ff32012-02-09 18:49:26 +00004803 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4804 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004805
Akira Hatanakada54ff32012-02-09 18:49:26 +00004806 // N32/64 returns struct/classes in floating point registers if the
4807 // following conditions are met:
4808 // 1. The size of the struct/class is no larger than 128-bit.
4809 // 2. The struct/class has one or two fields all of which are floating
4810 // point types.
4811 // 3. The offset of the first field is zero (this follows what gcc does).
4812 //
4813 // Any other composite results are returned in integer registers.
4814 //
4815 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
4816 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
4817 for (; b != e; ++b) {
David Blaikie262bc182012-04-30 02:36:29 +00004818 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004819
Akira Hatanakada54ff32012-02-09 18:49:26 +00004820 if (!BT || !BT->isFloatingPoint())
4821 break;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004822
David Blaikie262bc182012-04-30 02:36:29 +00004823 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakada54ff32012-02-09 18:49:26 +00004824 }
4825
4826 if (b == e)
4827 return llvm::StructType::get(getVMContext(), RTList,
4828 RD->hasAttr<PackedAttr>());
4829
4830 RTList.clear();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004831 }
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004832 }
4833
Akira Hatanakac359f202012-07-03 19:24:06 +00004834 CoerceToIntArgs(Size, RTList);
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004835 return llvm::StructType::get(getVMContext(), RTList);
4836}
4837
Akira Hatanaka619e8872011-06-02 00:09:17 +00004838ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanakaa8536c02012-01-23 23:18:57 +00004839 uint64_t Size = getContext().getTypeSize(RetTy);
4840
4841 if (RetTy->isVoidType() || Size == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00004842 return ABIArgInfo::getIgnore();
4843
Akira Hatanaka8aeb1472012-05-11 21:01:17 +00004844 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004845 if (isRecordReturnIndirect(RetTy, CGT))
4846 return ABIArgInfo::getIndirect(0);
4847
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004848 if (Size <= 128) {
4849 if (RetTy->isAnyComplexType())
4850 return ABIArgInfo::getDirect();
4851
Akira Hatanakac359f202012-07-03 19:24:06 +00004852 // O32 returns integer vectors in registers.
4853 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
4854 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4855
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004856 if (!IsO32)
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004857 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4858 }
Akira Hatanaka619e8872011-06-02 00:09:17 +00004859
4860 return ABIArgInfo::getIndirect(0);
4861 }
4862
4863 // Treat an enum type as its underlying type.
4864 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4865 RetTy = EnumTy->getDecl()->getIntegerType();
4866
4867 return (RetTy->isPromotableIntegerType() ?
4868 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4869}
4870
4871void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakacc662542012-01-12 01:10:09 +00004872 ABIArgInfo &RetInfo = FI.getReturnInfo();
4873 RetInfo = classifyReturnType(FI.getReturnType());
4874
4875 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004876 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanakacc662542012-01-12 01:10:09 +00004877
Akira Hatanaka619e8872011-06-02 00:09:17 +00004878 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4879 it != ie; ++it)
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004880 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanaka619e8872011-06-02 00:09:17 +00004881}
4882
4883llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4884 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00004885 llvm::Type *BP = CGF.Int8PtrTy;
4886 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004887
4888 CGBuilderTy &Builder = CGF.Builder;
4889 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4890 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004891 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004892 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4893 llvm::Value *AddrTyped;
John McCall64aa4b32013-04-16 22:48:15 +00004894 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004895 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004896
4897 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004898 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
4899 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
4900 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
4901 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004902 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
4903 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
4904 }
4905 else
4906 AddrTyped = Builder.CreateBitCast(Addr, PTy);
4907
4908 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004909 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004910 uint64_t Offset =
4911 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
4912 llvm::Value *NextAddr =
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004913 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004914 "ap.next");
4915 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4916
4917 return AddrTyped;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004918}
4919
John McCallaeeb7012010-05-27 06:19:26 +00004920bool
4921MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4922 llvm::Value *Address) const {
4923 // This information comes from gcc's implementation, which seems to
4924 // as canonical as it gets.
4925
John McCallaeeb7012010-05-27 06:19:26 +00004926 // Everything on MIPS is 4 bytes. Double-precision FP registers
4927 // are aliased to pairs of single-precision FP registers.
Chris Lattner8b418682012-02-07 00:39:47 +00004928 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCallaeeb7012010-05-27 06:19:26 +00004929
4930 // 0-31 are the general purpose registers, $0 - $31.
4931 // 32-63 are the floating-point registers, $f0 - $f31.
4932 // 64 and 65 are the multiply/divide registers, $hi and $lo.
4933 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattner8b418682012-02-07 00:39:47 +00004934 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCallaeeb7012010-05-27 06:19:26 +00004935
4936 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
4937 // They are one bit wide and ignored here.
4938
4939 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
4940 // (coprocessor 1 is the FP unit)
4941 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
4942 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
4943 // 176-181 are the DSP accumulator registers.
Chris Lattner8b418682012-02-07 00:39:47 +00004944 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCallaeeb7012010-05-27 06:19:26 +00004945 return false;
4946}
4947
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004948//===----------------------------------------------------------------------===//
4949// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
4950// Currently subclassed only to implement custom OpenCL C function attribute
4951// handling.
4952//===----------------------------------------------------------------------===//
4953
4954namespace {
4955
4956class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4957public:
4958 TCETargetCodeGenInfo(CodeGenTypes &CGT)
4959 : DefaultTargetCodeGenInfo(CGT) {}
4960
4961 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4962 CodeGen::CodeGenModule &M) const;
4963};
4964
4965void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4966 llvm::GlobalValue *GV,
4967 CodeGen::CodeGenModule &M) const {
4968 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4969 if (!FD) return;
4970
4971 llvm::Function *F = cast<llvm::Function>(GV);
4972
David Blaikie4e4d0842012-03-11 07:00:24 +00004973 if (M.getLangOpts().OpenCL) {
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004974 if (FD->hasAttr<OpenCLKernelAttr>()) {
4975 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00004976 F->addFnAttr(llvm::Attribute::NoInline);
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004977
4978 if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
4979
4980 // Convert the reqd_work_group_size() attributes to metadata.
4981 llvm::LLVMContext &Context = F->getContext();
4982 llvm::NamedMDNode *OpenCLMetadata =
4983 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
4984
4985 SmallVector<llvm::Value*, 5> Operands;
4986 Operands.push_back(F);
4987
Chris Lattner8b418682012-02-07 00:39:47 +00004988 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
4989 llvm::APInt(32,
4990 FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim())));
4991 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
4992 llvm::APInt(32,
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004993 FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim())));
Chris Lattner8b418682012-02-07 00:39:47 +00004994 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
4995 llvm::APInt(32,
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004996 FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim())));
4997
4998 // Add a boolean constant operand for "required" (true) or "hint" (false)
4999 // for implementing the work_group_size_hint attr later. Currently
5000 // always true as the hint is not yet implemented.
Chris Lattner8b418682012-02-07 00:39:47 +00005001 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005002 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5003 }
5004 }
5005 }
5006}
5007
5008}
John McCallaeeb7012010-05-27 06:19:26 +00005009
Tony Linthicum96319392011-12-12 21:14:55 +00005010//===----------------------------------------------------------------------===//
5011// Hexagon ABI Implementation
5012//===----------------------------------------------------------------------===//
5013
5014namespace {
5015
5016class HexagonABIInfo : public ABIInfo {
5017
5018
5019public:
5020 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5021
5022private:
5023
5024 ABIArgInfo classifyReturnType(QualType RetTy) const;
5025 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5026
5027 virtual void computeInfo(CGFunctionInfo &FI) const;
5028
5029 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5030 CodeGenFunction &CGF) const;
5031};
5032
5033class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5034public:
5035 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5036 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5037
5038 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5039 return 29;
5040 }
5041};
5042
5043}
5044
5045void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5046 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5047 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5048 it != ie; ++it)
5049 it->info = classifyArgumentType(it->type);
5050}
5051
5052ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5053 if (!isAggregateTypeForABI(Ty)) {
5054 // Treat an enum type as its underlying type.
5055 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5056 Ty = EnumTy->getDecl()->getIntegerType();
5057
5058 return (Ty->isPromotableIntegerType() ?
5059 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5060 }
5061
5062 // Ignore empty records.
5063 if (isEmptyRecord(getContext(), Ty, true))
5064 return ABIArgInfo::getIgnore();
5065
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005066 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
5067 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum96319392011-12-12 21:14:55 +00005068
5069 uint64_t Size = getContext().getTypeSize(Ty);
5070 if (Size > 64)
5071 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5072 // Pass in the smallest viable integer type.
5073 else if (Size > 32)
5074 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5075 else if (Size > 16)
5076 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5077 else if (Size > 8)
5078 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5079 else
5080 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5081}
5082
5083ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5084 if (RetTy->isVoidType())
5085 return ABIArgInfo::getIgnore();
5086
5087 // Large vector types should be returned via memory.
5088 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5089 return ABIArgInfo::getIndirect(0);
5090
5091 if (!isAggregateTypeForABI(RetTy)) {
5092 // Treat an enum type as its underlying type.
5093 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5094 RetTy = EnumTy->getDecl()->getIntegerType();
5095
5096 return (RetTy->isPromotableIntegerType() ?
5097 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5098 }
5099
5100 // Structures with either a non-trivial destructor or a non-trivial
5101 // copy constructor are always indirect.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005102 if (isRecordReturnIndirect(RetTy, CGT))
Tony Linthicum96319392011-12-12 21:14:55 +00005103 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5104
5105 if (isEmptyRecord(getContext(), RetTy, true))
5106 return ABIArgInfo::getIgnore();
5107
5108 // Aggregates <= 8 bytes are returned in r0; other aggregates
5109 // are returned indirectly.
5110 uint64_t Size = getContext().getTypeSize(RetTy);
5111 if (Size <= 64) {
5112 // Return in the smallest viable integer type.
5113 if (Size <= 8)
5114 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5115 if (Size <= 16)
5116 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5117 if (Size <= 32)
5118 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5119 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5120 }
5121
5122 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5123}
5124
5125llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner8b418682012-02-07 00:39:47 +00005126 CodeGenFunction &CGF) const {
Tony Linthicum96319392011-12-12 21:14:55 +00005127 // FIXME: Need to handle alignment
Chris Lattner8b418682012-02-07 00:39:47 +00005128 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum96319392011-12-12 21:14:55 +00005129
5130 CGBuilderTy &Builder = CGF.Builder;
5131 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5132 "ap");
5133 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5134 llvm::Type *PTy =
5135 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5136 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5137
5138 uint64_t Offset =
5139 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5140 llvm::Value *NextAddr =
5141 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5142 "ap.next");
5143 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5144
5145 return AddrTyped;
5146}
5147
5148
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005149//===----------------------------------------------------------------------===//
5150// SPARC v9 ABI Implementation.
5151// Based on the SPARC Compliance Definition version 2.4.1.
5152//
5153// Function arguments a mapped to a nominal "parameter array" and promoted to
5154// registers depending on their type. Each argument occupies 8 or 16 bytes in
5155// the array, structs larger than 16 bytes are passed indirectly.
5156//
5157// One case requires special care:
5158//
5159// struct mixed {
5160// int i;
5161// float f;
5162// };
5163//
5164// When a struct mixed is passed by value, it only occupies 8 bytes in the
5165// parameter array, but the int is passed in an integer register, and the float
5166// is passed in a floating point register. This is represented as two arguments
5167// with the LLVM IR inreg attribute:
5168//
5169// declare void f(i32 inreg %i, float inreg %f)
5170//
5171// The code generator will only allocate 4 bytes from the parameter array for
5172// the inreg arguments. All other arguments are allocated a multiple of 8
5173// bytes.
5174//
5175namespace {
5176class SparcV9ABIInfo : public ABIInfo {
5177public:
5178 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5179
5180private:
5181 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5182 virtual void computeInfo(CGFunctionInfo &FI) const;
5183 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5184 CodeGenFunction &CGF) const;
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00005185
5186 // Coercion type builder for structs passed in registers. The coercion type
5187 // serves two purposes:
5188 //
5189 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5190 // in registers.
5191 // 2. Expose aligned floating point elements as first-level elements, so the
5192 // code generator knows to pass them in floating point registers.
5193 //
5194 // We also compute the InReg flag which indicates that the struct contains
5195 // aligned 32-bit floats.
5196 //
5197 struct CoerceBuilder {
5198 llvm::LLVMContext &Context;
5199 const llvm::DataLayout &DL;
5200 SmallVector<llvm::Type*, 8> Elems;
5201 uint64_t Size;
5202 bool InReg;
5203
5204 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5205 : Context(c), DL(dl), Size(0), InReg(false) {}
5206
5207 // Pad Elems with integers until Size is ToSize.
5208 void pad(uint64_t ToSize) {
5209 assert(ToSize >= Size && "Cannot remove elements");
5210 if (ToSize == Size)
5211 return;
5212
5213 // Finish the current 64-bit word.
5214 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5215 if (Aligned > Size && Aligned <= ToSize) {
5216 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5217 Size = Aligned;
5218 }
5219
5220 // Add whole 64-bit words.
5221 while (Size + 64 <= ToSize) {
5222 Elems.push_back(llvm::Type::getInt64Ty(Context));
5223 Size += 64;
5224 }
5225
5226 // Final in-word padding.
5227 if (Size < ToSize) {
5228 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5229 Size = ToSize;
5230 }
5231 }
5232
5233 // Add a floating point element at Offset.
5234 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5235 // Unaligned floats are treated as integers.
5236 if (Offset % Bits)
5237 return;
5238 // The InReg flag is only required if there are any floats < 64 bits.
5239 if (Bits < 64)
5240 InReg = true;
5241 pad(Offset);
5242 Elems.push_back(Ty);
5243 Size = Offset + Bits;
5244 }
5245
5246 // Add a struct type to the coercion type, starting at Offset (in bits).
5247 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5248 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5249 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5250 llvm::Type *ElemTy = StrTy->getElementType(i);
5251 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5252 switch (ElemTy->getTypeID()) {
5253 case llvm::Type::StructTyID:
5254 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5255 break;
5256 case llvm::Type::FloatTyID:
5257 addFloat(ElemOffset, ElemTy, 32);
5258 break;
5259 case llvm::Type::DoubleTyID:
5260 addFloat(ElemOffset, ElemTy, 64);
5261 break;
5262 case llvm::Type::FP128TyID:
5263 addFloat(ElemOffset, ElemTy, 128);
5264 break;
5265 case llvm::Type::PointerTyID:
5266 if (ElemOffset % 64 == 0) {
5267 pad(ElemOffset);
5268 Elems.push_back(ElemTy);
5269 Size += 64;
5270 }
5271 break;
5272 default:
5273 break;
5274 }
5275 }
5276 }
5277
5278 // Check if Ty is a usable substitute for the coercion type.
5279 bool isUsableType(llvm::StructType *Ty) const {
5280 if (Ty->getNumElements() != Elems.size())
5281 return false;
5282 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5283 if (Elems[i] != Ty->getElementType(i))
5284 return false;
5285 return true;
5286 }
5287
5288 // Get the coercion type as a literal struct type.
5289 llvm::Type *getType() const {
5290 if (Elems.size() == 1)
5291 return Elems.front();
5292 else
5293 return llvm::StructType::get(Context, Elems);
5294 }
5295 };
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005296};
5297} // end anonymous namespace
5298
5299ABIArgInfo
5300SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5301 if (Ty->isVoidType())
5302 return ABIArgInfo::getIgnore();
5303
5304 uint64_t Size = getContext().getTypeSize(Ty);
5305
5306 // Anything too big to fit in registers is passed with an explicit indirect
5307 // pointer / sret pointer.
5308 if (Size > SizeLimit)
5309 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5310
5311 // Treat an enum type as its underlying type.
5312 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5313 Ty = EnumTy->getDecl()->getIntegerType();
5314
5315 // Integer types smaller than a register are extended.
5316 if (Size < 64 && Ty->isIntegerType())
5317 return ABIArgInfo::getExtend();
5318
5319 // Other non-aggregates go in registers.
5320 if (!isAggregateTypeForABI(Ty))
5321 return ABIArgInfo::getDirect();
5322
5323 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00005324 // Build a coercion type from the LLVM struct type.
5325 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5326 if (!StrTy)
5327 return ABIArgInfo::getDirect();
5328
5329 CoerceBuilder CB(getVMContext(), getDataLayout());
5330 CB.addStruct(0, StrTy);
5331 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5332
5333 // Try to use the original type for coercion.
5334 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5335
5336 if (CB.InReg)
5337 return ABIArgInfo::getDirectInReg(CoerceTy);
5338 else
5339 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005340}
5341
5342llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5343 CodeGenFunction &CGF) const {
Jakob Stoklund Olesena4b56d32013-06-05 03:00:18 +00005344 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5345 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5346 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5347 AI.setCoerceToType(ArgTy);
5348
5349 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5350 CGBuilderTy &Builder = CGF.Builder;
5351 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5352 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5353 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5354 llvm::Value *ArgAddr;
5355 unsigned Stride;
5356
5357 switch (AI.getKind()) {
5358 case ABIArgInfo::Expand:
5359 llvm_unreachable("Unsupported ABI kind for va_arg");
5360
5361 case ABIArgInfo::Extend:
5362 Stride = 8;
5363 ArgAddr = Builder
5364 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5365 "extend");
5366 break;
5367
5368 case ABIArgInfo::Direct:
5369 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5370 ArgAddr = Addr;
5371 break;
5372
5373 case ABIArgInfo::Indirect:
5374 Stride = 8;
5375 ArgAddr = Builder.CreateBitCast(Addr,
5376 llvm::PointerType::getUnqual(ArgPtrTy),
5377 "indirect");
5378 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5379 break;
5380
5381 case ABIArgInfo::Ignore:
5382 return llvm::UndefValue::get(ArgPtrTy);
5383 }
5384
5385 // Update VAList.
5386 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5387 Builder.CreateStore(Addr, VAListAddrAsBPP);
5388
5389 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005390}
5391
5392void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5393 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5394 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5395 it != ie; ++it)
5396 it->info = classifyType(it->type, 16 * 8);
5397}
5398
5399namespace {
5400class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5401public:
5402 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5403 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
5404};
5405} // end anonymous namespace
5406
5407
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005408//===----------------------------------------------------------------------===//
5409// Xcore ABI Implementation
5410//===----------------------------------------------------------------------===//
5411namespace {
Robert Lytton276c2892013-08-19 09:46:39 +00005412class XCoreABIInfo : public DefaultABIInfo {
5413public:
5414 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
5415 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5416 CodeGenFunction &CGF) const;
5417};
5418
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005419class XcoreTargetCodeGenInfo : public TargetCodeGenInfo {
5420public:
5421 XcoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton276c2892013-08-19 09:46:39 +00005422 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005423};
5424} // end anonymous namespace
5425
Robert Lytton276c2892013-08-19 09:46:39 +00005426llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5427 CodeGenFunction &CGF) const {
5428 ABIArgInfo AI = classifyArgumentType(Ty);
5429 CGBuilderTy &Builder = CGF.Builder;
5430 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5431 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5432 AI.setCoerceToType(ArgTy);
5433
5434 // handle the VAList
5435 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5436 CGF.Int8PtrPtrTy);
5437 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
5438 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, 4);
5439 Builder.CreateStore(APN, VAListAddrAsBPP);
5440
5441 // handle the argument
5442 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5443 switch (AI.getKind()) {
Robert Lytton276c2892013-08-19 09:46:39 +00005444 case ABIArgInfo::Expand:
5445 llvm_unreachable("Unsupported ABI kind for va_arg");
5446 case ABIArgInfo::Ignore:
5447 return llvm::UndefValue::get(ArgPtrTy);
5448 case ABIArgInfo::Extend:
5449 case ABIArgInfo::Direct:
5450 return Builder.CreatePointerCast(AP, ArgPtrTy);
5451 case ABIArgInfo::Indirect:
5452 llvm::Value *ArgAddr;
5453 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5454 ArgAddr = Builder.CreateLoad(ArgAddr);
5455 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5456 }
Alexey Samsonovacfea842013-08-19 13:07:12 +00005457 llvm_unreachable("Unknown ABI kind");
Robert Lytton276c2892013-08-19 09:46:39 +00005458}
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005459
5460//===----------------------------------------------------------------------===//
5461// Driver code
5462//===----------------------------------------------------------------------===//
5463
Chris Lattnerea044322010-07-29 02:01:43 +00005464const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005465 if (TheTargetCodeGenInfo)
5466 return *TheTargetCodeGenInfo;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005467
John McCall64aa4b32013-04-16 22:48:15 +00005468 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar1752ee42009-08-24 09:10:05 +00005469 switch (Triple.getArch()) {
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005470 default:
Chris Lattnerea044322010-07-29 02:01:43 +00005471 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005472
Derek Schuff9ed63f82012-09-06 17:37:28 +00005473 case llvm::Triple::le32:
5474 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCallaeeb7012010-05-27 06:19:26 +00005475 case llvm::Triple::mips:
5476 case llvm::Triple::mipsel:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005477 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
John McCallaeeb7012010-05-27 06:19:26 +00005478
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00005479 case llvm::Triple::mips64:
5480 case llvm::Triple::mips64el:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005481 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00005482
Tim Northoverc264e162013-01-31 12:13:10 +00005483 case llvm::Triple::aarch64:
5484 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5485
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005486 case llvm::Triple::arm:
5487 case llvm::Triple::thumb:
Sandeep Patel34c1af82011-04-05 00:23:47 +00005488 {
5489 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCall64aa4b32013-04-16 22:48:15 +00005490 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel34c1af82011-04-05 00:23:47 +00005491 Kind = ARMABIInfo::APCS;
David Tweedb16abb12012-10-25 13:33:01 +00005492 else if (CodeGenOpts.FloatABI == "hard" ||
John McCall64aa4b32013-04-16 22:48:15 +00005493 (CodeGenOpts.FloatABI != "soft" &&
5494 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel34c1af82011-04-05 00:23:47 +00005495 Kind = ARMABIInfo::AAPCS_VFP;
5496
Derek Schuff263366f2012-10-16 22:30:41 +00005497 switch (Triple.getOS()) {
Eli Bendersky441d9f72012-12-04 18:38:10 +00005498 case llvm::Triple::NaCl:
Derek Schuff263366f2012-10-16 22:30:41 +00005499 return *(TheTargetCodeGenInfo =
5500 new NaClARMTargetCodeGenInfo(Types, Kind));
5501 default:
5502 return *(TheTargetCodeGenInfo =
5503 new ARMTargetCodeGenInfo(Types, Kind));
5504 }
Sandeep Patel34c1af82011-04-05 00:23:47 +00005505 }
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005506
John McCallec853ba2010-03-11 00:10:12 +00005507 case llvm::Triple::ppc:
Chris Lattnerea044322010-07-29 02:01:43 +00005508 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divacky0fbc4b92012-05-09 18:22:46 +00005509 case llvm::Triple::ppc64:
Bill Schmidt2fc107f2012-10-03 19:18:57 +00005510 if (Triple.isOSBinFormatELF())
5511 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5512 else
5513 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidtea7fb0c2013-07-26 01:36:11 +00005514 case llvm::Triple::ppc64le:
5515 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5516 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallec853ba2010-03-11 00:10:12 +00005517
Peter Collingbourneedb66f32012-05-20 23:28:41 +00005518 case llvm::Triple::nvptx:
5519 case llvm::Triple::nvptx64:
Justin Holewinski2c585b92012-05-24 17:43:12 +00005520 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005521
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005522 case llvm::Triple::msp430:
Chris Lattnerea044322010-07-29 02:01:43 +00005523 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005524
Ulrich Weigandb8409212013-05-06 16:26:41 +00005525 case llvm::Triple::systemz:
5526 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5527
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005528 case llvm::Triple::tce:
5529 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5530
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00005531 case llvm::Triple::x86: {
John McCallb8b52972013-06-18 02:46:29 +00005532 bool IsDarwinVectorABI = Triple.isOSDarwin();
5533 bool IsSmallStructInRegABI =
5534 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5535 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbardb57a4c2011-04-19 21:43:27 +00005536
John McCallb8b52972013-06-18 02:46:29 +00005537 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedman55fc7e22012-01-25 22:46:34 +00005538 return *(TheTargetCodeGenInfo =
Reid Kleckner3190ca92013-05-08 13:44:39 +00005539 new WinX86_32TargetCodeGenInfo(Types,
John McCallb8b52972013-06-18 02:46:29 +00005540 IsDarwinVectorABI, IsSmallStructInRegABI,
5541 IsWin32FloatStructABI,
Reid Kleckner3190ca92013-05-08 13:44:39 +00005542 CodeGenOpts.NumRegisterParameters));
John McCallb8b52972013-06-18 02:46:29 +00005543 } else {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005544 return *(TheTargetCodeGenInfo =
John McCallb8b52972013-06-18 02:46:29 +00005545 new X86_32TargetCodeGenInfo(Types,
5546 IsDarwinVectorABI, IsSmallStructInRegABI,
5547 IsWin32FloatStructABI,
Rafael Espindolab48280b2012-07-31 02:44:24 +00005548 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005549 }
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00005550 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005551
Eli Friedmanee1ad992011-12-02 00:11:43 +00005552 case llvm::Triple::x86_64: {
John McCall64aa4b32013-04-16 22:48:15 +00005553 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanee1ad992011-12-02 00:11:43 +00005554
Chris Lattnerf13721d2010-08-31 16:44:54 +00005555 switch (Triple.getOS()) {
5556 case llvm::Triple::Win32:
NAKAMURA Takumi0aa20572011-02-17 08:51:38 +00005557 case llvm::Triple::MinGW32:
Chris Lattnerf13721d2010-08-31 16:44:54 +00005558 case llvm::Triple::Cygwin:
5559 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Bendersky441d9f72012-12-04 18:38:10 +00005560 case llvm::Triple::NaCl:
John McCall64aa4b32013-04-16 22:48:15 +00005561 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5562 HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00005563 default:
Eli Friedmanee1ad992011-12-02 00:11:43 +00005564 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5565 HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00005566 }
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005567 }
Tony Linthicum96319392011-12-12 21:14:55 +00005568 case llvm::Triple::hexagon:
5569 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005570 case llvm::Triple::sparcv9:
5571 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005572 case llvm::Triple::xcore:
5573 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types));
5574
Eli Friedmanee1ad992011-12-02 00:11:43 +00005575 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005576}