blob: fa9735705eba73ebe09a1ae01a15ea8d27992947 [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;
51 return CGT.CGM.getCXXABI().isReturnTypeIndirect(RD);
52}
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;
67 return CGT.CGM.getCXXABI().getRecordArgABI(RD);
68}
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)) {}
Eli Bendersky64b22d82013-07-03 19:19:12 +0000446
447 /// For PNaCl we don't want llvm.pow.* intrinsics to be emitted instead
448 /// of library function calls.
449 bool emitIntrinsicForPow() const { return false; }
Derek Schuff9ed63f82012-09-06 17:37:28 +0000450};
451
452void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
453 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
454
Derek Schuff9ed63f82012-09-06 17:37:28 +0000455 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
456 it != ie; ++it)
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000457 it->info = classifyArgumentType(it->type);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000458 }
459
460llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
461 CodeGenFunction &CGF) const {
462 return 0;
463}
464
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000465/// \brief Classify argument of given type \p Ty.
466ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff9ed63f82012-09-06 17:37:28 +0000467 if (isAggregateTypeForABI(Ty)) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000468 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
469 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000470 return ABIArgInfo::getIndirect(0);
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000471 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
472 // Treat an enum type as its underlying type.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000473 Ty = EnumTy->getDecl()->getIntegerType();
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000474 } else if (Ty->isFloatingType()) {
475 // Floating-point types don't go inreg.
476 return ABIArgInfo::getDirect();
Derek Schuff9ed63f82012-09-06 17:37:28 +0000477 }
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000478
479 return (Ty->isPromotableIntegerType() ?
480 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff9ed63f82012-09-06 17:37:28 +0000481}
482
483ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
484 if (RetTy->isVoidType())
485 return ABIArgInfo::getIgnore();
486
Eli Benderskye45dfd12013-04-04 22:49:35 +0000487 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000488 if (isAggregateTypeForABI(RetTy))
489 return ABIArgInfo::getIndirect(0);
490
491 // Treat an enum type as its underlying type.
492 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
493 RetTy = EnumTy->getDecl()->getIntegerType();
494
495 return (RetTy->isPromotableIntegerType() ?
496 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
497}
498
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000499/// IsX86_MMXType - Return true if this is an MMX type.
500bool IsX86_MMXType(llvm::Type *IRType) {
501 // 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 +0000502 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
503 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
504 IRType->getScalarSizeInBits() != 64;
505}
506
Jay Foadef6de3d2011-07-11 09:56:20 +0000507static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000508 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000509 llvm::Type* Ty) {
Tim Northover1bea6532013-06-07 00:04:50 +0000510 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
511 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
512 // Invalid MMX constraint
513 return 0;
514 }
515
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000516 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover1bea6532013-06-07 00:04:50 +0000517 }
518
519 // No operation needed
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000520 return Ty;
521}
522
Chris Lattnerdce5ad02010-06-28 20:05:43 +0000523//===----------------------------------------------------------------------===//
524// X86-32 ABI Implementation
525//===----------------------------------------------------------------------===//
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000526
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000527/// X86_32ABIInfo - The X86-32 ABI information.
528class X86_32ABIInfo : public ABIInfo {
Rafael Espindolab48280b2012-07-31 02:44:24 +0000529 enum Class {
530 Integer,
531 Float
532 };
533
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000534 static const unsigned MinABIStackAlignInBytes = 4;
535
David Chisnall1e4249c2009-08-17 23:08:21 +0000536 bool IsDarwinVectorABI;
537 bool IsSmallStructInRegABI;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000538 bool IsWin32StructABI;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000539 unsigned DefaultNumRegisterParameters;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000540
541 static bool isRegisterSize(unsigned Size) {
542 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
543 }
544
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000545 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
546 unsigned callingConvention);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000547
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000548 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
549 /// such that the argument will be passed in memory.
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000550 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal,
551 unsigned &FreeRegs) const;
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000552
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000553 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbare59d8582010-09-16 20:42:06 +0000554 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000555
Rafael Espindolab48280b2012-07-31 02:44:24 +0000556 Class classify(QualType Ty) const;
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000557 ABIArgInfo classifyReturnType(QualType RetTy,
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000558 unsigned callingConvention) const;
Rafael Espindolab6932692012-10-24 01:58:58 +0000559 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs,
560 bool IsFastCall) const;
561 bool shouldUseInReg(QualType Ty, unsigned &FreeRegs,
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000562 bool IsFastCall, bool &NeedsPadding) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000563
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000564public:
565
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000566 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000567 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
568 CodeGenFunction &CGF) const;
569
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000570 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindolab48280b2012-07-31 02:44:24 +0000571 unsigned r)
Eli Friedmanc3e0fb42011-07-08 23:31:17 +0000572 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000573 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000574};
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000575
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000576class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
577public:
Eli Friedman55fc7e22012-01-25 22:46:34 +0000578 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000579 bool d, bool p, bool w, unsigned r)
580 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis74f72932010-02-13 15:54:06 +0000581
John McCallb8b52972013-06-18 02:46:29 +0000582 static bool isStructReturnInRegABI(
583 const llvm::Triple &Triple, const CodeGenOptions &Opts);
584
Charles Davis74f72932010-02-13 15:54:06 +0000585 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
586 CodeGen::CodeGenModule &CGM) const;
John McCall6374c332010-03-06 00:35:14 +0000587
588 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
589 // Darwin uses different dwarf register numbers for EH.
John McCall64aa4b32013-04-16 22:48:15 +0000590 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCall6374c332010-03-06 00:35:14 +0000591 return 4;
592 }
593
594 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
595 llvm::Value *Address) const;
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000596
Jay Foadef6de3d2011-07-11 09:56:20 +0000597 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000598 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000599 llvm::Type* Ty) const {
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000600 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
601 }
602
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000603};
604
605}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000606
607/// shouldReturnTypeInRegister - Determine if the given type should be
608/// passed in a register (for the Darwin ABI).
609bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000610 ASTContext &Context,
611 unsigned callingConvention) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000612 uint64_t Size = Context.getTypeSize(Ty);
613
614 // Type must be register sized.
615 if (!isRegisterSize(Size))
616 return false;
617
618 if (Ty->isVectorType()) {
619 // 64- and 128- bit vectors inside structures are not returned in
620 // registers.
621 if (Size == 64 || Size == 128)
622 return false;
623
624 return true;
625 }
626
Daniel Dunbar77115232010-05-15 00:00:30 +0000627 // If this is a builtin, pointer, enum, complex type, member pointer, or
628 // member function pointer it is ok.
Daniel Dunbara1842d32010-05-14 03:40:53 +0000629 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbar55e59e12009-09-24 05:12:36 +0000630 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar77115232010-05-15 00:00:30 +0000631 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000632 return true;
633
634 // Arrays are treated like records.
635 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000636 return shouldReturnTypeInRegister(AT->getElementType(), Context,
637 callingConvention);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000638
639 // Otherwise, it must be a record type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000640 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000641 if (!RT) return false;
642
Anders Carlssona8874232010-01-27 03:25:19 +0000643 // FIXME: Traverse bases here too.
644
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000645 // For thiscall conventions, structures will never be returned in
646 // a register. This is for compatibility with the MSVC ABI
647 if (callingConvention == llvm::CallingConv::X86_ThisCall &&
648 RT->isStructureType()) {
649 return false;
650 }
651
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000652 // Structure types are passed in register if all fields would be
653 // passed in a register.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000654 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
655 e = RT->getDecl()->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000656 const FieldDecl *FD = *i;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000657
658 // Empty fields are ignored.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000659 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000660 continue;
661
662 // Check fields recursively.
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000663 if (!shouldReturnTypeInRegister(FD->getType(), Context,
664 callingConvention))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000665 return false;
666 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000667 return true;
668}
669
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000670ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
671 unsigned callingConvention) const {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000672 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000673 return ABIArgInfo::getIgnore();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000674
Chris Lattnera3c109b2010-07-29 02:16:43 +0000675 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000676 // On Darwin, some vectors are returned in registers.
David Chisnall1e4249c2009-08-17 23:08:21 +0000677 if (IsDarwinVectorABI) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000678 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000679
680 // 128-bit vectors are a special case; they are returned in
681 // registers and we need to make sure to pick a type the LLVM
682 // backend will like.
683 if (Size == 128)
Chris Lattner800588f2010-07-29 06:26:06 +0000684 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattnera3c109b2010-07-29 02:16:43 +0000685 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000686
687 // Always return in register if it fits in a general purpose
688 // register, or if it is 64 bits and has a single element.
689 if ((Size == 8 || Size == 16 || Size == 32) ||
690 (Size == 64 && VT->getNumElements() == 1))
Chris Lattner800588f2010-07-29 06:26:06 +0000691 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +0000692 Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000693
694 return ABIArgInfo::getIndirect(0);
695 }
696
697 return ABIArgInfo::getDirect();
Chris Lattnera3c109b2010-07-29 02:16:43 +0000698 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000699
John McCalld608cdb2010-08-22 10:59:02 +0000700 if (isAggregateTypeForABI(RetTy)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000701 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000702 if (isRecordReturnIndirect(RT, CGT))
Anders Carlsson40092972009-10-20 22:07:59 +0000703 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000704
Anders Carlsson40092972009-10-20 22:07:59 +0000705 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000706 if (RT->getDecl()->hasFlexibleArrayMember())
707 return ABIArgInfo::getIndirect(0);
Anders Carlsson40092972009-10-20 22:07:59 +0000708 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000709
David Chisnall1e4249c2009-08-17 23:08:21 +0000710 // If specified, structs and unions are always indirect.
711 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000712 return ABIArgInfo::getIndirect(0);
713
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000714 // Small structures which are register sized are generally returned
715 // in a register.
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000716 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(),
717 callingConvention)) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000718 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000719
720 // As a special-case, if the struct is a "single-element" struct, and
721 // the field is of type "float" or "double", return it in a
Eli Friedman55fc7e22012-01-25 22:46:34 +0000722 // floating-point register. (MSVC does not apply this special case.)
723 // We apply a similar transformation for pointer types to improve the
724 // quality of the generated IR.
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000725 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000726 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedman55fc7e22012-01-25 22:46:34 +0000727 || SeltTy->hasPointerRepresentation())
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000728 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
729
730 // FIXME: We should be able to narrow this integer in cases with dead
731 // padding.
Chris Lattner800588f2010-07-29 06:26:06 +0000732 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000733 }
734
735 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000736 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000737
Chris Lattnera3c109b2010-07-29 02:16:43 +0000738 // Treat an enum type as its underlying type.
739 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
740 RetTy = EnumTy->getDecl()->getIntegerType();
741
742 return (RetTy->isPromotableIntegerType() ?
743 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000744}
745
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000746static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
747 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
748}
749
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000750static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
751 const RecordType *RT = Ty->getAs<RecordType>();
752 if (!RT)
753 return 0;
754 const RecordDecl *RD = RT->getDecl();
755
756 // If this is a C++ record, check the bases first.
757 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
758 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
759 e = CXXRD->bases_end(); i != e; ++i)
760 if (!isRecordWithSSEVectorType(Context, i->getType()))
761 return false;
762
763 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
764 i != e; ++i) {
765 QualType FT = i->getType();
766
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000767 if (isSSEVectorType(Context, FT))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000768 return true;
769
770 if (isRecordWithSSEVectorType(Context, FT))
771 return true;
772 }
773
774 return false;
775}
776
Daniel Dunbare59d8582010-09-16 20:42:06 +0000777unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
778 unsigned Align) const {
779 // Otherwise, if the alignment is less than or equal to the minimum ABI
780 // alignment, just use the default; the backend will handle this.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000781 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbare59d8582010-09-16 20:42:06 +0000782 return 0; // Use default alignment.
783
784 // On non-Darwin, the stack type alignment is always 4.
785 if (!IsDarwinVectorABI) {
786 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000787 return MinABIStackAlignInBytes;
Daniel Dunbare59d8582010-09-16 20:42:06 +0000788 }
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000789
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000790 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000791 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
792 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000793 return 16;
794
795 return MinABIStackAlignInBytes;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000796}
797
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000798ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
799 unsigned &FreeRegs) const {
800 if (!ByVal) {
801 if (FreeRegs) {
802 --FreeRegs; // Non byval indirects just use one pointer.
803 return ABIArgInfo::getIndirectInReg(0, false);
804 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000805 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000806 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000807
Daniel Dunbare59d8582010-09-16 20:42:06 +0000808 // Compute the byval alignment.
809 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
810 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
811 if (StackAlign == 0)
Chris Lattnerde92d732011-05-22 23:35:00 +0000812 return ABIArgInfo::getIndirect(4);
Daniel Dunbare59d8582010-09-16 20:42:06 +0000813
814 // If the stack alignment is less than the type alignment, realign the
815 // argument.
816 if (StackAlign < TypeAlign)
817 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
818 /*Realign=*/true);
819
820 return ABIArgInfo::getIndirect(StackAlign);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000821}
822
Rafael Espindolab48280b2012-07-31 02:44:24 +0000823X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
824 const Type *T = isSingleElementStruct(Ty, getContext());
825 if (!T)
826 T = Ty.getTypePtr();
827
828 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
829 BuiltinType::Kind K = BT->getKind();
830 if (K == BuiltinType::Float || K == BuiltinType::Double)
831 return Float;
832 }
833 return Integer;
834}
835
Rafael Espindolab6932692012-10-24 01:58:58 +0000836bool X86_32ABIInfo::shouldUseInReg(QualType Ty, unsigned &FreeRegs,
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000837 bool IsFastCall, bool &NeedsPadding) const {
838 NeedsPadding = false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000839 Class C = classify(Ty);
840 if (C == Float)
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000841 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000842
Rafael Espindolab6932692012-10-24 01:58:58 +0000843 unsigned Size = getContext().getTypeSize(Ty);
844 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindola5f14fcb2012-10-23 02:04:01 +0000845
846 if (SizeInRegs == 0)
847 return false;
848
Rafael Espindolab48280b2012-07-31 02:44:24 +0000849 if (SizeInRegs > FreeRegs) {
850 FreeRegs = 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000851 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000852 }
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000853
Rafael Espindolab48280b2012-07-31 02:44:24 +0000854 FreeRegs -= SizeInRegs;
Rafael Espindolab6932692012-10-24 01:58:58 +0000855
856 if (IsFastCall) {
857 if (Size > 32)
858 return false;
859
860 if (Ty->isIntegralOrEnumerationType())
861 return true;
862
863 if (Ty->isPointerType())
864 return true;
865
866 if (Ty->isReferenceType())
867 return true;
868
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000869 if (FreeRegs)
870 NeedsPadding = true;
871
Rafael Espindolab6932692012-10-24 01:58:58 +0000872 return false;
873 }
874
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000875 return true;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000876}
877
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000878ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Rafael Espindolab6932692012-10-24 01:58:58 +0000879 unsigned &FreeRegs,
880 bool IsFastCall) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000881 // FIXME: Set alignment on indirect arguments.
John McCalld608cdb2010-08-22 10:59:02 +0000882 if (isAggregateTypeForABI(Ty)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000883 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000884 if (IsWin32StructABI)
885 return getIndirectResult(Ty, true, FreeRegs);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000886
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000887 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, CGT))
888 return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory, FreeRegs);
889
890 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000891 if (RT->getDecl()->hasFlexibleArrayMember())
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000892 return getIndirectResult(Ty, true, FreeRegs);
Anders Carlssona8874232010-01-27 03:25:19 +0000893 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000894
Eli Friedman5a4d3522011-11-18 00:28:11 +0000895 // Ignore empty structs/unions.
Eli Friedman5a1ac892011-11-18 04:01:36 +0000896 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000897 return ABIArgInfo::getIgnore();
898
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000899 llvm::LLVMContext &LLVMContext = getVMContext();
900 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
901 bool NeedsPadding;
902 if (shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding)) {
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000903 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000904 SmallVector<llvm::Type*, 3> Elements;
905 for (unsigned I = 0; I < SizeInRegs; ++I)
906 Elements.push_back(Int32);
907 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
908 return ABIArgInfo::getDirectInReg(Result);
909 }
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000910 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000911
Daniel Dunbar53012f42009-11-09 01:33:53 +0000912 // Expand small (<= 128-bit) record types when we know that the stack layout
913 // of those arguments will match the struct. This is important because the
914 // LLVM backend isn't smart enough to remove byval, which inhibits many
915 // optimizations.
Chris Lattnera3c109b2010-07-29 02:16:43 +0000916 if (getContext().getTypeSize(Ty) <= 4*32 &&
917 canExpandIndirectArgument(Ty, getContext()))
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000918 return ABIArgInfo::getExpandWithPadding(IsFastCall, PaddingType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000919
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000920 return getIndirectResult(Ty, true, FreeRegs);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000921 }
922
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000923 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner7b733502010-08-26 20:08:43 +0000924 // On Darwin, some vectors are passed in memory, we handle this by passing
925 // it as an i8/i16/i32/i64.
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000926 if (IsDarwinVectorABI) {
927 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000928 if ((Size == 8 || Size == 16 || Size == 32) ||
929 (Size == 64 && VT->getNumElements() == 1))
930 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
931 Size));
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000932 }
Bill Wendlingbb465d72010-10-18 03:41:31 +0000933
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000934 if (IsX86_MMXType(CGT.ConvertType(Ty)))
935 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000936
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000937 return ABIArgInfo::getDirect();
938 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000939
940
Chris Lattnera3c109b2010-07-29 02:16:43 +0000941 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
942 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000943
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000944 bool NeedsPadding;
945 bool InReg = shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000946
947 if (Ty->isPromotableIntegerType()) {
948 if (InReg)
949 return ABIArgInfo::getExtendInReg();
950 return ABIArgInfo::getExtend();
951 }
952 if (InReg)
953 return ABIArgInfo::getDirectInReg();
954 return ABIArgInfo::getDirect();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000955}
956
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000957void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
958 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
959 FI.getCallingConvention());
Rafael Espindolab48280b2012-07-31 02:44:24 +0000960
Rafael Espindolab6932692012-10-24 01:58:58 +0000961 unsigned CC = FI.getCallingConvention();
962 bool IsFastCall = CC == llvm::CallingConv::X86_FastCall;
963 unsigned FreeRegs;
964 if (IsFastCall)
965 FreeRegs = 2;
966 else if (FI.getHasRegParm())
967 FreeRegs = FI.getRegParm();
968 else
969 FreeRegs = DefaultNumRegisterParameters;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000970
971 // If the return value is indirect, then the hidden argument is consuming one
972 // integer register.
973 if (FI.getReturnInfo().isIndirect() && FreeRegs) {
974 --FreeRegs;
975 ABIArgInfo &Old = FI.getReturnInfo();
976 Old = ABIArgInfo::getIndirectInReg(Old.getIndirectAlign(),
977 Old.getIndirectByVal(),
978 Old.getIndirectRealign());
979 }
980
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000981 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
982 it != ie; ++it)
Rafael Espindolab6932692012-10-24 01:58:58 +0000983 it->info = classifyArgumentType(it->type, FreeRegs, IsFastCall);
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000984}
985
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000986llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
987 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +0000988 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000989
990 CGBuilderTy &Builder = CGF.Builder;
991 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
992 "ap");
993 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman7b1fb812011-11-18 02:12:09 +0000994
995 // Compute if the address needs to be aligned
996 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
997 Align = getTypeStackAlignInBytes(Ty, Align);
998 Align = std::max(Align, 4U);
999 if (Align > 4) {
1000 // addr = (addr + align - 1) & -align;
1001 llvm::Value *Offset =
1002 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1003 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1004 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1005 CGF.Int32Ty);
1006 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1007 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1008 Addr->getType(),
1009 "ap.cur.aligned");
1010 }
1011
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001012 llvm::Type *PTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001013 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001014 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1015
1016 uint64_t Offset =
Eli Friedman7b1fb812011-11-18 02:12:09 +00001017 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001018 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00001019 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001020 "ap.next");
1021 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1022
1023 return AddrTyped;
1024}
1025
Charles Davis74f72932010-02-13 15:54:06 +00001026void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1027 llvm::GlobalValue *GV,
1028 CodeGen::CodeGenModule &CGM) const {
1029 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1030 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1031 // Get the LLVM function.
1032 llvm::Function *Fn = cast<llvm::Function>(GV);
1033
1034 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendling0d583392012-10-15 20:36:26 +00001035 llvm::AttrBuilder B;
Bill Wendlinge91e9ec2012-10-14 03:28:14 +00001036 B.addStackAlignmentAttr(16);
Bill Wendling909b6de2013-01-23 00:21:06 +00001037 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1038 llvm::AttributeSet::get(CGM.getLLVMContext(),
1039 llvm::AttributeSet::FunctionIndex,
1040 B));
Charles Davis74f72932010-02-13 15:54:06 +00001041 }
1042 }
1043}
1044
John McCall6374c332010-03-06 00:35:14 +00001045bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1046 CodeGen::CodeGenFunction &CGF,
1047 llvm::Value *Address) const {
1048 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCall6374c332010-03-06 00:35:14 +00001049
Chris Lattner8b418682012-02-07 00:39:47 +00001050 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001051
John McCall6374c332010-03-06 00:35:14 +00001052 // 0-7 are the eight integer registers; the order is different
1053 // on Darwin (for EH), but the range is the same.
1054 // 8 is %eip.
John McCallaeeb7012010-05-27 06:19:26 +00001055 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCall6374c332010-03-06 00:35:14 +00001056
John McCall64aa4b32013-04-16 22:48:15 +00001057 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCall6374c332010-03-06 00:35:14 +00001058 // 12-16 are st(0..4). Not sure why we stop at 4.
1059 // These have size 16, which is sizeof(long double) on
1060 // platforms with 8-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001061 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCallaeeb7012010-05-27 06:19:26 +00001062 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001063
John McCall6374c332010-03-06 00:35:14 +00001064 } else {
1065 // 9 is %eflags, which doesn't get a size on Darwin for some
1066 // reason.
1067 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1068
1069 // 11-16 are st(0..5). Not sure why we stop at 5.
1070 // These have size 12, which is sizeof(long double) on
1071 // platforms with 4-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001072 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCallaeeb7012010-05-27 06:19:26 +00001073 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1074 }
John McCall6374c332010-03-06 00:35:14 +00001075
1076 return false;
1077}
1078
Chris Lattnerdce5ad02010-06-28 20:05:43 +00001079//===----------------------------------------------------------------------===//
1080// X86-64 ABI Implementation
1081//===----------------------------------------------------------------------===//
1082
1083
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001084namespace {
1085/// X86_64ABIInfo - The X86_64 ABI information.
1086class X86_64ABIInfo : public ABIInfo {
1087 enum Class {
1088 Integer = 0,
1089 SSE,
1090 SSEUp,
1091 X87,
1092 X87Up,
1093 ComplexX87,
1094 NoClass,
1095 Memory
1096 };
1097
1098 /// merge - Implement the X86_64 ABI merging algorithm.
1099 ///
1100 /// Merge an accumulating classification \arg Accum with a field
1101 /// classification \arg Field.
1102 ///
1103 /// \param Accum - The accumulating classification. This should
1104 /// always be either NoClass or the result of a previous merge
1105 /// call. In addition, this should never be Memory (the caller
1106 /// should just return Memory for the aggregate).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001107 static Class merge(Class Accum, Class Field);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001108
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001109 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1110 ///
1111 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1112 /// final MEMORY or SSE classes when necessary.
1113 ///
1114 /// \param AggregateSize - The size of the current aggregate in
1115 /// the classification process.
1116 ///
1117 /// \param Lo - The classification for the parts of the type
1118 /// residing in the low word of the containing object.
1119 ///
1120 /// \param Hi - The classification for the parts of the type
1121 /// residing in the higher words of the containing object.
1122 ///
1123 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1124
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001125 /// classify - Determine the x86_64 register classes in which the
1126 /// given type T should be passed.
1127 ///
1128 /// \param Lo - The classification for the parts of the type
1129 /// residing in the low word of the containing object.
1130 ///
1131 /// \param Hi - The classification for the parts of the type
1132 /// residing in the high word of the containing object.
1133 ///
1134 /// \param OffsetBase - The bit offset of this type in the
1135 /// containing object. Some parameters are classified different
1136 /// depending on whether they straddle an eightbyte boundary.
1137 ///
Eli Friedman7a1b5862013-06-12 00:13:45 +00001138 /// \param isNamedArg - Whether the argument in question is a "named"
1139 /// argument, as used in AMD64-ABI 3.5.7.
1140 ///
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001141 /// If a word is unused its result will be NoClass; if a type should
1142 /// be passed in Memory then at least the classification of \arg Lo
1143 /// will be Memory.
1144 ///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001145 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001146 ///
1147 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1148 /// also be ComplexX87.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001149 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1150 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001151
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001152 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001153 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1154 unsigned IROffset, QualType SourceTy,
1155 unsigned SourceOffset) const;
1156 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1157 unsigned IROffset, QualType SourceTy,
1158 unsigned SourceOffset) const;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001159
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001160 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001161 /// such that the argument will be returned in memory.
Chris Lattner9c254f02010-06-29 06:01:59 +00001162 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001163
1164 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001165 /// such that the argument will be passed in memory.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001166 ///
1167 /// \param freeIntRegs - The number of free integer registers remaining
1168 /// available.
1169 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001170
Chris Lattnera3c109b2010-07-29 02:16:43 +00001171 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001172
Bill Wendlingbb465d72010-10-18 03:41:31 +00001173 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbaredfac032012-03-10 01:03:58 +00001174 unsigned freeIntRegs,
Bill Wendlingbb465d72010-10-18 03:41:31 +00001175 unsigned &neededInt,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001176 unsigned &neededSSE,
1177 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001178
Eli Friedmanee1ad992011-12-02 00:11:43 +00001179 bool IsIllegalVectorType(QualType Ty) const;
1180
John McCall67a57732011-04-21 01:20:55 +00001181 /// The 0.98 ABI revision clarified a lot of ambiguities,
1182 /// unfortunately in ways that were not always consistent with
1183 /// certain previous compilers. In particular, platforms which
1184 /// required strict binary compatibility with older versions of GCC
1185 /// may need to exempt themselves.
1186 bool honorsRevision0_98() const {
John McCall64aa4b32013-04-16 22:48:15 +00001187 return !getTarget().getTriple().isOSDarwin();
John McCall67a57732011-04-21 01:20:55 +00001188 }
1189
Eli Friedmanee1ad992011-12-02 00:11:43 +00001190 bool HasAVX;
Derek Schuffbabaf312012-10-11 15:52:22 +00001191 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1192 // 64-bit hardware.
1193 bool Has64BitPointers;
Eli Friedmanee1ad992011-12-02 00:11:43 +00001194
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001195public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001196 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffbabaf312012-10-11 15:52:22 +00001197 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff90da80c2012-10-11 18:21:13 +00001198 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001199 }
Chris Lattner9c254f02010-06-29 06:01:59 +00001200
John McCallde5d3c72012-02-17 03:33:10 +00001201 bool isPassedUsingAVXType(QualType type) const {
1202 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00001203 // The freeIntRegs argument doesn't matter here.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001204 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1205 /*isNamedArg*/true);
John McCallde5d3c72012-02-17 03:33:10 +00001206 if (info.isDirect()) {
1207 llvm::Type *ty = info.getCoerceToType();
1208 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1209 return (vectorTy->getBitWidth() > 128);
1210 }
1211 return false;
1212 }
1213
Chris Lattneree5dcd02010-07-29 02:31:05 +00001214 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001215
1216 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1217 CodeGenFunction &CGF) const;
1218};
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001219
Chris Lattnerf13721d2010-08-31 16:44:54 +00001220/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001221class WinX86_64ABIInfo : public ABIInfo {
1222
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001223 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001224
Chris Lattnerf13721d2010-08-31 16:44:54 +00001225public:
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001226 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1227
1228 virtual void computeInfo(CGFunctionInfo &FI) const;
Chris Lattnerf13721d2010-08-31 16:44:54 +00001229
1230 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1231 CodeGenFunction &CGF) const;
1232};
1233
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001234class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1235public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001236 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffbabaf312012-10-11 15:52:22 +00001237 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCall6374c332010-03-06 00:35:14 +00001238
John McCallde5d3c72012-02-17 03:33:10 +00001239 const X86_64ABIInfo &getABIInfo() const {
1240 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1241 }
1242
John McCall6374c332010-03-06 00:35:14 +00001243 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1244 return 7;
1245 }
1246
1247 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1248 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001249 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001250
John McCallaeeb7012010-05-27 06:19:26 +00001251 // 0-15 are the 16 integer registers.
1252 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001253 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCall6374c332010-03-06 00:35:14 +00001254 return false;
1255 }
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001256
Jay Foadef6de3d2011-07-11 09:56:20 +00001257 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001258 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +00001259 llvm::Type* Ty) const {
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001260 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1261 }
1262
John McCallde5d3c72012-02-17 03:33:10 +00001263 bool isNoProtoCallVariadic(const CallArgList &args,
1264 const FunctionNoProtoType *fnType) const {
John McCall01f151e2011-09-21 08:08:30 +00001265 // The default CC on x86-64 sets %al to the number of SSA
1266 // registers used, and GCC sets this when calling an unprototyped
Eli Friedman3ed79032011-12-01 04:53:19 +00001267 // function, so we override the default behavior. However, don't do
Eli Friedman68805fe2011-12-06 03:08:26 +00001268 // that when AVX types are involved: the ABI explicitly states it is
1269 // undefined, and it doesn't work in practice because of how the ABI
1270 // defines varargs anyway.
John McCallde5d3c72012-02-17 03:33:10 +00001271 if (fnType->getCallConv() == CC_Default || fnType->getCallConv() == CC_C) {
Eli Friedman3ed79032011-12-01 04:53:19 +00001272 bool HasAVXType = false;
John McCallde5d3c72012-02-17 03:33:10 +00001273 for (CallArgList::const_iterator
1274 it = args.begin(), ie = args.end(); it != ie; ++it) {
1275 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1276 HasAVXType = true;
1277 break;
Eli Friedman3ed79032011-12-01 04:53:19 +00001278 }
1279 }
John McCallde5d3c72012-02-17 03:33:10 +00001280
Eli Friedman3ed79032011-12-01 04:53:19 +00001281 if (!HasAVXType)
1282 return true;
1283 }
John McCall01f151e2011-09-21 08:08:30 +00001284
John McCallde5d3c72012-02-17 03:33:10 +00001285 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCall01f151e2011-09-21 08:08:30 +00001286 }
1287
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001288};
1289
Aaron Ballman89735b92013-05-24 15:06:56 +00001290static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1291 // If the argument does not end in .lib, automatically add the suffix. This
1292 // matches the behavior of MSVC.
1293 std::string ArgStr = Lib;
1294 if (Lib.size() <= 4 ||
1295 Lib.substr(Lib.size() - 4).compare_lower(".lib") != 0) {
1296 ArgStr += ".lib";
1297 }
1298 return ArgStr;
1299}
1300
Reid Kleckner3190ca92013-05-08 13:44:39 +00001301class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1302public:
John McCallb8b52972013-06-18 02:46:29 +00001303 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1304 bool d, bool p, bool w, unsigned RegParms)
1305 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Kleckner3190ca92013-05-08 13:44:39 +00001306
1307 void getDependentLibraryOption(llvm::StringRef Lib,
1308 llvm::SmallString<24> &Opt) const {
1309 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001310 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001311 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001312
1313 void getDetectMismatchOption(llvm::StringRef Name,
1314 llvm::StringRef Value,
1315 llvm::SmallString<32> &Opt) const {
Eli Friedman572ac322013-06-07 22:42:22 +00001316 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001317 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001318};
1319
Chris Lattnerf13721d2010-08-31 16:44:54 +00001320class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1321public:
1322 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1323 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1324
1325 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1326 return 7;
1327 }
1328
1329 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1330 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001331 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001332
Chris Lattnerf13721d2010-08-31 16:44:54 +00001333 // 0-15 are the 16 integer registers.
1334 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001335 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattnerf13721d2010-08-31 16:44:54 +00001336 return false;
1337 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001338
1339 void getDependentLibraryOption(llvm::StringRef Lib,
1340 llvm::SmallString<24> &Opt) const {
1341 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001342 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001343 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001344
1345 void getDetectMismatchOption(llvm::StringRef Name,
1346 llvm::StringRef Value,
1347 llvm::SmallString<32> &Opt) const {
Eli Friedman572ac322013-06-07 22:42:22 +00001348 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001349 }
Chris Lattnerf13721d2010-08-31 16:44:54 +00001350};
1351
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001352}
1353
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001354void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1355 Class &Hi) const {
1356 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1357 //
1358 // (a) If one of the classes is Memory, the whole argument is passed in
1359 // memory.
1360 //
1361 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1362 // memory.
1363 //
1364 // (c) If the size of the aggregate exceeds two eightbytes and the first
1365 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1366 // argument is passed in memory. NOTE: This is necessary to keep the
1367 // ABI working for processors that don't support the __m256 type.
1368 //
1369 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1370 //
1371 // Some of these are enforced by the merging logic. Others can arise
1372 // only with unions; for example:
1373 // union { _Complex double; unsigned; }
1374 //
1375 // Note that clauses (b) and (c) were added in 0.98.
1376 //
1377 if (Hi == Memory)
1378 Lo = Memory;
1379 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1380 Lo = Memory;
1381 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1382 Lo = Memory;
1383 if (Hi == SSEUp && Lo != SSE)
1384 Hi = SSE;
1385}
1386
Chris Lattner1090a9b2010-06-28 21:43:59 +00001387X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001388 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1389 // classified recursively so that always two fields are
1390 // considered. The resulting class is calculated according to
1391 // the classes of the fields in the eightbyte:
1392 //
1393 // (a) If both classes are equal, this is the resulting class.
1394 //
1395 // (b) If one of the classes is NO_CLASS, the resulting class is
1396 // the other class.
1397 //
1398 // (c) If one of the classes is MEMORY, the result is the MEMORY
1399 // class.
1400 //
1401 // (d) If one of the classes is INTEGER, the result is the
1402 // INTEGER.
1403 //
1404 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1405 // MEMORY is used as class.
1406 //
1407 // (f) Otherwise class SSE is used.
1408
1409 // Accum should never be memory (we should have returned) or
1410 // ComplexX87 (because this cannot be passed in a structure).
1411 assert((Accum != Memory && Accum != ComplexX87) &&
1412 "Invalid accumulated classification during merge.");
1413 if (Accum == Field || Field == NoClass)
1414 return Accum;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001415 if (Field == Memory)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001416 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001417 if (Accum == NoClass)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001418 return Field;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001419 if (Accum == Integer || Field == Integer)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001420 return Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001421 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1422 Accum == X87 || Accum == X87Up)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001423 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001424 return SSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001425}
1426
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001427void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001428 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001429 // FIXME: This code can be simplified by introducing a simple value class for
1430 // Class pairs with appropriate constructor methods for the various
1431 // situations.
1432
1433 // FIXME: Some of the split computations are wrong; unaligned vectors
1434 // shouldn't be passed in registers for example, so there is no chance they
1435 // can straddle an eightbyte. Verify & simplify.
1436
1437 Lo = Hi = NoClass;
1438
1439 Class &Current = OffsetBase < 64 ? Lo : Hi;
1440 Current = Memory;
1441
John McCall183700f2009-09-21 23:43:11 +00001442 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001443 BuiltinType::Kind k = BT->getKind();
1444
1445 if (k == BuiltinType::Void) {
1446 Current = NoClass;
1447 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1448 Lo = Integer;
1449 Hi = Integer;
1450 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1451 Current = Integer;
Derek Schuff7da46f92012-10-11 16:55:58 +00001452 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1453 (k == BuiltinType::LongDouble &&
John McCall64aa4b32013-04-16 22:48:15 +00001454 getTarget().getTriple().getOS() == llvm::Triple::NaCl)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001455 Current = SSE;
1456 } else if (k == BuiltinType::LongDouble) {
1457 Lo = X87;
1458 Hi = X87Up;
1459 }
1460 // FIXME: _Decimal32 and _Decimal64 are SSE.
1461 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
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 (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001466 // Classify the underlying integer type.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001467 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattner1090a9b2010-06-28 21:43:59 +00001468 return;
1469 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001470
Chris Lattner1090a9b2010-06-28 21:43:59 +00001471 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001472 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001473 return;
1474 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001475
Chris Lattner1090a9b2010-06-28 21:43:59 +00001476 if (Ty->isMemberPointerType()) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001477 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar67d438d2010-05-15 00:00:37 +00001478 Lo = Hi = Integer;
1479 else
1480 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001481 return;
1482 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001483
Chris Lattner1090a9b2010-06-28 21:43:59 +00001484 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001485 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001486 if (Size == 32) {
1487 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1488 // float> as integer.
1489 Current = Integer;
1490
1491 // If this type crosses an eightbyte boundary, it should be
1492 // split.
1493 uint64_t EB_Real = (OffsetBase) / 64;
1494 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1495 if (EB_Real != EB_Imag)
1496 Hi = Lo;
1497 } else if (Size == 64) {
1498 // gcc passes <1 x double> in memory. :(
1499 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1500 return;
1501
1502 // gcc passes <1 x long long> as INTEGER.
Chris Lattner473f8e72010-08-26 18:03:20 +00001503 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner0fefa412010-08-26 18:13:50 +00001504 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1505 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1506 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001507 Current = Integer;
1508 else
1509 Current = SSE;
1510
1511 // If this type crosses an eightbyte boundary, it should be
1512 // split.
1513 if (OffsetBase && OffsetBase != 64)
1514 Hi = Lo;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001515 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001516 // Arguments of 256-bits are split into four eightbyte chunks. The
1517 // least significant one belongs to class SSE and all the others to class
1518 // SSEUP. The original Lo and Hi design considers that types can't be
1519 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1520 // This design isn't correct for 256-bits, but since there're no cases
1521 // where the upper parts would need to be inspected, avoid adding
1522 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001523 //
1524 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1525 // registers if they are "named", i.e. not part of the "..." of a
1526 // variadic function.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001527 Lo = SSE;
1528 Hi = SSEUp;
1529 }
Chris Lattner1090a9b2010-06-28 21:43:59 +00001530 return;
1531 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001532
Chris Lattner1090a9b2010-06-28 21:43:59 +00001533 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001534 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001535
Chris Lattnerea044322010-07-29 02:01:43 +00001536 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001537 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001538 if (Size <= 64)
1539 Current = Integer;
1540 else if (Size <= 128)
1541 Lo = Hi = Integer;
Chris Lattnerea044322010-07-29 02:01:43 +00001542 } else if (ET == getContext().FloatTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001543 Current = SSE;
Derek Schuff7da46f92012-10-11 16:55:58 +00001544 else if (ET == getContext().DoubleTy ||
1545 (ET == getContext().LongDoubleTy &&
John McCall64aa4b32013-04-16 22:48:15 +00001546 getTarget().getTriple().getOS() == llvm::Triple::NaCl))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001547 Lo = Hi = SSE;
Chris Lattnerea044322010-07-29 02:01:43 +00001548 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001549 Current = ComplexX87;
1550
1551 // If this complex type crosses an eightbyte boundary then it
1552 // should be split.
1553 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattnerea044322010-07-29 02:01:43 +00001554 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001555 if (Hi == NoClass && EB_Real != EB_Imag)
1556 Hi = Lo;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001557
Chris Lattner1090a9b2010-06-28 21:43:59 +00001558 return;
1559 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001560
Chris Lattnerea044322010-07-29 02:01:43 +00001561 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001562 // Arrays are treated like structures.
1563
Chris Lattnerea044322010-07-29 02:01:43 +00001564 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001565
1566 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001567 // than four eightbytes, ..., it has class MEMORY.
1568 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001569 return;
1570
1571 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1572 // fields, it has class MEMORY.
1573 //
1574 // Only need to check alignment of array base.
Chris Lattnerea044322010-07-29 02:01:43 +00001575 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001576 return;
1577
1578 // Otherwise implement simplified merge. We could be smarter about
1579 // this, but it isn't worth it and would be harder to verify.
1580 Current = NoClass;
Chris Lattnerea044322010-07-29 02:01:43 +00001581 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001582 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes089d8922011-07-12 01:27:38 +00001583
1584 // The only case a 256-bit wide vector could be used is when the array
1585 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1586 // to work for sizes wider than 128, early check and fallback to memory.
1587 if (Size > 128 && EltSize != 256)
1588 return;
1589
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001590 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1591 Class FieldLo, FieldHi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001592 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001593 Lo = merge(Lo, FieldLo);
1594 Hi = merge(Hi, FieldHi);
1595 if (Lo == Memory || Hi == Memory)
1596 break;
1597 }
1598
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001599 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001600 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattner1090a9b2010-06-28 21:43:59 +00001601 return;
1602 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001603
Chris Lattner1090a9b2010-06-28 21:43:59 +00001604 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001605 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001606
1607 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001608 // than four eightbytes, ..., it has class MEMORY.
1609 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001610 return;
1611
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001612 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1613 // copy constructor or a non-trivial destructor, it is passed by invisible
1614 // reference.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001615 if (getRecordArgABI(RT, CGT))
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001616 return;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001617
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001618 const RecordDecl *RD = RT->getDecl();
1619
1620 // Assume variable sized types are passed in memory.
1621 if (RD->hasFlexibleArrayMember())
1622 return;
1623
Chris Lattnerea044322010-07-29 02:01:43 +00001624 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001625
1626 // Reset Lo class, this will be recomputed.
1627 Current = NoClass;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001628
1629 // If this is a C++ record, classify the bases first.
1630 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1631 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1632 e = CXXRD->bases_end(); i != e; ++i) {
1633 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1634 "Unexpected base class!");
1635 const CXXRecordDecl *Base =
1636 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1637
1638 // Classify this field.
1639 //
1640 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1641 // single eightbyte, each is classified separately. Each eightbyte gets
1642 // initialized to class NO_CLASS.
1643 Class FieldLo, FieldHi;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001644 uint64_t Offset =
1645 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Eli Friedman7a1b5862013-06-12 00:13:45 +00001646 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001647 Lo = merge(Lo, FieldLo);
1648 Hi = merge(Hi, FieldHi);
1649 if (Lo == Memory || Hi == Memory)
1650 break;
1651 }
1652 }
1653
1654 // Classify the fields one at a time, merging the results.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001655 unsigned idx = 0;
Bruno Cardoso Lopes548e4782011-07-12 22:30:58 +00001656 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001657 i != e; ++i, ++idx) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001658 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1659 bool BitField = i->isBitField();
1660
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001661 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1662 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001663 //
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001664 // The only case a 256-bit wide vector could be used is when the struct
1665 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1666 // to work for sizes wider than 128, early check and fallback to memory.
1667 //
1668 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1669 Lo = Memory;
1670 return;
1671 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001672 // Note, skip this test for bit-fields, see below.
Chris Lattnerea044322010-07-29 02:01:43 +00001673 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001674 Lo = Memory;
1675 return;
1676 }
1677
1678 // Classify this field.
1679 //
1680 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1681 // exceeds a single eightbyte, each is classified
1682 // separately. Each eightbyte gets initialized to class
1683 // NO_CLASS.
1684 Class FieldLo, FieldHi;
1685
1686 // Bit-fields require special handling, they do not force the
1687 // structure to be passed in memory even if unaligned, and
1688 // therefore they can straddle an eightbyte.
1689 if (BitField) {
1690 // Ignore padding bit-fields.
1691 if (i->isUnnamedBitfield())
1692 continue;
1693
1694 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001695 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001696
1697 uint64_t EB_Lo = Offset / 64;
1698 uint64_t EB_Hi = (Offset + Size - 1) / 64;
1699 FieldLo = FieldHi = NoClass;
1700 if (EB_Lo) {
1701 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1702 FieldLo = NoClass;
1703 FieldHi = Integer;
1704 } else {
1705 FieldLo = Integer;
1706 FieldHi = EB_Hi ? Integer : NoClass;
1707 }
1708 } else
Eli Friedman7a1b5862013-06-12 00:13:45 +00001709 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001710 Lo = merge(Lo, FieldLo);
1711 Hi = merge(Hi, FieldHi);
1712 if (Lo == Memory || Hi == Memory)
1713 break;
1714 }
1715
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001716 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001717 }
1718}
1719
Chris Lattner9c254f02010-06-29 06:01:59 +00001720ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001721 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1722 // place naturally.
John McCalld608cdb2010-08-22 10:59:02 +00001723 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001724 // Treat an enum type as its underlying type.
1725 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1726 Ty = EnumTy->getDecl()->getIntegerType();
1727
1728 return (Ty->isPromotableIntegerType() ?
1729 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1730 }
1731
1732 return ABIArgInfo::getIndirect(0);
1733}
1734
Eli Friedmanee1ad992011-12-02 00:11:43 +00001735bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1736 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1737 uint64_t Size = getContext().getTypeSize(VecTy);
1738 unsigned LargestVector = HasAVX ? 256 : 128;
1739 if (Size <= 64 || Size > LargestVector)
1740 return true;
1741 }
1742
1743 return false;
1744}
1745
Daniel Dunbaredfac032012-03-10 01:03:58 +00001746ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1747 unsigned freeIntRegs) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001748 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1749 // place naturally.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001750 //
1751 // This assumption is optimistic, as there could be free registers available
1752 // when we need to pass this argument in memory, and LLVM could try to pass
1753 // the argument in the free register. This does not seem to happen currently,
1754 // but this code would be much safer if we could mark the argument with
1755 // 'onstack'. See PR12193.
Eli Friedmanee1ad992011-12-02 00:11:43 +00001756 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001757 // Treat an enum type as its underlying type.
1758 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1759 Ty = EnumTy->getDecl()->getIntegerType();
1760
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001761 return (Ty->isPromotableIntegerType() ?
1762 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001763 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001764
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001765 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
1766 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001767
Chris Lattner855d2272011-05-22 23:21:23 +00001768 // Compute the byval alignment. We specify the alignment of the byval in all
1769 // cases so that the mid-level optimizer knows the alignment of the byval.
1770 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbaredfac032012-03-10 01:03:58 +00001771
1772 // Attempt to avoid passing indirect results using byval when possible. This
1773 // is important for good codegen.
1774 //
1775 // We do this by coercing the value into a scalar type which the backend can
1776 // handle naturally (i.e., without using byval).
1777 //
1778 // For simplicity, we currently only do this when we have exhausted all of the
1779 // free integer registers. Doing this when there are free integer registers
1780 // would require more care, as we would have to ensure that the coerced value
1781 // did not claim the unused register. That would require either reording the
1782 // arguments to the function (so that any subsequent inreg values came first),
1783 // or only doing this optimization when there were no following arguments that
1784 // might be inreg.
1785 //
1786 // We currently expect it to be rare (particularly in well written code) for
1787 // arguments to be passed on the stack when there are still free integer
1788 // registers available (this would typically imply large structs being passed
1789 // by value), so this seems like a fair tradeoff for now.
1790 //
1791 // We can revisit this if the backend grows support for 'onstack' parameter
1792 // attributes. See PR12193.
1793 if (freeIntRegs == 0) {
1794 uint64_t Size = getContext().getTypeSize(Ty);
1795
1796 // If this type fits in an eightbyte, coerce it into the matching integral
1797 // type, which will end up on the stack (with alignment 8).
1798 if (Align == 8 && Size <= 64)
1799 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1800 Size));
1801 }
1802
Chris Lattner855d2272011-05-22 23:21:23 +00001803 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001804}
1805
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001806/// GetByteVectorType - The ABI specifies that a value should be passed in an
1807/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner0f408f52010-07-29 04:56:46 +00001808/// vector register.
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001809llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001810 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001811
Chris Lattner15842bd2010-07-29 05:02:29 +00001812 // Wrapper structs that just contain vectors are passed just like vectors,
1813 // strip them off if present.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001814 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner15842bd2010-07-29 05:02:29 +00001815 while (STy && STy->getNumElements() == 1) {
1816 IRType = STy->getElementType(0);
1817 STy = dyn_cast<llvm::StructType>(IRType);
1818 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001819
Bruno Cardoso Lopes528a8c72011-07-08 22:57:35 +00001820 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001821 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1822 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001823 unsigned BitWidth = VT->getBitWidth();
Tanya Lattnerce275672011-11-28 23:18:11 +00001824 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner0f408f52010-07-29 04:56:46 +00001825 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1826 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1827 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1828 EltTy->isIntegerTy(128)))
1829 return VT;
1830 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001831
Chris Lattner0f408f52010-07-29 04:56:46 +00001832 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1833}
1834
Chris Lattnere2962be2010-07-29 07:30:00 +00001835/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1836/// is known to either be off the end of the specified type or being in
1837/// alignment padding. The user type specified is known to be at most 128 bits
1838/// in size, and have passed through X86_64ABIInfo::classify with a successful
1839/// classification that put one of the two halves in the INTEGER class.
1840///
1841/// It is conservatively correct to return false.
1842static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1843 unsigned EndBit, ASTContext &Context) {
1844 // If the bytes being queried are off the end of the type, there is no user
1845 // data hiding here. This handles analysis of builtins, vectors and other
1846 // types that don't contain interesting padding.
1847 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1848 if (TySize <= StartBit)
1849 return true;
1850
Chris Lattner021c3a32010-07-29 07:43:55 +00001851 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1852 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1853 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1854
1855 // Check each element to see if the element overlaps with the queried range.
1856 for (unsigned i = 0; i != NumElts; ++i) {
1857 // If the element is after the span we care about, then we're done..
1858 unsigned EltOffset = i*EltSize;
1859 if (EltOffset >= EndBit) break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001860
Chris Lattner021c3a32010-07-29 07:43:55 +00001861 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1862 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1863 EndBit-EltOffset, Context))
1864 return false;
1865 }
1866 // If it overlaps no elements, then it is safe to process as padding.
1867 return true;
1868 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001869
Chris Lattnere2962be2010-07-29 07:30:00 +00001870 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1871 const RecordDecl *RD = RT->getDecl();
1872 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001873
Chris Lattnere2962be2010-07-29 07:30:00 +00001874 // If this is a C++ record, check the bases first.
1875 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1876 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1877 e = CXXRD->bases_end(); i != e; ++i) {
1878 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1879 "Unexpected base class!");
1880 const CXXRecordDecl *Base =
1881 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001882
Chris Lattnere2962be2010-07-29 07:30:00 +00001883 // If the base is after the span we care about, ignore it.
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001884 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnere2962be2010-07-29 07:30:00 +00001885 if (BaseOffset >= EndBit) continue;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001886
Chris Lattnere2962be2010-07-29 07:30:00 +00001887 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1888 if (!BitsContainNoUserData(i->getType(), BaseStart,
1889 EndBit-BaseOffset, Context))
1890 return false;
1891 }
1892 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001893
Chris Lattnere2962be2010-07-29 07:30:00 +00001894 // Verify that no field has data that overlaps the region of interest. Yes
1895 // this could be sped up a lot by being smarter about queried fields,
1896 // however we're only looking at structs up to 16 bytes, so we don't care
1897 // much.
1898 unsigned idx = 0;
1899 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1900 i != e; ++i, ++idx) {
1901 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001902
Chris Lattnere2962be2010-07-29 07:30:00 +00001903 // If we found a field after the region we care about, then we're done.
1904 if (FieldOffset >= EndBit) break;
1905
1906 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1907 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1908 Context))
1909 return false;
1910 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001911
Chris Lattnere2962be2010-07-29 07:30:00 +00001912 // If nothing in this record overlapped the area of interest, then we're
1913 // clean.
1914 return true;
1915 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001916
Chris Lattnere2962be2010-07-29 07:30:00 +00001917 return false;
1918}
1919
Chris Lattner0b362002010-07-29 18:39:32 +00001920/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1921/// float member at the specified offset. For example, {int,{float}} has a
1922/// float at offset 4. It is conservatively correct for this routine to return
1923/// false.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001924static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmow25a6a842012-10-08 16:25:52 +00001925 const llvm::DataLayout &TD) {
Chris Lattner0b362002010-07-29 18:39:32 +00001926 // Base case if we find a float.
1927 if (IROffset == 0 && IRType->isFloatTy())
1928 return true;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001929
Chris Lattner0b362002010-07-29 18:39:32 +00001930 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001931 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner0b362002010-07-29 18:39:32 +00001932 const llvm::StructLayout *SL = TD.getStructLayout(STy);
1933 unsigned Elt = SL->getElementContainingOffset(IROffset);
1934 IROffset -= SL->getElementOffset(Elt);
1935 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1936 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001937
Chris Lattner0b362002010-07-29 18:39:32 +00001938 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001939 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1940 llvm::Type *EltTy = ATy->getElementType();
Chris Lattner0b362002010-07-29 18:39:32 +00001941 unsigned EltSize = TD.getTypeAllocSize(EltTy);
1942 IROffset -= IROffset/EltSize*EltSize;
1943 return ContainsFloatAtOffset(EltTy, IROffset, TD);
1944 }
1945
1946 return false;
1947}
1948
Chris Lattnerf47c9442010-07-29 18:13:09 +00001949
1950/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1951/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001952llvm::Type *X86_64ABIInfo::
1953GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattnerf47c9442010-07-29 18:13:09 +00001954 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnercba8d312010-07-29 18:19:50 +00001955 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattnerf47c9442010-07-29 18:13:09 +00001956 // pass as float if the last 4 bytes is just padding. This happens for
1957 // structs that contain 3 floats.
1958 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1959 SourceOffset*8+64, getContext()))
1960 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001961
Chris Lattner0b362002010-07-29 18:39:32 +00001962 // We want to pass as <2 x float> if the LLVM IR type contains a float at
1963 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
1964 // case.
Micah Villmow25a6a842012-10-08 16:25:52 +00001965 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
1966 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner22fd4ba2010-08-25 23:39:14 +00001967 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001968
Chris Lattnerf47c9442010-07-29 18:13:09 +00001969 return llvm::Type::getDoubleTy(getVMContext());
1970}
1971
1972
Chris Lattner0d2656d2010-07-29 17:40:35 +00001973/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1974/// an 8-byte GPR. This means that we either have a scalar or we are talking
1975/// about the high or low part of an up-to-16-byte struct. This routine picks
1976/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattner49382de2010-07-28 22:44:07 +00001977/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1978/// etc).
1979///
1980/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1981/// the source type. IROffset is an offset in bytes into the LLVM IR type that
1982/// the 8-byte value references. PrefType may be null.
1983///
1984/// SourceTy is the source level type for the entire argument. SourceOffset is
1985/// an offset into this that we're processing (which is always either 0 or 8).
1986///
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001987llvm::Type *X86_64ABIInfo::
1988GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner0d2656d2010-07-29 17:40:35 +00001989 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnere2962be2010-07-29 07:30:00 +00001990 // If we're dealing with an un-offset LLVM IR type, then it means that we're
1991 // returning an 8-byte unit starting with it. See if we can safely use it.
1992 if (IROffset == 0) {
1993 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffbabaf312012-10-11 15:52:22 +00001994 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
1995 IRType->isIntegerTy(64))
Chris Lattnere2962be2010-07-29 07:30:00 +00001996 return IRType;
Chris Lattner49382de2010-07-28 22:44:07 +00001997
Chris Lattnere2962be2010-07-29 07:30:00 +00001998 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1999 // goodness in the source type is just tail padding. This is allowed to
2000 // kick in for struct {double,int} on the int, but not on
2001 // struct{double,int,int} because we wouldn't return the second int. We
2002 // have to do this analysis on the source type because we can't depend on
2003 // unions being lowered a specific way etc.
2004 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffbabaf312012-10-11 15:52:22 +00002005 IRType->isIntegerTy(32) ||
2006 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2007 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2008 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002009
Chris Lattnere2962be2010-07-29 07:30:00 +00002010 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2011 SourceOffset*8+64, getContext()))
2012 return IRType;
2013 }
2014 }
Chris Lattner49382de2010-07-28 22:44:07 +00002015
Chris Lattner2acc6e32011-07-18 04:24:23 +00002016 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner49382de2010-07-28 22:44:07 +00002017 // If this is a struct, recurse into the field at the specified offset.
Micah Villmow25a6a842012-10-08 16:25:52 +00002018 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattner49382de2010-07-28 22:44:07 +00002019 if (IROffset < SL->getSizeInBytes()) {
2020 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2021 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002022
Chris Lattner0d2656d2010-07-29 17:40:35 +00002023 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2024 SourceTy, SourceOffset);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002025 }
Chris Lattner49382de2010-07-28 22:44:07 +00002026 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002027
Chris Lattner2acc6e32011-07-18 04:24:23 +00002028 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002029 llvm::Type *EltTy = ATy->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00002030 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner021c3a32010-07-29 07:43:55 +00002031 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner0d2656d2010-07-29 17:40:35 +00002032 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2033 SourceOffset);
Chris Lattner021c3a32010-07-29 07:43:55 +00002034 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002035
Chris Lattner49382de2010-07-28 22:44:07 +00002036 // Okay, we don't have any better idea of what to pass, so we pass this in an
2037 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002038 unsigned TySizeInBytes =
2039 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattner49382de2010-07-28 22:44:07 +00002040
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002041 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002042
Chris Lattner49382de2010-07-28 22:44:07 +00002043 // It is always safe to classify this as an integer type up to i64 that
2044 // isn't larger than the structure.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002045 return llvm::IntegerType::get(getVMContext(),
2046 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner9c254f02010-06-29 06:01:59 +00002047}
2048
Chris Lattner66e7b682010-09-01 00:50:20 +00002049
2050/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2051/// be used as elements of a two register pair to pass or return, return a
2052/// first class aggregate to represent them. For example, if the low part of
2053/// a by-value argument should be passed as i32* and the high part as float,
2054/// return {i32*, float}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002055static llvm::Type *
Jay Foadef6de3d2011-07-11 09:56:20 +00002056GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmow25a6a842012-10-08 16:25:52 +00002057 const llvm::DataLayout &TD) {
Chris Lattner66e7b682010-09-01 00:50:20 +00002058 // In order to correctly satisfy the ABI, we need to the high part to start
2059 // at offset 8. If the high and low parts we inferred are both 4-byte types
2060 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2061 // the second element at offset 8. Check for this:
2062 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2063 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmow25a6a842012-10-08 16:25:52 +00002064 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattner66e7b682010-09-01 00:50:20 +00002065 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002066
Chris Lattner66e7b682010-09-01 00:50:20 +00002067 // To handle this, we have to increase the size of the low part so that the
2068 // second element will start at an 8 byte offset. We can't increase the size
2069 // of the second element because it might make us access off the end of the
2070 // struct.
2071 if (HiStart != 8) {
2072 // There are only two sorts of types the ABI generation code can produce for
2073 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2074 // Promote these to a larger type.
2075 if (Lo->isFloatTy())
2076 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2077 else {
2078 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2079 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2080 }
2081 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002082
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002083 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002084
2085
Chris Lattner66e7b682010-09-01 00:50:20 +00002086 // Verify that the second element is at an 8-byte offset.
2087 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2088 "Invalid x86-64 argument pair!");
2089 return Result;
2090}
2091
Chris Lattner519f68c2010-07-28 23:06:14 +00002092ABIArgInfo X86_64ABIInfo::
Chris Lattnera3c109b2010-07-29 02:16:43 +00002093classifyReturnType(QualType RetTy) const {
Chris Lattner519f68c2010-07-28 23:06:14 +00002094 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2095 // classification algorithm.
2096 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002097 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner519f68c2010-07-28 23:06:14 +00002098
2099 // Check some invariants.
2100 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002101 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2102
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002103 llvm::Type *ResType = 0;
Chris Lattner519f68c2010-07-28 23:06:14 +00002104 switch (Lo) {
2105 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002106 if (Hi == NoClass)
2107 return ABIArgInfo::getIgnore();
2108 // If the low part is just padding, it takes no register, leave ResType
2109 // null.
2110 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2111 "Unknown missing lo part");
2112 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002113
2114 case SSEUp:
2115 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002116 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002117
2118 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2119 // hidden argument.
2120 case Memory:
2121 return getIndirectReturnResult(RetTy);
2122
2123 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2124 // available register of the sequence %rax, %rdx is used.
2125 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002126 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002127
Chris Lattnereb518b42010-07-29 21:42:50 +00002128 // If we have a sign or zero extended integer, make sure to return Extend
2129 // so that the parameter gets the right LLVM IR attributes.
2130 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2131 // Treat an enum type as its underlying type.
2132 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2133 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002134
Chris Lattnereb518b42010-07-29 21:42:50 +00002135 if (RetTy->isIntegralOrEnumerationType() &&
2136 RetTy->isPromotableIntegerType())
2137 return ABIArgInfo::getExtend();
2138 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002139 break;
2140
2141 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2142 // available SSE register of the sequence %xmm0, %xmm1 is used.
2143 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002144 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattner0b30c672010-07-28 23:12:33 +00002145 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002146
2147 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2148 // returned on the X87 stack in %st0 as 80-bit x87 number.
2149 case X87:
Chris Lattnerea044322010-07-29 02:01:43 +00002150 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattner0b30c672010-07-28 23:12:33 +00002151 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002152
2153 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2154 // part of the value is returned in %st0 and the imaginary part in
2155 // %st1.
2156 case ComplexX87:
2157 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner7650d952011-06-18 22:49:11 +00002158 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattnerea044322010-07-29 02:01:43 +00002159 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner519f68c2010-07-28 23:06:14 +00002160 NULL);
2161 break;
2162 }
2163
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002164 llvm::Type *HighPart = 0;
Chris Lattner519f68c2010-07-28 23:06:14 +00002165 switch (Hi) {
2166 // Memory was handled previously and X87 should
2167 // never occur as a hi class.
2168 case Memory:
2169 case X87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002170 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002171
2172 case ComplexX87: // Previously handled.
Chris Lattner0b30c672010-07-28 23:12:33 +00002173 case NoClass:
2174 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002175
Chris Lattner3db4dde2010-09-01 00:20:33 +00002176 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002177 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002178 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2179 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002180 break;
Chris Lattner3db4dde2010-09-01 00:20:33 +00002181 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002182 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002183 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2184 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002185 break;
2186
2187 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002188 // is passed in the next available eightbyte chunk if the last used
2189 // vector register.
Chris Lattner519f68c2010-07-28 23:06:14 +00002190 //
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002191 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner519f68c2010-07-28 23:06:14 +00002192 case SSEUp:
2193 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002194 ResType = GetByteVectorType(RetTy);
Chris Lattner519f68c2010-07-28 23:06:14 +00002195 break;
2196
2197 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2198 // returned together with the previous X87 value in %st0.
2199 case X87Up:
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002200 // If X87Up is preceded by X87, we don't need to do
Chris Lattner519f68c2010-07-28 23:06:14 +00002201 // anything. However, in some cases with unions it may not be
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002202 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner519f68c2010-07-28 23:06:14 +00002203 // extra bits in an SSE reg.
Chris Lattner603519d2010-07-29 17:49:08 +00002204 if (Lo != X87) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002205 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002206 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2207 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner603519d2010-07-29 17:49:08 +00002208 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002209 break;
2210 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002211
Chris Lattner3db4dde2010-09-01 00:20:33 +00002212 // If a high part was specified, merge it together with the low part. It is
Chris Lattner645406a2010-09-01 00:24:35 +00002213 // known to pass in the high eightbyte of the result. We do this by forming a
2214 // first class struct aggregate with the high and low part: {low, high}
Chris Lattner66e7b682010-09-01 00:50:20 +00002215 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002216 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner519f68c2010-07-28 23:06:14 +00002217
Chris Lattnereb518b42010-07-29 21:42:50 +00002218 return ABIArgInfo::getDirect(ResType);
Chris Lattner519f68c2010-07-28 23:06:14 +00002219}
2220
Daniel Dunbaredfac032012-03-10 01:03:58 +00002221ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman7a1b5862013-06-12 00:13:45 +00002222 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2223 bool isNamedArg)
Daniel Dunbaredfac032012-03-10 01:03:58 +00002224 const
2225{
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002226 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002227 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002228
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002229 // Check some invariants.
2230 // FIXME: Enforce these by construction.
2231 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002232 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2233
2234 neededInt = 0;
2235 neededSSE = 0;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002236 llvm::Type *ResType = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002237 switch (Lo) {
2238 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002239 if (Hi == NoClass)
2240 return ABIArgInfo::getIgnore();
2241 // If the low part is just padding, it takes no register, leave ResType
2242 // null.
2243 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2244 "Unknown missing lo part");
2245 break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002246
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002247 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2248 // on the stack.
2249 case Memory:
2250
2251 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2252 // COMPLEX_X87, it is passed in memory.
2253 case X87:
2254 case ComplexX87:
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002255 if (getRecordArgABI(Ty, CGT) == CGCXXABI::RAA_Indirect)
Eli Friedmanded137f2011-06-29 07:04:55 +00002256 ++neededInt;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002257 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002258
2259 case SSEUp:
2260 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002261 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002262
2263 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2264 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2265 // and %r9 is used.
2266 case Integer:
Chris Lattner9c254f02010-06-29 06:01:59 +00002267 ++neededInt;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002268
Chris Lattner49382de2010-07-28 22:44:07 +00002269 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002270 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattnereb518b42010-07-29 21:42:50 +00002271
2272 // If we have a sign or zero extended integer, make sure to return Extend
2273 // so that the parameter gets the right LLVM IR attributes.
2274 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2275 // Treat an enum type as its underlying type.
2276 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2277 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002278
Chris Lattnereb518b42010-07-29 21:42:50 +00002279 if (Ty->isIntegralOrEnumerationType() &&
2280 Ty->isPromotableIntegerType())
2281 return ABIArgInfo::getExtend();
2282 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002283
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002284 break;
2285
2286 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2287 // available SSE register is used, the registers are taken in the
2288 // order from %xmm0 to %xmm7.
Bill Wendlingbb465d72010-10-18 03:41:31 +00002289 case SSE: {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002290 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman14508ff2011-07-02 00:57:27 +00002291 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling99aaae82010-10-18 23:51:38 +00002292 ++neededSSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002293 break;
2294 }
Bill Wendlingbb465d72010-10-18 03:41:31 +00002295 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002296
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002297 llvm::Type *HighPart = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002298 switch (Hi) {
2299 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002300 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002301 // which is passed in memory.
2302 case Memory:
2303 case X87:
2304 case ComplexX87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002305 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002306
2307 case NoClass: break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002308
Chris Lattner645406a2010-09-01 00:24:35 +00002309 case Integer:
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002310 ++neededInt;
Chris Lattner49382de2010-07-28 22:44:07 +00002311 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002312 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002313
Chris Lattner645406a2010-09-01 00:24:35 +00002314 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2315 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002316 break;
2317
2318 // X87Up generally doesn't occur here (long double is passed in
2319 // memory), except in situations involving unions.
2320 case X87Up:
Chris Lattner645406a2010-09-01 00:24:35 +00002321 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002322 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002323
Chris Lattner645406a2010-09-01 00:24:35 +00002324 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2325 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner117e3f42010-07-30 04:02:24 +00002326
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002327 ++neededSSE;
2328 break;
2329
2330 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2331 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002332 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002333 case SSEUp:
Chris Lattnerab5722e2010-07-28 23:47:21 +00002334 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002335 ResType = GetByteVectorType(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002336 break;
2337 }
2338
Chris Lattner645406a2010-09-01 00:24:35 +00002339 // If a high part was specified, merge it together with the low part. It is
2340 // known to pass in the high eightbyte of the result. We do this by forming a
2341 // first class struct aggregate with the high and low part: {low, high}
2342 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002343 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002344
Chris Lattnereb518b42010-07-29 21:42:50 +00002345 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002346}
2347
Chris Lattneree5dcd02010-07-29 02:31:05 +00002348void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002349
Chris Lattnera3c109b2010-07-29 02:16:43 +00002350 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002351
2352 // Keep track of the number of assigned registers.
Bill Wendling99aaae82010-10-18 23:51:38 +00002353 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002354
2355 // If the return value is indirect, then the hidden argument is consuming one
2356 // integer register.
2357 if (FI.getReturnInfo().isIndirect())
2358 --freeIntRegs;
2359
Eli Friedman7a1b5862013-06-12 00:13:45 +00002360 bool isVariadic = FI.isVariadic();
2361 unsigned numRequiredArgs = 0;
2362 if (isVariadic)
2363 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2364
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002365 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2366 // get assigned (in left-to-right order) for passing as follows...
2367 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2368 it != ie; ++it) {
Eli Friedman7a1b5862013-06-12 00:13:45 +00002369 bool isNamedArg = true;
2370 if (isVariadic)
Aaron Ballmaneba7d2f2013-06-12 15:03:45 +00002371 isNamedArg = (it - FI.arg_begin()) <
2372 static_cast<signed>(numRequiredArgs);
Eli Friedman7a1b5862013-06-12 00:13:45 +00002373
Bill Wendling99aaae82010-10-18 23:51:38 +00002374 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002375 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman7a1b5862013-06-12 00:13:45 +00002376 neededSSE, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002377
2378 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2379 // eightbyte of an argument, the whole argument is passed on the
2380 // stack. If registers have already been assigned for some
2381 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling99aaae82010-10-18 23:51:38 +00002382 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002383 freeIntRegs -= neededInt;
2384 freeSSERegs -= neededSSE;
2385 } else {
Daniel Dunbaredfac032012-03-10 01:03:58 +00002386 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002387 }
2388 }
2389}
2390
2391static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2392 QualType Ty,
2393 CodeGenFunction &CGF) {
2394 llvm::Value *overflow_arg_area_p =
2395 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2396 llvm::Value *overflow_arg_area =
2397 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2398
2399 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2400 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedman8d2fe422011-11-18 02:44:19 +00002401 // It isn't stated explicitly in the standard, but in practice we use
2402 // alignment greater than 16 where necessary.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002403 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2404 if (Align > 8) {
Eli Friedman8d2fe422011-11-18 02:44:19 +00002405 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson0032b272009-08-13 21:57:51 +00002406 llvm::Value *Offset =
Eli Friedman8d2fe422011-11-18 02:44:19 +00002407 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002408 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2409 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner77b89b82010-06-27 07:15:29 +00002410 CGF.Int64Ty);
Eli Friedman8d2fe422011-11-18 02:44:19 +00002411 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002412 overflow_arg_area =
2413 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2414 overflow_arg_area->getType(),
2415 "overflow_arg_area.align");
2416 }
2417
2418 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002419 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002420 llvm::Value *Res =
2421 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002422 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002423
2424 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2425 // l->overflow_arg_area + sizeof(type).
2426 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2427 // an 8 byte boundary.
2428
2429 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson0032b272009-08-13 21:57:51 +00002430 llvm::Value *Offset =
Chris Lattner77b89b82010-06-27 07:15:29 +00002431 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002432 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2433 "overflow_arg_area.next");
2434 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2435
2436 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2437 return Res;
2438}
2439
2440llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2441 CodeGenFunction &CGF) const {
2442 // Assume that va_list type is correct; should be pointer to LLVM type:
2443 // struct {
2444 // i32 gp_offset;
2445 // i32 fp_offset;
2446 // i8* overflow_arg_area;
2447 // i8* reg_save_area;
2448 // };
Bill Wendling99aaae82010-10-18 23:51:38 +00002449 unsigned neededInt, neededSSE;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002450
Chris Lattnera14db752010-03-11 18:19:55 +00002451 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman7a1b5862013-06-12 00:13:45 +00002452 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2453 /*isNamedArg*/false);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002454
2455 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2456 // in the registers. If not go to step 7.
2457 if (!neededInt && !neededSSE)
2458 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2459
2460 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2461 // general purpose registers needed to pass type and num_fp to hold
2462 // the number of floating point registers needed.
2463
2464 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2465 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2466 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2467 //
2468 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2469 // register save space).
2470
2471 llvm::Value *InRegs = 0;
2472 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2473 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2474 if (neededInt) {
2475 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2476 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattner1090a9b2010-06-28 21:43:59 +00002477 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2478 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002479 }
2480
2481 if (neededSSE) {
2482 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2483 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2484 llvm::Value *FitsInFP =
Chris Lattner1090a9b2010-06-28 21:43:59 +00002485 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2486 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002487 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2488 }
2489
2490 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2491 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2492 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2493 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2494
2495 // Emit code to load the value if it was passed in registers.
2496
2497 CGF.EmitBlock(InRegBlock);
2498
2499 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2500 // an offset of l->gp_offset and/or l->fp_offset. This may require
2501 // copying to a temporary location in case the parameter is passed
2502 // in different register classes or requires an alignment greater
2503 // than 8 for general purpose registers and 16 for XMM registers.
2504 //
2505 // FIXME: This really results in shameful code when we end up needing to
2506 // collect arguments from different places; often what should result in a
2507 // simple assembling of a structure from scattered addresses has many more
2508 // loads than necessary. Can we clean this up?
Chris Lattner2acc6e32011-07-18 04:24:23 +00002509 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002510 llvm::Value *RegAddr =
2511 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2512 "reg_save_area");
2513 if (neededInt && neededSSE) {
2514 // FIXME: Cleanup.
Chris Lattner800588f2010-07-29 06:26:06 +00002515 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002516 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmaneeb00622013-06-07 23:20:55 +00002517 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2518 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002519 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002520 llvm::Type *TyLo = ST->getElementType(0);
2521 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattnera8b7a7d2010-08-26 06:28:35 +00002522 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002523 "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002524 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2525 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002526 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2527 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002528 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2529 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002530 llvm::Value *V =
2531 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2532 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2533 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2534 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2535
Owen Andersona1cf15f2009-07-14 23:10:40 +00002536 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002537 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002538 } else if (neededInt) {
2539 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2540 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002541 llvm::PointerType::getUnqual(LTy));
Eli Friedmaneeb00622013-06-07 23:20:55 +00002542
2543 // Copy to a temporary if necessary to ensure the appropriate alignment.
2544 std::pair<CharUnits, CharUnits> SizeAlign =
2545 CGF.getContext().getTypeInfoInChars(Ty);
2546 uint64_t TySize = SizeAlign.first.getQuantity();
2547 unsigned TyAlign = SizeAlign.second.getQuantity();
2548 if (TyAlign > 8) {
Eli Friedmaneeb00622013-06-07 23:20:55 +00002549 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2550 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2551 RegAddr = Tmp;
2552 }
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002553 } else if (neededSSE == 1) {
2554 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2555 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2556 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002557 } else {
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002558 assert(neededSSE == 2 && "Invalid number of needed registers!");
2559 // SSE registers are spaced 16 bytes apart in the register save
2560 // area, we need to collect the two eightbytes together.
2561 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattner1090a9b2010-06-28 21:43:59 +00002562 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattner8b418682012-02-07 00:39:47 +00002563 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002564 llvm::Type *DblPtrTy =
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002565 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmaneeb00622013-06-07 23:20:55 +00002566 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2567 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2568 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002569 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2570 DblPtrTy));
2571 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2572 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2573 DblPtrTy));
2574 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2575 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2576 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002577 }
2578
2579 // AMD64-ABI 3.5.7p5: Step 5. Set:
2580 // l->gp_offset = l->gp_offset + num_gp * 8
2581 // l->fp_offset = l->fp_offset + num_fp * 16.
2582 if (neededInt) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002583 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002584 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2585 gp_offset_p);
2586 }
2587 if (neededSSE) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002588 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002589 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2590 fp_offset_p);
2591 }
2592 CGF.EmitBranch(ContBlock);
2593
2594 // Emit code to load the value if it was passed in memory.
2595
2596 CGF.EmitBlock(InMemBlock);
2597 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2598
2599 // Return the appropriate result.
2600
2601 CGF.EmitBlock(ContBlock);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002602 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002603 "vaarg.addr");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002604 ResAddr->addIncoming(RegAddr, InRegBlock);
2605 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002606 return ResAddr;
2607}
2608
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002609ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002610
2611 if (Ty->isVoidType())
2612 return ABIArgInfo::getIgnore();
2613
2614 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2615 Ty = EnumTy->getDecl()->getIntegerType();
2616
2617 uint64_t Size = getContext().getTypeSize(Ty);
2618
2619 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002620 if (IsReturnType) {
2621 if (isRecordReturnIndirect(RT, CGT))
2622 return ABIArgInfo::getIndirect(0, false);
2623 } else {
2624 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, CGT))
2625 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2626 }
2627
2628 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002629 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2630
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002631 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCall64aa4b32013-04-16 22:48:15 +00002632 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002633 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2634 Size));
2635
2636 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2637 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2638 if (Size <= 64 &&
NAKAMURA Takumiff8be0e2011-01-19 00:11:33 +00002639 (Size & (Size - 1)) == 0)
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002640 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2641 Size));
2642
2643 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2644 }
2645
2646 if (Ty->isPromotableIntegerType())
2647 return ABIArgInfo::getExtend();
2648
2649 return ABIArgInfo::getDirect();
2650}
2651
2652void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2653
2654 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002655 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002656
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002657 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2658 it != ie; ++it)
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002659 it->info = classify(it->type, false);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002660}
2661
Chris Lattnerf13721d2010-08-31 16:44:54 +00002662llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2663 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00002664 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002665
Chris Lattnerf13721d2010-08-31 16:44:54 +00002666 CGBuilderTy &Builder = CGF.Builder;
2667 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2668 "ap");
2669 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2670 llvm::Type *PTy =
2671 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2672 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2673
2674 uint64_t Offset =
2675 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2676 llvm::Value *NextAddr =
2677 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2678 "ap.next");
2679 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2680
2681 return AddrTyped;
2682}
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002683
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00002684namespace {
2685
Derek Schuff263366f2012-10-16 22:30:41 +00002686class NaClX86_64ABIInfo : public ABIInfo {
2687 public:
2688 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2689 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2690 virtual void computeInfo(CGFunctionInfo &FI) const;
2691 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2692 CodeGenFunction &CGF) const;
2693 private:
2694 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2695 X86_64ABIInfo NInfo; // Used for everything else.
2696};
2697
2698class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2699 public:
2700 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2701 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2702};
2703
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00002704}
2705
Derek Schuff263366f2012-10-16 22:30:41 +00002706void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2707 if (FI.getASTCallingConvention() == CC_PnaclCall)
2708 PInfo.computeInfo(FI);
2709 else
2710 NInfo.computeInfo(FI);
2711}
2712
2713llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2714 CodeGenFunction &CGF) const {
2715 // Always use the native convention; calling pnacl-style varargs functions
2716 // is unuspported.
2717 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2718}
2719
2720
John McCallec853ba2010-03-11 00:10:12 +00002721// PowerPC-32
2722
2723namespace {
2724class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2725public:
Chris Lattnerea044322010-07-29 02:01:43 +00002726 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002727
John McCallec853ba2010-03-11 00:10:12 +00002728 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2729 // This is recovered from gcc output.
2730 return 1; // r1 is the dedicated stack pointer
2731 }
2732
2733 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002734 llvm::Value *Address) const;
John McCallec853ba2010-03-11 00:10:12 +00002735};
2736
2737}
2738
2739bool
2740PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2741 llvm::Value *Address) const {
2742 // This is calculated from the LLVM and GCC tables and verified
2743 // against gcc output. AFAIK all ABIs use the same encoding.
2744
2745 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallec853ba2010-03-11 00:10:12 +00002746
Chris Lattner8b418682012-02-07 00:39:47 +00002747 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallec853ba2010-03-11 00:10:12 +00002748 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2749 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2750 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2751
2752 // 0-31: r0-31, the 4-byte general-purpose registers
John McCallaeeb7012010-05-27 06:19:26 +00002753 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallec853ba2010-03-11 00:10:12 +00002754
2755 // 32-63: fp0-31, the 8-byte floating-point registers
John McCallaeeb7012010-05-27 06:19:26 +00002756 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallec853ba2010-03-11 00:10:12 +00002757
2758 // 64-76 are various 4-byte special-purpose registers:
2759 // 64: mq
2760 // 65: lr
2761 // 66: ctr
2762 // 67: ap
2763 // 68-75 cr0-7
2764 // 76: xer
John McCallaeeb7012010-05-27 06:19:26 +00002765 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallec853ba2010-03-11 00:10:12 +00002766
2767 // 77-108: v0-31, the 16-byte vector registers
John McCallaeeb7012010-05-27 06:19:26 +00002768 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallec853ba2010-03-11 00:10:12 +00002769
2770 // 109: vrsave
2771 // 110: vscr
2772 // 111: spe_acc
2773 // 112: spefscr
2774 // 113: sfp
John McCallaeeb7012010-05-27 06:19:26 +00002775 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallec853ba2010-03-11 00:10:12 +00002776
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002777 return false;
John McCallec853ba2010-03-11 00:10:12 +00002778}
2779
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002780// PowerPC-64
2781
2782namespace {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002783/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2784class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2785
2786public:
2787 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2788
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002789 bool isPromotableTypeForABI(QualType Ty) const;
2790
2791 ABIArgInfo classifyReturnType(QualType RetTy) const;
2792 ABIArgInfo classifyArgumentType(QualType Ty) const;
2793
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002794 // TODO: We can add more logic to computeInfo to improve performance.
2795 // Example: For aggregate arguments that fit in a register, we could
2796 // use getDirectInReg (as is done below for structs containing a single
2797 // floating-point value) to avoid pushing them to memory on function
2798 // entry. This would require changing the logic in PPCISelLowering
2799 // when lowering the parameters in the caller and args in the callee.
2800 virtual void computeInfo(CGFunctionInfo &FI) const {
2801 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2802 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2803 it != ie; ++it) {
2804 // We rely on the default argument classification for the most part.
2805 // One exception: An aggregate containing a single floating-point
2806 // item must be passed in a register if one is available.
2807 const Type *T = isSingleElementStruct(it->type, getContext());
2808 if (T) {
2809 const BuiltinType *BT = T->getAs<BuiltinType>();
2810 if (BT && BT->isFloatingPoint()) {
2811 QualType QT(T, 0);
2812 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2813 continue;
2814 }
2815 }
2816 it->info = classifyArgumentType(it->type);
2817 }
2818 }
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002819
2820 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2821 QualType Ty,
2822 CodeGenFunction &CGF) const;
2823};
2824
2825class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2826public:
2827 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2828 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2829
2830 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2831 // This is recovered from gcc output.
2832 return 1; // r1 is the dedicated stack pointer
2833 }
2834
2835 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2836 llvm::Value *Address) const;
2837};
2838
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002839class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2840public:
2841 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2842
2843 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2844 // This is recovered from gcc output.
2845 return 1; // r1 is the dedicated stack pointer
2846 }
2847
2848 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2849 llvm::Value *Address) const;
2850};
2851
2852}
2853
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002854// Return true if the ABI requires Ty to be passed sign- or zero-
2855// extended to 64 bits.
2856bool
2857PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2858 // Treat an enum type as its underlying type.
2859 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2860 Ty = EnumTy->getDecl()->getIntegerType();
2861
2862 // Promotable integer types are required to be promoted by the ABI.
2863 if (Ty->isPromotableIntegerType())
2864 return true;
2865
2866 // In addition to the usual promotable integer types, we also need to
2867 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2868 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2869 switch (BT->getKind()) {
2870 case BuiltinType::Int:
2871 case BuiltinType::UInt:
2872 return true;
2873 default:
2874 break;
2875 }
2876
2877 return false;
2878}
2879
2880ABIArgInfo
2881PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidtc9715fc2012-11-27 02:46:43 +00002882 if (Ty->isAnyComplexType())
2883 return ABIArgInfo::getDirect();
2884
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002885 if (isAggregateTypeForABI(Ty)) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002886 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
2887 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002888
2889 return ABIArgInfo::getIndirect(0);
2890 }
2891
2892 return (isPromotableTypeForABI(Ty) ?
2893 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2894}
2895
2896ABIArgInfo
2897PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
2898 if (RetTy->isVoidType())
2899 return ABIArgInfo::getIgnore();
2900
Bill Schmidt9e6111a2012-12-17 04:20:17 +00002901 if (RetTy->isAnyComplexType())
2902 return ABIArgInfo::getDirect();
2903
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002904 if (isAggregateTypeForABI(RetTy))
2905 return ABIArgInfo::getIndirect(0);
2906
2907 return (isPromotableTypeForABI(RetTy) ?
2908 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2909}
2910
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002911// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
2912llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2913 QualType Ty,
2914 CodeGenFunction &CGF) const {
2915 llvm::Type *BP = CGF.Int8PtrTy;
2916 llvm::Type *BPP = CGF.Int8PtrPtrTy;
2917
2918 CGBuilderTy &Builder = CGF.Builder;
2919 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2920 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2921
Bill Schmidt19f8e852013-01-14 17:45:36 +00002922 // Update the va_list pointer. The pointer should be bumped by the
2923 // size of the object. We can trust getTypeSize() except for a complex
2924 // type whose base type is smaller than a doubleword. For these, the
2925 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002926 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt19f8e852013-01-14 17:45:36 +00002927 QualType BaseTy;
2928 unsigned CplxBaseSize = 0;
2929
2930 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
2931 BaseTy = CTy->getElementType();
2932 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
2933 if (CplxBaseSize < 8)
2934 SizeInBytes = 16;
2935 }
2936
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002937 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
2938 llvm::Value *NextAddr =
2939 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
2940 "ap.next");
2941 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2942
Bill Schmidt19f8e852013-01-14 17:45:36 +00002943 // If we have a complex type and the base type is smaller than 8 bytes,
2944 // the ABI calls for the real and imaginary parts to be right-adjusted
2945 // in separate doublewords. However, Clang expects us to produce a
2946 // pointer to a structure with the two parts packed tightly. So generate
2947 // loads of the real and imaginary parts relative to the va_list pointer,
2948 // and store them to a temporary structure.
2949 if (CplxBaseSize && CplxBaseSize < 8) {
2950 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2951 llvm::Value *ImagAddr = RealAddr;
2952 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
2953 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
2954 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
2955 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
2956 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
2957 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
2958 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
2959 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
2960 "vacplx");
2961 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
2962 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
2963 Builder.CreateStore(Real, RealPtr, false);
2964 Builder.CreateStore(Imag, ImagPtr, false);
2965 return Ptr;
2966 }
2967
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002968 // If the argument is smaller than 8 bytes, it is right-adjusted in
2969 // its doubleword slot. Adjust the pointer to pick it up from the
2970 // correct offset.
2971 if (SizeInBytes < 8) {
2972 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2973 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
2974 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2975 }
2976
2977 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2978 return Builder.CreateBitCast(Addr, PTy);
2979}
2980
2981static bool
2982PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2983 llvm::Value *Address) {
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002984 // This is calculated from the LLVM and GCC tables and verified
2985 // against gcc output. AFAIK all ABIs use the same encoding.
2986
2987 CodeGen::CGBuilderTy &Builder = CGF.Builder;
2988
2989 llvm::IntegerType *i8 = CGF.Int8Ty;
2990 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2991 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2992 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2993
2994 // 0-31: r0-31, the 8-byte general-purpose registers
2995 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
2996
2997 // 32-63: fp0-31, the 8-byte floating-point registers
2998 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2999
3000 // 64-76 are various 4-byte special-purpose registers:
3001 // 64: mq
3002 // 65: lr
3003 // 66: ctr
3004 // 67: ap
3005 // 68-75 cr0-7
3006 // 76: xer
3007 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3008
3009 // 77-108: v0-31, the 16-byte vector registers
3010 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3011
3012 // 109: vrsave
3013 // 110: vscr
3014 // 111: spe_acc
3015 // 112: spefscr
3016 // 113: sfp
3017 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3018
3019 return false;
3020}
John McCallec853ba2010-03-11 00:10:12 +00003021
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003022bool
3023PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3024 CodeGen::CodeGenFunction &CGF,
3025 llvm::Value *Address) const {
3026
3027 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3028}
3029
3030bool
3031PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3032 llvm::Value *Address) const {
3033
3034 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3035}
3036
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003037//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003038// ARM ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003039//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003040
3041namespace {
3042
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003043class ARMABIInfo : public ABIInfo {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003044public:
3045 enum ABIKind {
3046 APCS = 0,
3047 AAPCS = 1,
3048 AAPCS_VFP
3049 };
3050
3051private:
3052 ABIKind Kind;
3053
3054public:
John McCallbd7370a2013-02-28 19:01:20 +00003055 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
3056 setRuntimeCC();
3057 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003058
John McCall49e34be2011-08-30 01:42:09 +00003059 bool isEABI() const {
John McCall64aa4b32013-04-16 22:48:15 +00003060 StringRef Env = getTarget().getTriple().getEnvironmentName();
Logan Chien94a71422012-09-02 09:30:11 +00003061 return (Env == "gnueabi" || Env == "eabi" ||
3062 Env == "android" || Env == "androideabi");
John McCall49e34be2011-08-30 01:42:09 +00003063 }
3064
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003065private:
3066 ABIKind getABIKind() const { return Kind; }
3067
Chris Lattnera3c109b2010-07-29 02:16:43 +00003068 ABIArgInfo classifyReturnType(QualType RetTy) const;
Manman Ren710c5172012-10-31 19:02:26 +00003069 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs,
3070 unsigned &AllocatedVFP,
Manman Renb3fa55f2012-10-30 23:21:41 +00003071 bool &IsHA) const;
Manman Ren97f81572012-10-16 19:18:39 +00003072 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003073
Chris Lattneree5dcd02010-07-29 02:31:05 +00003074 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003075
3076 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3077 CodeGenFunction &CGF) const;
John McCallbd7370a2013-02-28 19:01:20 +00003078
3079 llvm::CallingConv::ID getLLVMDefaultCC() const;
3080 llvm::CallingConv::ID getABIDefaultCC() const;
3081 void setRuntimeCC();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003082};
3083
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00003084class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3085public:
Chris Lattnerea044322010-07-29 02:01:43 +00003086 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3087 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCall6374c332010-03-06 00:35:14 +00003088
John McCall49e34be2011-08-30 01:42:09 +00003089 const ARMABIInfo &getABIInfo() const {
3090 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3091 }
3092
John McCall6374c332010-03-06 00:35:14 +00003093 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3094 return 13;
3095 }
Roman Divacky09345d12011-05-18 19:36:54 +00003096
Chris Lattner5f9e2722011-07-23 10:55:15 +00003097 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
John McCallf85e1932011-06-15 23:02:42 +00003098 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3099 }
3100
Roman Divacky09345d12011-05-18 19:36:54 +00003101 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3102 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00003103 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divacky09345d12011-05-18 19:36:54 +00003104
3105 // 0-15 are the 16 integer registers.
Chris Lattner8b418682012-02-07 00:39:47 +00003106 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divacky09345d12011-05-18 19:36:54 +00003107 return false;
3108 }
John McCall49e34be2011-08-30 01:42:09 +00003109
3110 unsigned getSizeOfUnwindException() const {
3111 if (getABIInfo().isEABI()) return 88;
3112 return TargetCodeGenInfo::getSizeOfUnwindException();
3113 }
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00003114};
3115
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003116}
3117
Chris Lattneree5dcd02010-07-29 02:31:05 +00003118void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Renb3fa55f2012-10-30 23:21:41 +00003119 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Ren710c5172012-10-31 19:02:26 +00003120 // VFP registers allocated so far.
Manman Renb3fa55f2012-10-30 23:21:41 +00003121 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3122 // VFP registers of the appropriate type unallocated then the argument is
3123 // allocated to the lowest-numbered sequence of such registers.
3124 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3125 // unallocated are marked as unavailable.
3126 unsigned AllocatedVFP = 0;
Manman Ren710c5172012-10-31 19:02:26 +00003127 int VFPRegs[16] = { 0 };
Chris Lattnera3c109b2010-07-29 02:16:43 +00003128 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003129 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Manman Renb3fa55f2012-10-30 23:21:41 +00003130 it != ie; ++it) {
3131 unsigned PreAllocation = AllocatedVFP;
3132 bool IsHA = false;
3133 // 6.1.2.3 There is one VFP co-processor register class using registers
3134 // s0-s15 (d0-d7) for passing arguments.
3135 const unsigned NumVFPs = 16;
Manman Ren710c5172012-10-31 19:02:26 +00003136 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA);
Manman Renb3fa55f2012-10-30 23:21:41 +00003137 // If we do not have enough VFP registers for the HA, any VFP registers
3138 // that are unallocated are marked as unavailable. To achieve this, we add
3139 // padding of (NumVFPs - PreAllocation) floats.
3140 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3141 llvm::Type *PaddingTy = llvm::ArrayType::get(
3142 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3143 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3144 }
3145 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003146
Anton Korobeynikov414d8962011-04-14 20:06:49 +00003147 // Always honor user-specified calling convention.
3148 if (FI.getCallingConvention() != llvm::CallingConv::C)
3149 return;
3150
John McCallbd7370a2013-02-28 19:01:20 +00003151 llvm::CallingConv::ID cc = getRuntimeCC();
3152 if (cc != llvm::CallingConv::C)
3153 FI.setEffectiveCallingConvention(cc);
3154}
Rafael Espindola25117ab2010-06-16 16:13:39 +00003155
John McCallbd7370a2013-02-28 19:01:20 +00003156/// Return the default calling convention that LLVM will use.
3157llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3158 // The default calling convention that LLVM will infer.
John McCall64aa4b32013-04-16 22:48:15 +00003159 if (getTarget().getTriple().getEnvironmentName()=="gnueabihf")
John McCallbd7370a2013-02-28 19:01:20 +00003160 return llvm::CallingConv::ARM_AAPCS_VFP;
3161 else if (isEABI())
3162 return llvm::CallingConv::ARM_AAPCS;
3163 else
3164 return llvm::CallingConv::ARM_APCS;
3165}
3166
3167/// Return the calling convention that our ABI would like us to use
3168/// as the C calling convention.
3169llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003170 switch (getABIKind()) {
John McCallbd7370a2013-02-28 19:01:20 +00003171 case APCS: return llvm::CallingConv::ARM_APCS;
3172 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3173 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003174 }
John McCallbd7370a2013-02-28 19:01:20 +00003175 llvm_unreachable("bad ABI kind");
3176}
3177
3178void ARMABIInfo::setRuntimeCC() {
3179 assert(getRuntimeCC() == llvm::CallingConv::C);
3180
3181 // Don't muddy up the IR with a ton of explicit annotations if
3182 // they'd just match what LLVM will infer from the triple.
3183 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3184 if (abiCC != getLLVMDefaultCC())
3185 RuntimeCC = abiCC;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003186}
3187
Bob Wilson194f06a2011-08-03 05:58:22 +00003188/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3189/// aggregate. If HAMembers is non-null, the number of base elements
3190/// contained in the type is returned through it; this is used for the
3191/// recursive calls that check aggregate component types.
3192static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3193 ASTContext &Context,
3194 uint64_t *HAMembers = 0) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003195 uint64_t Members = 0;
Bob Wilson194f06a2011-08-03 05:58:22 +00003196 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3197 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3198 return false;
3199 Members *= AT->getSize().getZExtValue();
3200 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3201 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003202 if (RD->hasFlexibleArrayMember())
Bob Wilson194f06a2011-08-03 05:58:22 +00003203 return false;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003204
Bob Wilson194f06a2011-08-03 05:58:22 +00003205 Members = 0;
3206 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3207 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003208 const FieldDecl *FD = *i;
Bob Wilson194f06a2011-08-03 05:58:22 +00003209 uint64_t FldMembers;
3210 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3211 return false;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003212
3213 Members = (RD->isUnion() ?
3214 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilson194f06a2011-08-03 05:58:22 +00003215 }
3216 } else {
3217 Members = 1;
3218 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3219 Members = 2;
3220 Ty = CT->getElementType();
3221 }
3222
3223 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3224 // double, or 64-bit or 128-bit vectors.
3225 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3226 if (BT->getKind() != BuiltinType::Float &&
Tim Northoveradfa45f2012-07-20 22:29:29 +00003227 BT->getKind() != BuiltinType::Double &&
3228 BT->getKind() != BuiltinType::LongDouble)
Bob Wilson194f06a2011-08-03 05:58:22 +00003229 return false;
3230 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3231 unsigned VecSize = Context.getTypeSize(VT);
3232 if (VecSize != 64 && VecSize != 128)
3233 return false;
3234 } else {
3235 return false;
3236 }
3237
3238 // The base type must be the same for all members. Vector types of the
3239 // same total size are treated as being equivalent here.
3240 const Type *TyPtr = Ty.getTypePtr();
3241 if (!Base)
3242 Base = TyPtr;
3243 if (Base != TyPtr &&
3244 (!Base->isVectorType() || !TyPtr->isVectorType() ||
3245 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
3246 return false;
3247 }
3248
3249 // Homogeneous Aggregates can have at most 4 members of the base type.
3250 if (HAMembers)
3251 *HAMembers = Members;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003252
3253 return (Members > 0 && Members <= 4);
Bob Wilson194f06a2011-08-03 05:58:22 +00003254}
3255
Manman Ren710c5172012-10-31 19:02:26 +00003256/// markAllocatedVFPs - update VFPRegs according to the alignment and
3257/// number of VFP registers (unit is S register) requested.
3258static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP,
3259 unsigned Alignment,
3260 unsigned NumRequired) {
3261 // Early Exit.
3262 if (AllocatedVFP >= 16)
3263 return;
3264 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3265 // VFP registers of the appropriate type unallocated then the argument is
3266 // allocated to the lowest-numbered sequence of such registers.
3267 for (unsigned I = 0; I < 16; I += Alignment) {
3268 bool FoundSlot = true;
3269 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3270 if (J >= 16 || VFPRegs[J]) {
3271 FoundSlot = false;
3272 break;
3273 }
3274 if (FoundSlot) {
3275 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3276 VFPRegs[J] = 1;
3277 AllocatedVFP += NumRequired;
3278 return;
3279 }
3280 }
3281 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3282 // unallocated are marked as unavailable.
3283 for (unsigned I = 0; I < 16; I++)
3284 VFPRegs[I] = 1;
3285 AllocatedVFP = 17; // We do not have enough VFP registers.
3286}
3287
3288ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
3289 unsigned &AllocatedVFP,
Manman Renb3fa55f2012-10-30 23:21:41 +00003290 bool &IsHA) const {
3291 // We update number of allocated VFPs according to
3292 // 6.1.2.1 The following argument types are VFP CPRCs:
3293 // A single-precision floating-point type (including promoted
3294 // half-precision types); A double-precision floating-point type;
3295 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3296 // with a Base Type of a single- or double-precision floating-point type,
3297 // 64-bit containerized vectors or 128-bit containerized vectors with one
3298 // to four Elements.
3299
Manman Ren97f81572012-10-16 19:18:39 +00003300 // Handle illegal vector types here.
3301 if (isIllegalVectorType(Ty)) {
3302 uint64_t Size = getContext().getTypeSize(Ty);
3303 if (Size <= 32) {
3304 llvm::Type *ResType =
3305 llvm::Type::getInt32Ty(getVMContext());
3306 return ABIArgInfo::getDirect(ResType);
3307 }
3308 if (Size == 64) {
3309 llvm::Type *ResType = llvm::VectorType::get(
3310 llvm::Type::getInt32Ty(getVMContext()), 2);
Manman Ren710c5172012-10-31 19:02:26 +00003311 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Ren97f81572012-10-16 19:18:39 +00003312 return ABIArgInfo::getDirect(ResType);
3313 }
3314 if (Size == 128) {
3315 llvm::Type *ResType = llvm::VectorType::get(
3316 llvm::Type::getInt32Ty(getVMContext()), 4);
Manman Ren710c5172012-10-31 19:02:26 +00003317 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4);
Manman Ren97f81572012-10-16 19:18:39 +00003318 return ABIArgInfo::getDirect(ResType);
3319 }
3320 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3321 }
Manman Ren710c5172012-10-31 19:02:26 +00003322 // Update VFPRegs for legal vector types.
Manman Renb3fa55f2012-10-30 23:21:41 +00003323 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3324 uint64_t Size = getContext().getTypeSize(VT);
3325 // Size of a legal vector should be power of 2 and above 64.
Manman Ren710c5172012-10-31 19:02:26 +00003326 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32);
Manman Renb3fa55f2012-10-30 23:21:41 +00003327 }
Manman Ren710c5172012-10-31 19:02:26 +00003328 // Update VFPRegs for floating point types.
Manman Renb3fa55f2012-10-30 23:21:41 +00003329 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3330 if (BT->getKind() == BuiltinType::Half ||
3331 BT->getKind() == BuiltinType::Float)
Manman Ren710c5172012-10-31 19:02:26 +00003332 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1);
Manman Renb3fa55f2012-10-30 23:21:41 +00003333 if (BT->getKind() == BuiltinType::Double ||
Manman Ren710c5172012-10-31 19:02:26 +00003334 BT->getKind() == BuiltinType::LongDouble)
3335 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Renb3fa55f2012-10-30 23:21:41 +00003336 }
Manman Ren97f81572012-10-16 19:18:39 +00003337
John McCalld608cdb2010-08-22 10:59:02 +00003338 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003339 // Treat an enum type as its underlying type.
3340 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3341 Ty = EnumTy->getDecl()->getIntegerType();
3342
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00003343 return (Ty->isPromotableIntegerType() ?
3344 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003345 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003346
Tim Northoverf5c3a252013-06-21 22:49:34 +00003347 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
3348 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3349
Daniel Dunbar42025572009-09-14 21:54:03 +00003350 // Ignore empty records.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003351 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar42025572009-09-14 21:54:03 +00003352 return ABIArgInfo::getIgnore();
3353
Bob Wilson194f06a2011-08-03 05:58:22 +00003354 if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
Manman Renb3fa55f2012-10-30 23:21:41 +00003355 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3356 // into VFP registers.
Bob Wilson194f06a2011-08-03 05:58:22 +00003357 const Type *Base = 0;
Manman Renb3fa55f2012-10-30 23:21:41 +00003358 uint64_t Members = 0;
3359 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003360 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Renb3fa55f2012-10-30 23:21:41 +00003361 // Base can be a floating-point or a vector.
3362 if (Base->isVectorType()) {
3363 // ElementSize is in number of floats.
3364 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Manman Rencb489dd2012-11-06 19:05:29 +00003365 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize,
3366 Members * ElementSize);
Manman Renb3fa55f2012-10-30 23:21:41 +00003367 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Manman Ren710c5172012-10-31 19:02:26 +00003368 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members);
Manman Renb3fa55f2012-10-30 23:21:41 +00003369 else {
3370 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3371 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Manman Ren710c5172012-10-31 19:02:26 +00003372 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2);
Manman Renb3fa55f2012-10-30 23:21:41 +00003373 }
3374 IsHA = true;
Bob Wilson194f06a2011-08-03 05:58:22 +00003375 return ABIArgInfo::getExpand();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003376 }
Bob Wilson194f06a2011-08-03 05:58:22 +00003377 }
3378
Manman Ren634b3d22012-08-13 21:23:55 +00003379 // Support byval for ARM.
Manman Rencb489dd2012-11-06 19:05:29 +00003380 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3381 // most 8-byte. We realign the indirect argument if type alignment is bigger
3382 // than ABI alignment.
Manman Renfd1ba912012-11-05 22:42:46 +00003383 uint64_t ABIAlign = 4;
3384 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3385 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3386 getABIKind() == ARMABIInfo::AAPCS)
3387 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren885ad692012-11-06 04:58:01 +00003388 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
3389 return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
Manman Rencb489dd2012-11-06 19:05:29 +00003390 /*Realign=*/TyAlign > ABIAlign);
Eli Friedman79f30982012-08-09 00:31:40 +00003391 }
3392
Daniel Dunbar8aa87c72010-09-23 01:54:28 +00003393 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003394 llvm::Type* ElemTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003395 unsigned SizeRegs;
Eli Friedman79f30982012-08-09 00:31:40 +00003396 // FIXME: Try to match the types of the arguments more accurately where
3397 // we can.
3398 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson53fc1a62011-08-01 23:39:04 +00003399 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3400 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren78eb76e2012-06-25 22:04:00 +00003401 } else {
Manman Ren78eb76e2012-06-25 22:04:00 +00003402 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3403 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastings67d097e2011-04-27 17:24:02 +00003404 }
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00003405
Chris Lattner9cbe4f02011-07-09 17:41:47 +00003406 llvm::Type *STy =
Chris Lattner7650d952011-06-18 22:49:11 +00003407 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00003408 return ABIArgInfo::getDirect(STy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003409}
3410
Chris Lattnera3c109b2010-07-29 02:16:43 +00003411static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar98303b92009-09-13 08:03:58 +00003412 llvm::LLVMContext &VMContext) {
3413 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3414 // is called integer-like if its size is less than or equal to one word, and
3415 // the offset of each of its addressable sub-fields is zero.
3416
3417 uint64_t Size = Context.getTypeSize(Ty);
3418
3419 // Check that the type fits in a word.
3420 if (Size > 32)
3421 return false;
3422
3423 // FIXME: Handle vector types!
3424 if (Ty->isVectorType())
3425 return false;
3426
Daniel Dunbarb0d58192009-09-14 02:20:34 +00003427 // Float types are never treated as "integer like".
3428 if (Ty->isRealFloatingType())
3429 return false;
3430
Daniel Dunbar98303b92009-09-13 08:03:58 +00003431 // If this is a builtin or pointer type then it is ok.
John McCall183700f2009-09-21 23:43:11 +00003432 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar98303b92009-09-13 08:03:58 +00003433 return true;
3434
Daniel Dunbar45815812010-02-01 23:31:26 +00003435 // Small complex integer types are "integer like".
3436 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3437 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar98303b92009-09-13 08:03:58 +00003438
3439 // Single element and zero sized arrays should be allowed, by the definition
3440 // above, but they are not.
3441
3442 // Otherwise, it must be a record type.
3443 const RecordType *RT = Ty->getAs<RecordType>();
3444 if (!RT) return false;
3445
3446 // Ignore records with flexible arrays.
3447 const RecordDecl *RD = RT->getDecl();
3448 if (RD->hasFlexibleArrayMember())
3449 return false;
3450
3451 // Check that all sub-fields are at offset 0, and are themselves "integer
3452 // like".
3453 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3454
3455 bool HadField = false;
3456 unsigned idx = 0;
3457 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3458 i != e; ++i, ++idx) {
David Blaikie581deb32012-06-06 20:45:41 +00003459 const FieldDecl *FD = *i;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003460
Daniel Dunbar679855a2010-01-29 03:22:29 +00003461 // Bit-fields are not addressable, we only need to verify they are "integer
3462 // like". We still have to disallow a subsequent non-bitfield, for example:
3463 // struct { int : 0; int x }
3464 // is non-integer like according to gcc.
3465 if (FD->isBitField()) {
3466 if (!RD->isUnion())
3467 HadField = true;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003468
Daniel Dunbar679855a2010-01-29 03:22:29 +00003469 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3470 return false;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003471
Daniel Dunbar679855a2010-01-29 03:22:29 +00003472 continue;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003473 }
3474
Daniel Dunbar679855a2010-01-29 03:22:29 +00003475 // Check if this field is at offset 0.
3476 if (Layout.getFieldOffset(idx) != 0)
3477 return false;
3478
Daniel Dunbar98303b92009-09-13 08:03:58 +00003479 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3480 return false;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00003481
Daniel Dunbar679855a2010-01-29 03:22:29 +00003482 // Only allow at most one field in a structure. This doesn't match the
3483 // wording above, but follows gcc in situations with a field following an
3484 // empty structure.
Daniel Dunbar98303b92009-09-13 08:03:58 +00003485 if (!RD->isUnion()) {
3486 if (HadField)
3487 return false;
3488
3489 HadField = true;
3490 }
3491 }
3492
3493 return true;
3494}
3495
Chris Lattnera3c109b2010-07-29 02:16:43 +00003496ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
Daniel Dunbar98303b92009-09-13 08:03:58 +00003497 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003498 return ABIArgInfo::getIgnore();
Daniel Dunbar98303b92009-09-13 08:03:58 +00003499
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00003500 // Large vector types should be returned via memory.
3501 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3502 return ABIArgInfo::getIndirect(0);
3503
John McCalld608cdb2010-08-22 10:59:02 +00003504 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003505 // Treat an enum type as its underlying type.
3506 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3507 RetTy = EnumTy->getDecl()->getIntegerType();
3508
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00003509 return (RetTy->isPromotableIntegerType() ?
3510 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003511 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003512
Rafael Espindola0eb1d972010-06-08 02:42:08 +00003513 // Structures with either a non-trivial destructor or a non-trivial
3514 // copy constructor are always indirect.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003515 if (isRecordReturnIndirect(RetTy, CGT))
Rafael Espindola0eb1d972010-06-08 02:42:08 +00003516 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3517
Daniel Dunbar98303b92009-09-13 08:03:58 +00003518 // Are we following APCS?
3519 if (getABIKind() == APCS) {
Chris Lattnera3c109b2010-07-29 02:16:43 +00003520 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar98303b92009-09-13 08:03:58 +00003521 return ABIArgInfo::getIgnore();
3522
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00003523 // Complex types are all returned as packed integers.
3524 //
3525 // FIXME: Consider using 2 x vector types if the back end handles them
3526 // correctly.
3527 if (RetTy->isAnyComplexType())
Chris Lattner800588f2010-07-29 06:26:06 +00003528 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +00003529 getContext().getTypeSize(RetTy)));
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00003530
Daniel Dunbar98303b92009-09-13 08:03:58 +00003531 // Integer like structures are returned in r0.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003532 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar98303b92009-09-13 08:03:58 +00003533 // Return in the smallest viable integer type.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003534 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar98303b92009-09-13 08:03:58 +00003535 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00003536 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00003537 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00003538 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3539 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00003540 }
3541
3542 // Otherwise return in memory.
3543 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003544 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003545
3546 // Otherwise this is an AAPCS variant.
3547
Chris Lattnera3c109b2010-07-29 02:16:43 +00003548 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar16a08082009-09-14 00:56:55 +00003549 return ABIArgInfo::getIgnore();
3550
Bob Wilson3b694fa2011-11-02 04:51:36 +00003551 // Check for homogeneous aggregates with AAPCS-VFP.
3552 if (getABIKind() == AAPCS_VFP) {
3553 const Type *Base = 0;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003554 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3555 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson3b694fa2011-11-02 04:51:36 +00003556 // Homogeneous Aggregates are returned directly.
3557 return ABIArgInfo::getDirect();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003558 }
Bob Wilson3b694fa2011-11-02 04:51:36 +00003559 }
3560
Daniel Dunbar98303b92009-09-13 08:03:58 +00003561 // Aggregates <= 4 bytes are returned in r0; other aggregates
3562 // are returned indirectly.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003563 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar16a08082009-09-14 00:56:55 +00003564 if (Size <= 32) {
3565 // Return in the smallest viable integer type.
3566 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00003567 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00003568 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00003569 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3570 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00003571 }
3572
Daniel Dunbar98303b92009-09-13 08:03:58 +00003573 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003574}
3575
Manman Ren97f81572012-10-16 19:18:39 +00003576/// isIllegalVector - check whether Ty is an illegal vector type.
3577bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3578 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3579 // Check whether VT is legal.
3580 unsigned NumElements = VT->getNumElements();
3581 uint64_t Size = getContext().getTypeSize(VT);
3582 // NumElements should be power of 2.
3583 if ((NumElements & (NumElements - 1)) != 0)
3584 return true;
3585 // Size should be greater than 32 bits.
3586 return Size <= 32;
3587 }
3588 return false;
3589}
3590
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003591llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner77b89b82010-06-27 07:15:29 +00003592 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00003593 llvm::Type *BP = CGF.Int8PtrTy;
3594 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003595
3596 CGBuilderTy &Builder = CGF.Builder;
Chris Lattner8b418682012-02-07 00:39:47 +00003597 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003598 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rend105e732012-10-16 19:01:37 +00003599
Tim Northover373ac0a2013-06-21 23:05:33 +00003600 if (isEmptyRecord(getContext(), Ty, true)) {
3601 // These are ignored for parameter passing purposes.
3602 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3603 return Builder.CreateBitCast(Addr, PTy);
3604 }
3605
Manman Rend105e732012-10-16 19:01:37 +00003606 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindolae164c182011-08-02 22:33:37 +00003607 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Ren97f81572012-10-16 19:18:39 +00003608 bool IsIndirect = false;
Manman Rend105e732012-10-16 19:01:37 +00003609
3610 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3611 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren93371022012-10-16 19:51:48 +00003612 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3613 getABIKind() == ARMABIInfo::AAPCS)
3614 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3615 else
3616 TyAlign = 4;
Manman Ren97f81572012-10-16 19:18:39 +00003617 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3618 if (isIllegalVectorType(Ty) && Size > 16) {
3619 IsIndirect = true;
3620 Size = 4;
3621 TyAlign = 4;
3622 }
Manman Rend105e732012-10-16 19:01:37 +00003623
3624 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindolae164c182011-08-02 22:33:37 +00003625 if (TyAlign > 4) {
3626 assert((TyAlign & (TyAlign - 1)) == 0 &&
3627 "Alignment is not power of 2!");
3628 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3629 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3630 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rend105e732012-10-16 19:01:37 +00003631 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindolae164c182011-08-02 22:33:37 +00003632 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003633
3634 uint64_t Offset =
Manman Rend105e732012-10-16 19:01:37 +00003635 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003636 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00003637 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003638 "ap.next");
3639 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3640
Manman Ren97f81572012-10-16 19:18:39 +00003641 if (IsIndirect)
3642 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren93371022012-10-16 19:51:48 +00003643 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rend105e732012-10-16 19:01:37 +00003644 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3645 // may not be correctly aligned for the vector type. We create an aligned
3646 // temporary space and copy the content over from ap.cur to the temporary
3647 // space. This is necessary if the natural alignment of the type is greater
3648 // than the ABI alignment.
3649 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3650 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3651 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3652 "var.align");
3653 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3654 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3655 Builder.CreateMemCpy(Dst, Src,
3656 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3657 TyAlign, false);
3658 Addr = AlignedTemp; //The content is in aligned location.
3659 }
3660 llvm::Type *PTy =
3661 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3662 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3663
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003664 return AddrTyped;
3665}
3666
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00003667namespace {
3668
Derek Schuff263366f2012-10-16 22:30:41 +00003669class NaClARMABIInfo : public ABIInfo {
3670 public:
3671 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3672 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3673 virtual void computeInfo(CGFunctionInfo &FI) const;
3674 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3675 CodeGenFunction &CGF) const;
3676 private:
3677 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3678 ARMABIInfo NInfo; // Used for everything else.
3679};
3680
3681class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3682 public:
3683 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3684 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3685};
3686
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00003687}
3688
Derek Schuff263366f2012-10-16 22:30:41 +00003689void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3690 if (FI.getASTCallingConvention() == CC_PnaclCall)
3691 PInfo.computeInfo(FI);
3692 else
3693 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3694}
3695
3696llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3697 CodeGenFunction &CGF) const {
3698 // Always use the native convention; calling pnacl-style varargs functions
3699 // is unsupported.
3700 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3701}
3702
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003703//===----------------------------------------------------------------------===//
Tim Northoverc264e162013-01-31 12:13:10 +00003704// AArch64 ABI Implementation
3705//===----------------------------------------------------------------------===//
3706
3707namespace {
3708
3709class AArch64ABIInfo : public ABIInfo {
3710public:
3711 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3712
3713private:
3714 // The AArch64 PCS is explicit about return types and argument types being
3715 // handled identically, so we don't need to draw a distinction between
3716 // Argument and Return classification.
3717 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3718 int &FreeVFPRegs) const;
3719
3720 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3721 llvm::Type *DirectTy = 0) const;
3722
3723 virtual void computeInfo(CGFunctionInfo &FI) const;
3724
3725 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3726 CodeGenFunction &CGF) const;
3727};
3728
3729class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3730public:
3731 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3732 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3733
3734 const AArch64ABIInfo &getABIInfo() const {
3735 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3736 }
3737
3738 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3739 return 31;
3740 }
3741
3742 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3743 llvm::Value *Address) const {
3744 // 0-31 are x0-x30 and sp: 8 bytes each
3745 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
3746 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
3747
3748 // 64-95 are v0-v31: 16 bytes each
3749 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
3750 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
3751
3752 return false;
3753 }
3754
3755};
3756
3757}
3758
3759void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3760 int FreeIntRegs = 8, FreeVFPRegs = 8;
3761
3762 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
3763 FreeIntRegs, FreeVFPRegs);
3764
3765 FreeIntRegs = FreeVFPRegs = 8;
3766 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3767 it != ie; ++it) {
3768 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
3769
3770 }
3771}
3772
3773ABIArgInfo
3774AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
3775 bool IsInt, llvm::Type *DirectTy) const {
3776 if (FreeRegs >= RegsNeeded) {
3777 FreeRegs -= RegsNeeded;
3778 return ABIArgInfo::getDirect(DirectTy);
3779 }
3780
3781 llvm::Type *Padding = 0;
3782
3783 // We need padding so that later arguments don't get filled in anyway. That
3784 // wouldn't happen if only ByVal arguments followed in the same category, but
3785 // a large structure will simply seem to be a pointer as far as LLVM is
3786 // concerned.
3787 if (FreeRegs > 0) {
3788 if (IsInt)
3789 Padding = llvm::Type::getInt64Ty(getVMContext());
3790 else
3791 Padding = llvm::Type::getFloatTy(getVMContext());
3792
3793 // Either [N x i64] or [N x float].
3794 Padding = llvm::ArrayType::get(Padding, FreeRegs);
3795 FreeRegs = 0;
3796 }
3797
3798 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
3799 /*IsByVal=*/ true, /*Realign=*/ false,
3800 Padding);
3801}
3802
3803
3804ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
3805 int &FreeIntRegs,
3806 int &FreeVFPRegs) const {
3807 // Can only occurs for return, but harmless otherwise.
3808 if (Ty->isVoidType())
3809 return ABIArgInfo::getIgnore();
3810
3811 // Large vector types should be returned via memory. There's no such concept
3812 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
3813 // classified they'd go into memory (see B.3).
3814 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
3815 if (FreeIntRegs > 0)
3816 --FreeIntRegs;
3817 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3818 }
3819
3820 // All non-aggregate LLVM types have a concrete ABI representation so they can
3821 // be passed directly. After this block we're guaranteed to be in a
3822 // complicated case.
3823 if (!isAggregateTypeForABI(Ty)) {
3824 // Treat an enum type as its underlying type.
3825 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3826 Ty = EnumTy->getDecl()->getIntegerType();
3827
3828 if (Ty->isFloatingType() || Ty->isVectorType())
3829 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
3830
3831 assert(getContext().getTypeSize(Ty) <= 128 &&
3832 "unexpectedly large scalar type");
3833
3834 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3835
3836 // If the type may need padding registers to ensure "alignment", we must be
3837 // careful when this is accounted for. Increasing the effective size covers
3838 // all cases.
3839 if (getContext().getTypeAlign(Ty) == 128)
3840 RegsNeeded += FreeIntRegs % 2 != 0;
3841
3842 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
3843 }
3844
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003845 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT)) {
3846 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northoverc264e162013-01-31 12:13:10 +00003847 --FreeIntRegs;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003848 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northoverc264e162013-01-31 12:13:10 +00003849 }
3850
3851 if (isEmptyRecord(getContext(), Ty, true)) {
3852 if (!getContext().getLangOpts().CPlusPlus) {
3853 // Empty structs outside C++ mode are a GNU extension, so no ABI can
3854 // possibly tell us what to do. It turns out (I believe) that GCC ignores
3855 // the object for parameter-passsing purposes.
3856 return ABIArgInfo::getIgnore();
3857 }
3858
3859 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
3860 // description of va_arg in the PCS require that an empty struct does
3861 // actually occupy space for parameter-passing. I'm hoping for a
3862 // clarification giving an explicit paragraph to point to in future.
3863 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
3864 llvm::Type::getInt8Ty(getVMContext()));
3865 }
3866
3867 // Homogeneous vector aggregates get passed in registers or on the stack.
3868 const Type *Base = 0;
3869 uint64_t NumMembers = 0;
3870 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
3871 assert(Base && "Base class should be set for homogeneous aggregate");
3872 // Homogeneous aggregates are passed and returned directly.
3873 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
3874 /*IsInt=*/ false);
3875 }
3876
3877 uint64_t Size = getContext().getTypeSize(Ty);
3878 if (Size <= 128) {
3879 // Small structs can use the same direct type whether they're in registers
3880 // or on the stack.
3881 llvm::Type *BaseTy;
3882 unsigned NumBases;
3883 int SizeInRegs = (Size + 63) / 64;
3884
3885 if (getContext().getTypeAlign(Ty) == 128) {
3886 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
3887 NumBases = 1;
3888
3889 // If the type may need padding registers to ensure "alignment", we must
3890 // be careful when this is accounted for. Increasing the effective size
3891 // covers all cases.
3892 SizeInRegs += FreeIntRegs % 2 != 0;
3893 } else {
3894 BaseTy = llvm::Type::getInt64Ty(getVMContext());
3895 NumBases = SizeInRegs;
3896 }
3897 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
3898
3899 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
3900 /*IsInt=*/ true, DirectTy);
3901 }
3902
3903 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
3904 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
3905 --FreeIntRegs;
3906 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
3907}
3908
3909llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3910 CodeGenFunction &CGF) const {
3911 // The AArch64 va_list type and handling is specified in the Procedure Call
3912 // Standard, section B.4:
3913 //
3914 // struct {
3915 // void *__stack;
3916 // void *__gr_top;
3917 // void *__vr_top;
3918 // int __gr_offs;
3919 // int __vr_offs;
3920 // };
3921
3922 assert(!CGF.CGM.getDataLayout().isBigEndian()
3923 && "va_arg not implemented for big-endian AArch64");
3924
3925 int FreeIntRegs = 8, FreeVFPRegs = 8;
3926 Ty = CGF.getContext().getCanonicalType(Ty);
3927 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
3928
3929 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3930 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3931 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3932 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3933
3934 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
3935 int reg_top_index;
3936 int RegSize;
3937 if (FreeIntRegs < 8) {
3938 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
3939 // 3 is the field number of __gr_offs
3940 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3941 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3942 reg_top_index = 1; // field number for __gr_top
3943 RegSize = 8 * (8 - FreeIntRegs);
3944 } else {
3945 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
3946 // 4 is the field number of __vr_offs.
3947 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3948 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3949 reg_top_index = 2; // field number for __vr_top
3950 RegSize = 16 * (8 - FreeVFPRegs);
3951 }
3952
3953 //=======================================
3954 // Find out where argument was passed
3955 //=======================================
3956
3957 // If reg_offs >= 0 we're already using the stack for this type of
3958 // argument. We don't want to keep updating reg_offs (in case it overflows,
3959 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3960 // whatever they get).
3961 llvm::Value *UsingStack = 0;
3962 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
3963 llvm::ConstantInt::get(CGF.Int32Ty, 0));
3964
3965 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3966
3967 // Otherwise, at least some kind of argument could go in these registers, the
3968 // quesiton is whether this particular type is too big.
3969 CGF.EmitBlock(MaybeRegBlock);
3970
3971 // Integer arguments may need to correct register alignment (for example a
3972 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3973 // align __gr_offs to calculate the potential address.
3974 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
3975 int Align = getContext().getTypeAlign(Ty) / 8;
3976
3977 reg_offs = CGF.Builder.CreateAdd(reg_offs,
3978 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3979 "align_regoffs");
3980 reg_offs = CGF.Builder.CreateAnd(reg_offs,
3981 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3982 "aligned_regoffs");
3983 }
3984
3985 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
3986 llvm::Value *NewOffset = 0;
3987 NewOffset = CGF.Builder.CreateAdd(reg_offs,
3988 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
3989 "new_reg_offs");
3990 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3991
3992 // Now we're in a position to decide whether this argument really was in
3993 // registers or not.
3994 llvm::Value *InRegs = 0;
3995 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
3996 llvm::ConstantInt::get(CGF.Int32Ty, 0),
3997 "inreg");
3998
3999 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4000
4001 //=======================================
4002 // Argument was in registers
4003 //=======================================
4004
4005 // Now we emit the code for if the argument was originally passed in
4006 // registers. First start the appropriate block:
4007 CGF.EmitBlock(InRegBlock);
4008
4009 llvm::Value *reg_top_p = 0, *reg_top = 0;
4010 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4011 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4012 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4013 llvm::Value *RegAddr = 0;
4014 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4015
4016 if (!AI.isDirect()) {
4017 // If it's been passed indirectly (actually a struct), whatever we find from
4018 // stored registers or on the stack will actually be a struct **.
4019 MemTy = llvm::PointerType::getUnqual(MemTy);
4020 }
4021
4022 const Type *Base = 0;
4023 uint64_t NumMembers;
4024 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4025 && NumMembers > 1) {
4026 // Homogeneous aggregates passed in registers will have their elements split
4027 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4028 // qN+1, ...). We reload and store into a temporary local variable
4029 // contiguously.
4030 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4031 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4032 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4033 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4034
4035 for (unsigned i = 0; i < NumMembers; ++i) {
4036 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
4037 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4038 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4039 llvm::PointerType::getUnqual(BaseTy));
4040 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4041
4042 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4043 CGF.Builder.CreateStore(Elem, StoreAddr);
4044 }
4045
4046 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4047 } else {
4048 // Otherwise the object is contiguous in memory
4049 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4050 }
4051
4052 CGF.EmitBranch(ContBlock);
4053
4054 //=======================================
4055 // Argument was on the stack
4056 //=======================================
4057 CGF.EmitBlock(OnStackBlock);
4058
4059 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4060 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4061 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4062
4063 // Again, stack arguments may need realigmnent. In this case both integer and
4064 // floating-point ones might be affected.
4065 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4066 int Align = getContext().getTypeAlign(Ty) / 8;
4067
4068 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4069
4070 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4071 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4072 "align_stack");
4073 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4074 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4075 "align_stack");
4076
4077 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4078 }
4079
4080 uint64_t StackSize;
4081 if (AI.isDirect())
4082 StackSize = getContext().getTypeSize(Ty) / 8;
4083 else
4084 StackSize = 8;
4085
4086 // All stack slots are 8 bytes
4087 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4088
4089 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4090 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4091 "new_stack");
4092
4093 // Write the new value of __stack for the next call to va_arg
4094 CGF.Builder.CreateStore(NewStack, stack_p);
4095
4096 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4097
4098 CGF.EmitBranch(ContBlock);
4099
4100 //=======================================
4101 // Tidy up
4102 //=======================================
4103 CGF.EmitBlock(ContBlock);
4104
4105 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4106 ResAddr->addIncoming(RegAddr, InRegBlock);
4107 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4108
4109 if (AI.isDirect())
4110 return ResAddr;
4111
4112 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4113}
4114
4115//===----------------------------------------------------------------------===//
Justin Holewinski2c585b92012-05-24 17:43:12 +00004116// NVPTX ABI Implementation
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004117//===----------------------------------------------------------------------===//
4118
4119namespace {
4120
Justin Holewinski2c585b92012-05-24 17:43:12 +00004121class NVPTXABIInfo : public ABIInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004122public:
Justin Holewinskidca8f332013-03-30 14:38:24 +00004123 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004124
4125 ABIArgInfo classifyReturnType(QualType RetTy) const;
4126 ABIArgInfo classifyArgumentType(QualType Ty) const;
4127
4128 virtual void computeInfo(CGFunctionInfo &FI) const;
4129 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4130 CodeGenFunction &CFG) const;
4131};
4132
Justin Holewinski2c585b92012-05-24 17:43:12 +00004133class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004134public:
Justin Holewinski2c585b92012-05-24 17:43:12 +00004135 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4136 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Justin Holewinski818eafb2011-10-05 17:58:44 +00004137
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004138 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4139 CodeGen::CodeGenModule &M) const;
Justin Holewinskidca8f332013-03-30 14:38:24 +00004140private:
4141 static void addKernelMetadata(llvm::Function *F);
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004142};
4143
Justin Holewinski2c585b92012-05-24 17:43:12 +00004144ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004145 if (RetTy->isVoidType())
4146 return ABIArgInfo::getIgnore();
4147 if (isAggregateTypeForABI(RetTy))
4148 return ABIArgInfo::getIndirect(0);
4149 return ABIArgInfo::getDirect();
4150}
4151
Justin Holewinski2c585b92012-05-24 17:43:12 +00004152ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004153 if (isAggregateTypeForABI(Ty))
4154 return ABIArgInfo::getIndirect(0);
4155
4156 return ABIArgInfo::getDirect();
4157}
4158
Justin Holewinski2c585b92012-05-24 17:43:12 +00004159void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004160 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4161 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4162 it != ie; ++it)
4163 it->info = classifyArgumentType(it->type);
4164
4165 // Always honor user-specified calling convention.
4166 if (FI.getCallingConvention() != llvm::CallingConv::C)
4167 return;
4168
John McCallbd7370a2013-02-28 19:01:20 +00004169 FI.setEffectiveCallingConvention(getRuntimeCC());
4170}
4171
Justin Holewinski2c585b92012-05-24 17:43:12 +00004172llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4173 CodeGenFunction &CFG) const {
4174 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004175}
4176
Justin Holewinski2c585b92012-05-24 17:43:12 +00004177void NVPTXTargetCodeGenInfo::
4178SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4179 CodeGen::CodeGenModule &M) const{
Justin Holewinski818eafb2011-10-05 17:58:44 +00004180 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4181 if (!FD) return;
4182
4183 llvm::Function *F = cast<llvm::Function>(GV);
4184
4185 // Perform special handling in OpenCL mode
David Blaikie4e4d0842012-03-11 07:00:24 +00004186 if (M.getLangOpts().OpenCL) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004187 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00004188 // By default, all functions are device functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00004189 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004190 // OpenCL __kernel functions get kernel metadata
4191 addKernelMetadata(F);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004192 // And kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00004193 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004194 }
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004195 }
Justin Holewinski818eafb2011-10-05 17:58:44 +00004196
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004197 // Perform special handling in CUDA mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00004198 if (M.getLangOpts().CUDA) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004199 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004200 // __global__ functions cannot be called from the device, we do not
4201 // need to set the noinline attribute.
4202 if (FD->getAttr<CUDAGlobalAttr>())
Justin Holewinskidca8f332013-03-30 14:38:24 +00004203 addKernelMetadata(F);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004204 }
4205}
4206
Justin Holewinskidca8f332013-03-30 14:38:24 +00004207void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4208 llvm::Module *M = F->getParent();
4209 llvm::LLVMContext &Ctx = M->getContext();
4210
4211 // Get "nvvm.annotations" metadata node
4212 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4213
4214 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4215 llvm::SmallVector<llvm::Value *, 3> MDVals;
4216 MDVals.push_back(F);
4217 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4218 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4219
4220 // Append metadata to nvvm.annotations
4221 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4222}
4223
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004224}
4225
4226//===----------------------------------------------------------------------===//
Ulrich Weigandb8409212013-05-06 16:26:41 +00004227// SystemZ ABI Implementation
4228//===----------------------------------------------------------------------===//
4229
4230namespace {
4231
4232class SystemZABIInfo : public ABIInfo {
4233public:
4234 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4235
4236 bool isPromotableIntegerType(QualType Ty) const;
4237 bool isCompoundType(QualType Ty) const;
4238 bool isFPArgumentType(QualType Ty) const;
4239
4240 ABIArgInfo classifyReturnType(QualType RetTy) const;
4241 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4242
4243 virtual void computeInfo(CGFunctionInfo &FI) const {
4244 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4245 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4246 it != ie; ++it)
4247 it->info = classifyArgumentType(it->type);
4248 }
4249
4250 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4251 CodeGenFunction &CGF) const;
4252};
4253
4254class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4255public:
4256 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4257 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4258};
4259
4260}
4261
4262bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4263 // Treat an enum type as its underlying type.
4264 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4265 Ty = EnumTy->getDecl()->getIntegerType();
4266
4267 // Promotable integer types are required to be promoted by the ABI.
4268 if (Ty->isPromotableIntegerType())
4269 return true;
4270
4271 // 32-bit values must also be promoted.
4272 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4273 switch (BT->getKind()) {
4274 case BuiltinType::Int:
4275 case BuiltinType::UInt:
4276 return true;
4277 default:
4278 return false;
4279 }
4280 return false;
4281}
4282
4283bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4284 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4285}
4286
4287bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4288 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4289 switch (BT->getKind()) {
4290 case BuiltinType::Float:
4291 case BuiltinType::Double:
4292 return true;
4293 default:
4294 return false;
4295 }
4296
4297 if (const RecordType *RT = Ty->getAsStructureType()) {
4298 const RecordDecl *RD = RT->getDecl();
4299 bool Found = false;
4300
4301 // If this is a C++ record, check the bases first.
4302 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4303 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4304 E = CXXRD->bases_end(); I != E; ++I) {
4305 QualType Base = I->getType();
4306
4307 // Empty bases don't affect things either way.
4308 if (isEmptyRecord(getContext(), Base, true))
4309 continue;
4310
4311 if (Found)
4312 return false;
4313 Found = isFPArgumentType(Base);
4314 if (!Found)
4315 return false;
4316 }
4317
4318 // Check the fields.
4319 for (RecordDecl::field_iterator I = RD->field_begin(),
4320 E = RD->field_end(); I != E; ++I) {
4321 const FieldDecl *FD = *I;
4322
4323 // Empty bitfields don't affect things either way.
4324 // Unlike isSingleElementStruct(), empty structure and array fields
4325 // do count. So do anonymous bitfields that aren't zero-sized.
4326 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4327 return true;
4328
4329 // Unlike isSingleElementStruct(), arrays do not count.
4330 // Nested isFPArgumentType structures still do though.
4331 if (Found)
4332 return false;
4333 Found = isFPArgumentType(FD->getType());
4334 if (!Found)
4335 return false;
4336 }
4337
4338 // Unlike isSingleElementStruct(), trailing padding is allowed.
4339 // An 8-byte aligned struct s { float f; } is passed as a double.
4340 return Found;
4341 }
4342
4343 return false;
4344}
4345
4346llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4347 CodeGenFunction &CGF) const {
4348 // Assume that va_list type is correct; should be pointer to LLVM type:
4349 // struct {
4350 // i64 __gpr;
4351 // i64 __fpr;
4352 // i8 *__overflow_arg_area;
4353 // i8 *__reg_save_area;
4354 // };
4355
4356 // Every argument occupies 8 bytes and is passed by preference in either
4357 // GPRs or FPRs.
4358 Ty = CGF.getContext().getCanonicalType(Ty);
4359 ABIArgInfo AI = classifyArgumentType(Ty);
4360 bool InFPRs = isFPArgumentType(Ty);
4361
4362 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4363 bool IsIndirect = AI.isIndirect();
4364 unsigned UnpaddedBitSize;
4365 if (IsIndirect) {
4366 APTy = llvm::PointerType::getUnqual(APTy);
4367 UnpaddedBitSize = 64;
4368 } else
4369 UnpaddedBitSize = getContext().getTypeSize(Ty);
4370 unsigned PaddedBitSize = 64;
4371 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4372
4373 unsigned PaddedSize = PaddedBitSize / 8;
4374 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4375
4376 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4377 if (InFPRs) {
4378 MaxRegs = 4; // Maximum of 4 FPR arguments
4379 RegCountField = 1; // __fpr
4380 RegSaveIndex = 16; // save offset for f0
4381 RegPadding = 0; // floats are passed in the high bits of an FPR
4382 } else {
4383 MaxRegs = 5; // Maximum of 5 GPR arguments
4384 RegCountField = 0; // __gpr
4385 RegSaveIndex = 2; // save offset for r2
4386 RegPadding = Padding; // values are passed in the low bits of a GPR
4387 }
4388
4389 llvm::Value *RegCountPtr =
4390 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4391 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4392 llvm::Type *IndexTy = RegCount->getType();
4393 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4394 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
4395 "fits_in_regs");
4396
4397 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4398 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4399 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4400 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4401
4402 // Emit code to load the value if it was passed in registers.
4403 CGF.EmitBlock(InRegBlock);
4404
4405 // Work out the address of an argument register.
4406 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4407 llvm::Value *ScaledRegCount =
4408 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4409 llvm::Value *RegBase =
4410 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4411 llvm::Value *RegOffset =
4412 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4413 llvm::Value *RegSaveAreaPtr =
4414 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4415 llvm::Value *RegSaveArea =
4416 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4417 llvm::Value *RawRegAddr =
4418 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4419 llvm::Value *RegAddr =
4420 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4421
4422 // Update the register count
4423 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4424 llvm::Value *NewRegCount =
4425 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4426 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4427 CGF.EmitBranch(ContBlock);
4428
4429 // Emit code to load the value if it was passed in memory.
4430 CGF.EmitBlock(InMemBlock);
4431
4432 // Work out the address of a stack argument.
4433 llvm::Value *OverflowArgAreaPtr =
4434 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4435 llvm::Value *OverflowArgArea =
4436 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4437 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4438 llvm::Value *RawMemAddr =
4439 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4440 llvm::Value *MemAddr =
4441 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4442
4443 // Update overflow_arg_area_ptr pointer
4444 llvm::Value *NewOverflowArgArea =
4445 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4446 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4447 CGF.EmitBranch(ContBlock);
4448
4449 // Return the appropriate result.
4450 CGF.EmitBlock(ContBlock);
4451 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4452 ResAddr->addIncoming(RegAddr, InRegBlock);
4453 ResAddr->addIncoming(MemAddr, InMemBlock);
4454
4455 if (IsIndirect)
4456 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4457
4458 return ResAddr;
4459}
4460
John McCallb8b52972013-06-18 02:46:29 +00004461bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4462 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4463 assert(Triple.getArch() == llvm::Triple::x86);
4464
4465 switch (Opts.getStructReturnConvention()) {
4466 case CodeGenOptions::SRCK_Default:
4467 break;
4468 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4469 return false;
4470 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4471 return true;
4472 }
4473
4474 if (Triple.isOSDarwin())
4475 return true;
4476
4477 switch (Triple.getOS()) {
4478 case llvm::Triple::Cygwin:
4479 case llvm::Triple::MinGW32:
4480 case llvm::Triple::AuroraUX:
4481 case llvm::Triple::DragonFly:
4482 case llvm::Triple::FreeBSD:
4483 case llvm::Triple::OpenBSD:
4484 case llvm::Triple::Bitrig:
4485 case llvm::Triple::Win32:
4486 return true;
4487 default:
4488 return false;
4489 }
4490}
Ulrich Weigandb8409212013-05-06 16:26:41 +00004491
4492ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4493 if (RetTy->isVoidType())
4494 return ABIArgInfo::getIgnore();
4495 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4496 return ABIArgInfo::getIndirect(0);
4497 return (isPromotableIntegerType(RetTy) ?
4498 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4499}
4500
4501ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4502 // Handle the generic C++ ABI.
4503 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
4504 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4505
4506 // Integers and enums are extended to full register width.
4507 if (isPromotableIntegerType(Ty))
4508 return ABIArgInfo::getExtend();
4509
4510 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4511 uint64_t Size = getContext().getTypeSize(Ty);
4512 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
4513 return ABIArgInfo::getIndirect(0);
4514
4515 // Handle small structures.
4516 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4517 // Structures with flexible arrays have variable length, so really
4518 // fail the size test above.
4519 const RecordDecl *RD = RT->getDecl();
4520 if (RD->hasFlexibleArrayMember())
4521 return ABIArgInfo::getIndirect(0);
4522
4523 // The structure is passed as an unextended integer, a float, or a double.
4524 llvm::Type *PassTy;
4525 if (isFPArgumentType(Ty)) {
4526 assert(Size == 32 || Size == 64);
4527 if (Size == 32)
4528 PassTy = llvm::Type::getFloatTy(getVMContext());
4529 else
4530 PassTy = llvm::Type::getDoubleTy(getVMContext());
4531 } else
4532 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4533 return ABIArgInfo::getDirect(PassTy);
4534 }
4535
4536 // Non-structure compounds are passed indirectly.
4537 if (isCompoundType(Ty))
4538 return ABIArgInfo::getIndirect(0);
4539
4540 return ABIArgInfo::getDirect(0);
4541}
4542
4543//===----------------------------------------------------------------------===//
Wesley Peck276fdf42010-12-19 19:57:51 +00004544// MBlaze ABI Implementation
4545//===----------------------------------------------------------------------===//
4546
4547namespace {
4548
4549class MBlazeABIInfo : public ABIInfo {
4550public:
4551 MBlazeABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4552
4553 bool isPromotableIntegerType(QualType Ty) const;
4554
4555 ABIArgInfo classifyReturnType(QualType RetTy) const;
4556 ABIArgInfo classifyArgumentType(QualType RetTy) const;
4557
4558 virtual void computeInfo(CGFunctionInfo &FI) const {
4559 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4560 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4561 it != ie; ++it)
4562 it->info = classifyArgumentType(it->type);
4563 }
4564
4565 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4566 CodeGenFunction &CGF) const;
4567};
4568
4569class MBlazeTargetCodeGenInfo : public TargetCodeGenInfo {
4570public:
4571 MBlazeTargetCodeGenInfo(CodeGenTypes &CGT)
4572 : TargetCodeGenInfo(new MBlazeABIInfo(CGT)) {}
4573 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4574 CodeGen::CodeGenModule &M) const;
4575};
4576
4577}
4578
4579bool MBlazeABIInfo::isPromotableIntegerType(QualType Ty) const {
4580 // MBlaze ABI requires all 8 and 16 bit quantities to be extended.
4581 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4582 switch (BT->getKind()) {
4583 case BuiltinType::Bool:
4584 case BuiltinType::Char_S:
4585 case BuiltinType::Char_U:
4586 case BuiltinType::SChar:
4587 case BuiltinType::UChar:
4588 case BuiltinType::Short:
4589 case BuiltinType::UShort:
4590 return true;
4591 default:
4592 return false;
4593 }
4594 return false;
4595}
4596
4597llvm::Value *MBlazeABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4598 CodeGenFunction &CGF) const {
4599 // FIXME: Implement
4600 return 0;
4601}
4602
4603
4604ABIArgInfo MBlazeABIInfo::classifyReturnType(QualType RetTy) const {
4605 if (RetTy->isVoidType())
4606 return ABIArgInfo::getIgnore();
4607 if (isAggregateTypeForABI(RetTy))
4608 return ABIArgInfo::getIndirect(0);
4609
4610 return (isPromotableIntegerType(RetTy) ?
4611 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4612}
4613
4614ABIArgInfo MBlazeABIInfo::classifyArgumentType(QualType Ty) const {
4615 if (isAggregateTypeForABI(Ty))
4616 return ABIArgInfo::getIndirect(0);
4617
4618 return (isPromotableIntegerType(Ty) ?
4619 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4620}
4621
4622void MBlazeTargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4623 llvm::GlobalValue *GV,
4624 CodeGen::CodeGenModule &M)
4625 const {
4626 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4627 if (!FD) return;
NAKAMURA Takumi125b4cb2011-02-17 08:50:50 +00004628
Wesley Peck276fdf42010-12-19 19:57:51 +00004629 llvm::CallingConv::ID CC = llvm::CallingConv::C;
4630 if (FD->hasAttr<MBlazeInterruptHandlerAttr>())
4631 CC = llvm::CallingConv::MBLAZE_INTR;
4632 else if (FD->hasAttr<MBlazeSaveVolatilesAttr>())
4633 CC = llvm::CallingConv::MBLAZE_SVOL;
4634
4635 if (CC != llvm::CallingConv::C) {
4636 // Handle 'interrupt_handler' attribute:
4637 llvm::Function *F = cast<llvm::Function>(GV);
4638
4639 // Step 1: Set ISR calling convention.
4640 F->setCallingConv(CC);
4641
4642 // Step 2: Add attributes goodness.
Bill Wendling72390b32012-12-20 19:27:06 +00004643 F->addFnAttr(llvm::Attribute::NoInline);
Wesley Peck276fdf42010-12-19 19:57:51 +00004644 }
4645
4646 // Step 3: Emit _interrupt_handler alias.
4647 if (CC == llvm::CallingConv::MBLAZE_INTR)
4648 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
4649 "_interrupt_handler", GV, &M.getModule());
4650}
4651
4652
4653//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004654// MSP430 ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004655//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004656
4657namespace {
4658
4659class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4660public:
Chris Lattnerea044322010-07-29 02:01:43 +00004661 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4662 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004663 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4664 CodeGen::CodeGenModule &M) const;
4665};
4666
4667}
4668
4669void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4670 llvm::GlobalValue *GV,
4671 CodeGen::CodeGenModule &M) const {
4672 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4673 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4674 // Handle 'interrupt' attribute:
4675 llvm::Function *F = cast<llvm::Function>(GV);
4676
4677 // Step 1: Set ISR calling convention.
4678 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4679
4680 // Step 2: Add attributes goodness.
Bill Wendling72390b32012-12-20 19:27:06 +00004681 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004682
4683 // Step 3: Emit ISR vector alias.
Anton Korobeynikovf419a852012-11-26 18:59:10 +00004684 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004685 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovf419a852012-11-26 18:59:10 +00004686 "__isr_" + Twine(Num),
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004687 GV, &M.getModule());
4688 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004689 }
4690}
4691
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004692//===----------------------------------------------------------------------===//
John McCallaeeb7012010-05-27 06:19:26 +00004693// MIPS ABI Implementation. This works for both little-endian and
4694// big-endian variants.
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004695//===----------------------------------------------------------------------===//
4696
John McCallaeeb7012010-05-27 06:19:26 +00004697namespace {
Akira Hatanaka619e8872011-06-02 00:09:17 +00004698class MipsABIInfo : public ABIInfo {
Akira Hatanakac0e3b662011-11-02 23:14:57 +00004699 bool IsO32;
Akira Hatanakac359f202012-07-03 19:24:06 +00004700 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4701 void CoerceToIntArgs(uint64_t TySize,
4702 SmallVector<llvm::Type*, 8> &ArgList) const;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004703 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004704 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004705 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004706public:
Akira Hatanakab551dd32011-11-03 00:05:50 +00004707 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakac359f202012-07-03 19:24:06 +00004708 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
4709 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanaka619e8872011-06-02 00:09:17 +00004710
4711 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004712 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004713 virtual void computeInfo(CGFunctionInfo &FI) const;
4714 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4715 CodeGenFunction &CGF) const;
4716};
4717
John McCallaeeb7012010-05-27 06:19:26 +00004718class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanakae624fa02011-09-20 18:23:28 +00004719 unsigned SizeOfUnwindException;
John McCallaeeb7012010-05-27 06:19:26 +00004720public:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00004721 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
4722 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
4723 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCallaeeb7012010-05-27 06:19:26 +00004724
4725 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4726 return 29;
4727 }
4728
Reed Kotler7dfd1822013-01-16 17:10:28 +00004729 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4730 CodeGen::CodeGenModule &CGM) const {
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004731 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4732 if (!FD) return;
Rafael Espindolad8e6d6d2013-03-19 14:32:23 +00004733 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004734 if (FD->hasAttr<Mips16Attr>()) {
4735 Fn->addFnAttr("mips16");
4736 }
4737 else if (FD->hasAttr<NoMips16Attr>()) {
4738 Fn->addFnAttr("nomips16");
4739 }
Reed Kotler7dfd1822013-01-16 17:10:28 +00004740 }
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004741
John McCallaeeb7012010-05-27 06:19:26 +00004742 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00004743 llvm::Value *Address) const;
John McCall49e34be2011-08-30 01:42:09 +00004744
4745 unsigned getSizeOfUnwindException() const {
Akira Hatanakae624fa02011-09-20 18:23:28 +00004746 return SizeOfUnwindException;
John McCall49e34be2011-08-30 01:42:09 +00004747 }
John McCallaeeb7012010-05-27 06:19:26 +00004748};
4749}
4750
Akira Hatanakac359f202012-07-03 19:24:06 +00004751void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
4752 SmallVector<llvm::Type*, 8> &ArgList) const {
4753 llvm::IntegerType *IntTy =
4754 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004755
4756 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4757 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4758 ArgList.push_back(IntTy);
4759
4760 // If necessary, add one more integer type to ArgList.
4761 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4762
4763 if (R)
4764 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004765}
4766
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004767// In N32/64, an aligned double precision floating point field is passed in
4768// a register.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004769llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00004770 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4771
4772 if (IsO32) {
4773 CoerceToIntArgs(TySize, ArgList);
4774 return llvm::StructType::get(getVMContext(), ArgList);
4775 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004776
Akira Hatanaka2afd23d2012-01-12 00:52:17 +00004777 if (Ty->isComplexType())
4778 return CGT.ConvertType(Ty);
Akira Hatanaka6d1080f2012-01-10 23:12:19 +00004779
Akira Hatanakaa34e9212012-02-09 19:54:16 +00004780 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004781
Akira Hatanakac359f202012-07-03 19:24:06 +00004782 // Unions/vectors are passed in integer registers.
4783 if (!RT || !RT->isStructureOrClassType()) {
4784 CoerceToIntArgs(TySize, ArgList);
4785 return llvm::StructType::get(getVMContext(), ArgList);
4786 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004787
4788 const RecordDecl *RD = RT->getDecl();
4789 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004790 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004791
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004792 uint64_t LastOffset = 0;
4793 unsigned idx = 0;
4794 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4795
Akira Hatanakaa34e9212012-02-09 19:54:16 +00004796 // Iterate over fields in the struct/class and check if there are any aligned
4797 // double fields.
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004798 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4799 i != e; ++i, ++idx) {
David Blaikie262bc182012-04-30 02:36:29 +00004800 const QualType Ty = i->getType();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004801 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4802
4803 if (!BT || BT->getKind() != BuiltinType::Double)
4804 continue;
4805
4806 uint64_t Offset = Layout.getFieldOffset(idx);
4807 if (Offset % 64) // Ignore doubles that are not aligned.
4808 continue;
4809
4810 // Add ((Offset - LastOffset) / 64) args of type i64.
4811 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4812 ArgList.push_back(I64);
4813
4814 // Add double type.
4815 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4816 LastOffset = Offset + 64;
4817 }
4818
Akira Hatanakac359f202012-07-03 19:24:06 +00004819 CoerceToIntArgs(TySize - LastOffset, IntArgList);
4820 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004821
4822 return llvm::StructType::get(getVMContext(), ArgList);
4823}
4824
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004825llvm::Type *MipsABIInfo::getPaddingType(uint64_t Align, uint64_t Offset) const {
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004826 assert((Offset % MinABIStackAlignInBytes) == 0);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004827
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004828 if ((Align - 1) & Offset)
4829 return llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
4830
4831 return 0;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004832}
Akira Hatanaka9659d592012-01-10 22:44:52 +00004833
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004834ABIArgInfo
4835MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004836 uint64_t OrigOffset = Offset;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004837 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004838 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004839
Akira Hatanakac359f202012-07-03 19:24:06 +00004840 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
4841 (uint64_t)StackAlignInBytes);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004842 Offset = llvm::RoundUpToAlignment(Offset, Align);
4843 Offset += llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004844
Akira Hatanakac359f202012-07-03 19:24:06 +00004845 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanaka619e8872011-06-02 00:09:17 +00004846 // Ignore empty aggregates.
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004847 if (TySize == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00004848 return ABIArgInfo::getIgnore();
4849
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004850 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT)) {
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004851 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004852 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004853 }
Akira Hatanaka511949b2011-08-01 18:09:58 +00004854
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004855 // If we have reached here, aggregates are passed directly by coercing to
4856 // another structure type. Padding is inserted if the offset of the
4857 // aggregate is unaligned.
4858 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
4859 getPaddingType(Align, OrigOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00004860 }
4861
4862 // Treat an enum type as its underlying type.
4863 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4864 Ty = EnumTy->getDecl()->getIntegerType();
4865
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004866 if (Ty->isPromotableIntegerType())
4867 return ABIArgInfo::getExtend();
4868
Akira Hatanaka4055cfc2013-01-24 21:47:33 +00004869 return ABIArgInfo::getDirect(0, 0,
4870 IsO32 ? 0 : getPaddingType(Align, OrigOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00004871}
4872
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004873llvm::Type*
4874MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakada54ff32012-02-09 18:49:26 +00004875 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakac359f202012-07-03 19:24:06 +00004876 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004877
Akira Hatanakada54ff32012-02-09 18:49:26 +00004878 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004879 const RecordDecl *RD = RT->getDecl();
Akira Hatanakada54ff32012-02-09 18:49:26 +00004880 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4881 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004882
Akira Hatanakada54ff32012-02-09 18:49:26 +00004883 // N32/64 returns struct/classes in floating point registers if the
4884 // following conditions are met:
4885 // 1. The size of the struct/class is no larger than 128-bit.
4886 // 2. The struct/class has one or two fields all of which are floating
4887 // point types.
4888 // 3. The offset of the first field is zero (this follows what gcc does).
4889 //
4890 // Any other composite results are returned in integer registers.
4891 //
4892 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
4893 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
4894 for (; b != e; ++b) {
David Blaikie262bc182012-04-30 02:36:29 +00004895 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004896
Akira Hatanakada54ff32012-02-09 18:49:26 +00004897 if (!BT || !BT->isFloatingPoint())
4898 break;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004899
David Blaikie262bc182012-04-30 02:36:29 +00004900 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakada54ff32012-02-09 18:49:26 +00004901 }
4902
4903 if (b == e)
4904 return llvm::StructType::get(getVMContext(), RTList,
4905 RD->hasAttr<PackedAttr>());
4906
4907 RTList.clear();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004908 }
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004909 }
4910
Akira Hatanakac359f202012-07-03 19:24:06 +00004911 CoerceToIntArgs(Size, RTList);
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004912 return llvm::StructType::get(getVMContext(), RTList);
4913}
4914
Akira Hatanaka619e8872011-06-02 00:09:17 +00004915ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanakaa8536c02012-01-23 23:18:57 +00004916 uint64_t Size = getContext().getTypeSize(RetTy);
4917
4918 if (RetTy->isVoidType() || Size == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00004919 return ABIArgInfo::getIgnore();
4920
Akira Hatanaka8aeb1472012-05-11 21:01:17 +00004921 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004922 if (isRecordReturnIndirect(RetTy, CGT))
4923 return ABIArgInfo::getIndirect(0);
4924
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004925 if (Size <= 128) {
4926 if (RetTy->isAnyComplexType())
4927 return ABIArgInfo::getDirect();
4928
Akira Hatanakac359f202012-07-03 19:24:06 +00004929 // O32 returns integer vectors in registers.
4930 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
4931 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4932
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004933 if (!IsO32)
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004934 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4935 }
Akira Hatanaka619e8872011-06-02 00:09:17 +00004936
4937 return ABIArgInfo::getIndirect(0);
4938 }
4939
4940 // Treat an enum type as its underlying type.
4941 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4942 RetTy = EnumTy->getDecl()->getIntegerType();
4943
4944 return (RetTy->isPromotableIntegerType() ?
4945 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4946}
4947
4948void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakacc662542012-01-12 01:10:09 +00004949 ABIArgInfo &RetInfo = FI.getReturnInfo();
4950 RetInfo = classifyReturnType(FI.getReturnType());
4951
4952 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004953 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanakacc662542012-01-12 01:10:09 +00004954
Akira Hatanaka619e8872011-06-02 00:09:17 +00004955 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4956 it != ie; ++it)
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004957 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanaka619e8872011-06-02 00:09:17 +00004958}
4959
4960llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4961 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00004962 llvm::Type *BP = CGF.Int8PtrTy;
4963 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004964
4965 CGBuilderTy &Builder = CGF.Builder;
4966 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4967 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004968 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004969 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4970 llvm::Value *AddrTyped;
John McCall64aa4b32013-04-16 22:48:15 +00004971 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004972 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004973
4974 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004975 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
4976 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
4977 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
4978 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004979 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
4980 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
4981 }
4982 else
4983 AddrTyped = Builder.CreateBitCast(Addr, PTy);
4984
4985 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004986 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004987 uint64_t Offset =
4988 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
4989 llvm::Value *NextAddr =
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004990 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004991 "ap.next");
4992 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4993
4994 return AddrTyped;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004995}
4996
John McCallaeeb7012010-05-27 06:19:26 +00004997bool
4998MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4999 llvm::Value *Address) const {
5000 // This information comes from gcc's implementation, which seems to
5001 // as canonical as it gets.
5002
John McCallaeeb7012010-05-27 06:19:26 +00005003 // Everything on MIPS is 4 bytes. Double-precision FP registers
5004 // are aliased to pairs of single-precision FP registers.
Chris Lattner8b418682012-02-07 00:39:47 +00005005 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCallaeeb7012010-05-27 06:19:26 +00005006
5007 // 0-31 are the general purpose registers, $0 - $31.
5008 // 32-63 are the floating-point registers, $f0 - $f31.
5009 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5010 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattner8b418682012-02-07 00:39:47 +00005011 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCallaeeb7012010-05-27 06:19:26 +00005012
5013 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5014 // They are one bit wide and ignored here.
5015
5016 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5017 // (coprocessor 1 is the FP unit)
5018 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5019 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5020 // 176-181 are the DSP accumulator registers.
Chris Lattner8b418682012-02-07 00:39:47 +00005021 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCallaeeb7012010-05-27 06:19:26 +00005022 return false;
5023}
5024
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005025//===----------------------------------------------------------------------===//
5026// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5027// Currently subclassed only to implement custom OpenCL C function attribute
5028// handling.
5029//===----------------------------------------------------------------------===//
5030
5031namespace {
5032
5033class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5034public:
5035 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5036 : DefaultTargetCodeGenInfo(CGT) {}
5037
5038 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5039 CodeGen::CodeGenModule &M) const;
5040};
5041
5042void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5043 llvm::GlobalValue *GV,
5044 CodeGen::CodeGenModule &M) const {
5045 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5046 if (!FD) return;
5047
5048 llvm::Function *F = cast<llvm::Function>(GV);
5049
David Blaikie4e4d0842012-03-11 07:00:24 +00005050 if (M.getLangOpts().OpenCL) {
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005051 if (FD->hasAttr<OpenCLKernelAttr>()) {
5052 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00005053 F->addFnAttr(llvm::Attribute::NoInline);
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005054
5055 if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
5056
5057 // Convert the reqd_work_group_size() attributes to metadata.
5058 llvm::LLVMContext &Context = F->getContext();
5059 llvm::NamedMDNode *OpenCLMetadata =
5060 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5061
5062 SmallVector<llvm::Value*, 5> Operands;
5063 Operands.push_back(F);
5064
Chris Lattner8b418682012-02-07 00:39:47 +00005065 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5066 llvm::APInt(32,
5067 FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim())));
5068 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5069 llvm::APInt(32,
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005070 FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim())));
Chris Lattner8b418682012-02-07 00:39:47 +00005071 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5072 llvm::APInt(32,
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005073 FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim())));
5074
5075 // Add a boolean constant operand for "required" (true) or "hint" (false)
5076 // for implementing the work_group_size_hint attr later. Currently
5077 // always true as the hint is not yet implemented.
Chris Lattner8b418682012-02-07 00:39:47 +00005078 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005079 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5080 }
5081 }
5082 }
5083}
5084
5085}
John McCallaeeb7012010-05-27 06:19:26 +00005086
Tony Linthicum96319392011-12-12 21:14:55 +00005087//===----------------------------------------------------------------------===//
5088// Hexagon ABI Implementation
5089//===----------------------------------------------------------------------===//
5090
5091namespace {
5092
5093class HexagonABIInfo : public ABIInfo {
5094
5095
5096public:
5097 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5098
5099private:
5100
5101 ABIArgInfo classifyReturnType(QualType RetTy) const;
5102 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5103
5104 virtual void computeInfo(CGFunctionInfo &FI) const;
5105
5106 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5107 CodeGenFunction &CGF) const;
5108};
5109
5110class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5111public:
5112 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5113 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5114
5115 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5116 return 29;
5117 }
5118};
5119
5120}
5121
5122void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5123 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5124 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5125 it != ie; ++it)
5126 it->info = classifyArgumentType(it->type);
5127}
5128
5129ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5130 if (!isAggregateTypeForABI(Ty)) {
5131 // Treat an enum type as its underlying type.
5132 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5133 Ty = EnumTy->getDecl()->getIntegerType();
5134
5135 return (Ty->isPromotableIntegerType() ?
5136 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5137 }
5138
5139 // Ignore empty records.
5140 if (isEmptyRecord(getContext(), Ty, true))
5141 return ABIArgInfo::getIgnore();
5142
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005143 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
5144 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum96319392011-12-12 21:14:55 +00005145
5146 uint64_t Size = getContext().getTypeSize(Ty);
5147 if (Size > 64)
5148 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5149 // Pass in the smallest viable integer type.
5150 else if (Size > 32)
5151 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5152 else if (Size > 16)
5153 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5154 else if (Size > 8)
5155 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5156 else
5157 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5158}
5159
5160ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5161 if (RetTy->isVoidType())
5162 return ABIArgInfo::getIgnore();
5163
5164 // Large vector types should be returned via memory.
5165 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5166 return ABIArgInfo::getIndirect(0);
5167
5168 if (!isAggregateTypeForABI(RetTy)) {
5169 // Treat an enum type as its underlying type.
5170 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5171 RetTy = EnumTy->getDecl()->getIntegerType();
5172
5173 return (RetTy->isPromotableIntegerType() ?
5174 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5175 }
5176
5177 // Structures with either a non-trivial destructor or a non-trivial
5178 // copy constructor are always indirect.
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005179 if (isRecordReturnIndirect(RetTy, CGT))
Tony Linthicum96319392011-12-12 21:14:55 +00005180 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5181
5182 if (isEmptyRecord(getContext(), RetTy, true))
5183 return ABIArgInfo::getIgnore();
5184
5185 // Aggregates <= 8 bytes are returned in r0; other aggregates
5186 // are returned indirectly.
5187 uint64_t Size = getContext().getTypeSize(RetTy);
5188 if (Size <= 64) {
5189 // Return in the smallest viable integer type.
5190 if (Size <= 8)
5191 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5192 if (Size <= 16)
5193 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5194 if (Size <= 32)
5195 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5196 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5197 }
5198
5199 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5200}
5201
5202llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner8b418682012-02-07 00:39:47 +00005203 CodeGenFunction &CGF) const {
Tony Linthicum96319392011-12-12 21:14:55 +00005204 // FIXME: Need to handle alignment
Chris Lattner8b418682012-02-07 00:39:47 +00005205 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum96319392011-12-12 21:14:55 +00005206
5207 CGBuilderTy &Builder = CGF.Builder;
5208 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5209 "ap");
5210 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5211 llvm::Type *PTy =
5212 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5213 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5214
5215 uint64_t Offset =
5216 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5217 llvm::Value *NextAddr =
5218 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5219 "ap.next");
5220 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5221
5222 return AddrTyped;
5223}
5224
5225
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005226//===----------------------------------------------------------------------===//
5227// SPARC v9 ABI Implementation.
5228// Based on the SPARC Compliance Definition version 2.4.1.
5229//
5230// Function arguments a mapped to a nominal "parameter array" and promoted to
5231// registers depending on their type. Each argument occupies 8 or 16 bytes in
5232// the array, structs larger than 16 bytes are passed indirectly.
5233//
5234// One case requires special care:
5235//
5236// struct mixed {
5237// int i;
5238// float f;
5239// };
5240//
5241// When a struct mixed is passed by value, it only occupies 8 bytes in the
5242// parameter array, but the int is passed in an integer register, and the float
5243// is passed in a floating point register. This is represented as two arguments
5244// with the LLVM IR inreg attribute:
5245//
5246// declare void f(i32 inreg %i, float inreg %f)
5247//
5248// The code generator will only allocate 4 bytes from the parameter array for
5249// the inreg arguments. All other arguments are allocated a multiple of 8
5250// bytes.
5251//
5252namespace {
5253class SparcV9ABIInfo : public ABIInfo {
5254public:
5255 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5256
5257private:
5258 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5259 virtual void computeInfo(CGFunctionInfo &FI) const;
5260 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5261 CodeGenFunction &CGF) const;
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00005262
5263 // Coercion type builder for structs passed in registers. The coercion type
5264 // serves two purposes:
5265 //
5266 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5267 // in registers.
5268 // 2. Expose aligned floating point elements as first-level elements, so the
5269 // code generator knows to pass them in floating point registers.
5270 //
5271 // We also compute the InReg flag which indicates that the struct contains
5272 // aligned 32-bit floats.
5273 //
5274 struct CoerceBuilder {
5275 llvm::LLVMContext &Context;
5276 const llvm::DataLayout &DL;
5277 SmallVector<llvm::Type*, 8> Elems;
5278 uint64_t Size;
5279 bool InReg;
5280
5281 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5282 : Context(c), DL(dl), Size(0), InReg(false) {}
5283
5284 // Pad Elems with integers until Size is ToSize.
5285 void pad(uint64_t ToSize) {
5286 assert(ToSize >= Size && "Cannot remove elements");
5287 if (ToSize == Size)
5288 return;
5289
5290 // Finish the current 64-bit word.
5291 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5292 if (Aligned > Size && Aligned <= ToSize) {
5293 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5294 Size = Aligned;
5295 }
5296
5297 // Add whole 64-bit words.
5298 while (Size + 64 <= ToSize) {
5299 Elems.push_back(llvm::Type::getInt64Ty(Context));
5300 Size += 64;
5301 }
5302
5303 // Final in-word padding.
5304 if (Size < ToSize) {
5305 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5306 Size = ToSize;
5307 }
5308 }
5309
5310 // Add a floating point element at Offset.
5311 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5312 // Unaligned floats are treated as integers.
5313 if (Offset % Bits)
5314 return;
5315 // The InReg flag is only required if there are any floats < 64 bits.
5316 if (Bits < 64)
5317 InReg = true;
5318 pad(Offset);
5319 Elems.push_back(Ty);
5320 Size = Offset + Bits;
5321 }
5322
5323 // Add a struct type to the coercion type, starting at Offset (in bits).
5324 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5325 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5326 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5327 llvm::Type *ElemTy = StrTy->getElementType(i);
5328 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5329 switch (ElemTy->getTypeID()) {
5330 case llvm::Type::StructTyID:
5331 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5332 break;
5333 case llvm::Type::FloatTyID:
5334 addFloat(ElemOffset, ElemTy, 32);
5335 break;
5336 case llvm::Type::DoubleTyID:
5337 addFloat(ElemOffset, ElemTy, 64);
5338 break;
5339 case llvm::Type::FP128TyID:
5340 addFloat(ElemOffset, ElemTy, 128);
5341 break;
5342 case llvm::Type::PointerTyID:
5343 if (ElemOffset % 64 == 0) {
5344 pad(ElemOffset);
5345 Elems.push_back(ElemTy);
5346 Size += 64;
5347 }
5348 break;
5349 default:
5350 break;
5351 }
5352 }
5353 }
5354
5355 // Check if Ty is a usable substitute for the coercion type.
5356 bool isUsableType(llvm::StructType *Ty) const {
5357 if (Ty->getNumElements() != Elems.size())
5358 return false;
5359 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5360 if (Elems[i] != Ty->getElementType(i))
5361 return false;
5362 return true;
5363 }
5364
5365 // Get the coercion type as a literal struct type.
5366 llvm::Type *getType() const {
5367 if (Elems.size() == 1)
5368 return Elems.front();
5369 else
5370 return llvm::StructType::get(Context, Elems);
5371 }
5372 };
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005373};
5374} // end anonymous namespace
5375
5376ABIArgInfo
5377SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5378 if (Ty->isVoidType())
5379 return ABIArgInfo::getIgnore();
5380
5381 uint64_t Size = getContext().getTypeSize(Ty);
5382
5383 // Anything too big to fit in registers is passed with an explicit indirect
5384 // pointer / sret pointer.
5385 if (Size > SizeLimit)
5386 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5387
5388 // Treat an enum type as its underlying type.
5389 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5390 Ty = EnumTy->getDecl()->getIntegerType();
5391
5392 // Integer types smaller than a register are extended.
5393 if (Size < 64 && Ty->isIntegerType())
5394 return ABIArgInfo::getExtend();
5395
5396 // Other non-aggregates go in registers.
5397 if (!isAggregateTypeForABI(Ty))
5398 return ABIArgInfo::getDirect();
5399
5400 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00005401 // Build a coercion type from the LLVM struct type.
5402 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5403 if (!StrTy)
5404 return ABIArgInfo::getDirect();
5405
5406 CoerceBuilder CB(getVMContext(), getDataLayout());
5407 CB.addStruct(0, StrTy);
5408 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5409
5410 // Try to use the original type for coercion.
5411 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5412
5413 if (CB.InReg)
5414 return ABIArgInfo::getDirectInReg(CoerceTy);
5415 else
5416 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005417}
5418
5419llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5420 CodeGenFunction &CGF) const {
Jakob Stoklund Olesena4b56d32013-06-05 03:00:18 +00005421 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5422 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5423 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5424 AI.setCoerceToType(ArgTy);
5425
5426 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5427 CGBuilderTy &Builder = CGF.Builder;
5428 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5429 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5430 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5431 llvm::Value *ArgAddr;
5432 unsigned Stride;
5433
5434 switch (AI.getKind()) {
5435 case ABIArgInfo::Expand:
5436 llvm_unreachable("Unsupported ABI kind for va_arg");
5437
5438 case ABIArgInfo::Extend:
5439 Stride = 8;
5440 ArgAddr = Builder
5441 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5442 "extend");
5443 break;
5444
5445 case ABIArgInfo::Direct:
5446 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5447 ArgAddr = Addr;
5448 break;
5449
5450 case ABIArgInfo::Indirect:
5451 Stride = 8;
5452 ArgAddr = Builder.CreateBitCast(Addr,
5453 llvm::PointerType::getUnqual(ArgPtrTy),
5454 "indirect");
5455 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5456 break;
5457
5458 case ABIArgInfo::Ignore:
5459 return llvm::UndefValue::get(ArgPtrTy);
5460 }
5461
5462 // Update VAList.
5463 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5464 Builder.CreateStore(Addr, VAListAddrAsBPP);
5465
5466 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005467}
5468
5469void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5470 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5471 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5472 it != ie; ++it)
5473 it->info = classifyType(it->type, 16 * 8);
5474}
5475
5476namespace {
5477class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5478public:
5479 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5480 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
5481};
5482} // end anonymous namespace
5483
5484
Chris Lattnerea044322010-07-29 02:01:43 +00005485const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005486 if (TheTargetCodeGenInfo)
5487 return *TheTargetCodeGenInfo;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005488
John McCall64aa4b32013-04-16 22:48:15 +00005489 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar1752ee42009-08-24 09:10:05 +00005490 switch (Triple.getArch()) {
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005491 default:
Chris Lattnerea044322010-07-29 02:01:43 +00005492 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005493
Derek Schuff9ed63f82012-09-06 17:37:28 +00005494 case llvm::Triple::le32:
5495 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCallaeeb7012010-05-27 06:19:26 +00005496 case llvm::Triple::mips:
5497 case llvm::Triple::mipsel:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005498 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
John McCallaeeb7012010-05-27 06:19:26 +00005499
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00005500 case llvm::Triple::mips64:
5501 case llvm::Triple::mips64el:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005502 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00005503
Tim Northoverc264e162013-01-31 12:13:10 +00005504 case llvm::Triple::aarch64:
5505 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5506
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005507 case llvm::Triple::arm:
5508 case llvm::Triple::thumb:
Sandeep Patel34c1af82011-04-05 00:23:47 +00005509 {
5510 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCall64aa4b32013-04-16 22:48:15 +00005511 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel34c1af82011-04-05 00:23:47 +00005512 Kind = ARMABIInfo::APCS;
David Tweedb16abb12012-10-25 13:33:01 +00005513 else if (CodeGenOpts.FloatABI == "hard" ||
John McCall64aa4b32013-04-16 22:48:15 +00005514 (CodeGenOpts.FloatABI != "soft" &&
5515 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel34c1af82011-04-05 00:23:47 +00005516 Kind = ARMABIInfo::AAPCS_VFP;
5517
Derek Schuff263366f2012-10-16 22:30:41 +00005518 switch (Triple.getOS()) {
Eli Bendersky441d9f72012-12-04 18:38:10 +00005519 case llvm::Triple::NaCl:
Derek Schuff263366f2012-10-16 22:30:41 +00005520 return *(TheTargetCodeGenInfo =
5521 new NaClARMTargetCodeGenInfo(Types, Kind));
5522 default:
5523 return *(TheTargetCodeGenInfo =
5524 new ARMTargetCodeGenInfo(Types, Kind));
5525 }
Sandeep Patel34c1af82011-04-05 00:23:47 +00005526 }
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005527
John McCallec853ba2010-03-11 00:10:12 +00005528 case llvm::Triple::ppc:
Chris Lattnerea044322010-07-29 02:01:43 +00005529 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divacky0fbc4b92012-05-09 18:22:46 +00005530 case llvm::Triple::ppc64:
Bill Schmidt2fc107f2012-10-03 19:18:57 +00005531 if (Triple.isOSBinFormatELF())
5532 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5533 else
5534 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
John McCallec853ba2010-03-11 00:10:12 +00005535
Peter Collingbourneedb66f32012-05-20 23:28:41 +00005536 case llvm::Triple::nvptx:
5537 case llvm::Triple::nvptx64:
Justin Holewinski2c585b92012-05-24 17:43:12 +00005538 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005539
Wesley Peck276fdf42010-12-19 19:57:51 +00005540 case llvm::Triple::mblaze:
5541 return *(TheTargetCodeGenInfo = new MBlazeTargetCodeGenInfo(Types));
5542
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005543 case llvm::Triple::msp430:
Chris Lattnerea044322010-07-29 02:01:43 +00005544 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005545
Ulrich Weigandb8409212013-05-06 16:26:41 +00005546 case llvm::Triple::systemz:
5547 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5548
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005549 case llvm::Triple::tce:
5550 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5551
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00005552 case llvm::Triple::x86: {
John McCallb8b52972013-06-18 02:46:29 +00005553 bool IsDarwinVectorABI = Triple.isOSDarwin();
5554 bool IsSmallStructInRegABI =
5555 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5556 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbardb57a4c2011-04-19 21:43:27 +00005557
John McCallb8b52972013-06-18 02:46:29 +00005558 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedman55fc7e22012-01-25 22:46:34 +00005559 return *(TheTargetCodeGenInfo =
Reid Kleckner3190ca92013-05-08 13:44:39 +00005560 new WinX86_32TargetCodeGenInfo(Types,
John McCallb8b52972013-06-18 02:46:29 +00005561 IsDarwinVectorABI, IsSmallStructInRegABI,
5562 IsWin32FloatStructABI,
Reid Kleckner3190ca92013-05-08 13:44:39 +00005563 CodeGenOpts.NumRegisterParameters));
John McCallb8b52972013-06-18 02:46:29 +00005564 } else {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005565 return *(TheTargetCodeGenInfo =
John McCallb8b52972013-06-18 02:46:29 +00005566 new X86_32TargetCodeGenInfo(Types,
5567 IsDarwinVectorABI, IsSmallStructInRegABI,
5568 IsWin32FloatStructABI,
Rafael Espindolab48280b2012-07-31 02:44:24 +00005569 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005570 }
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00005571 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005572
Eli Friedmanee1ad992011-12-02 00:11:43 +00005573 case llvm::Triple::x86_64: {
John McCall64aa4b32013-04-16 22:48:15 +00005574 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanee1ad992011-12-02 00:11:43 +00005575
Chris Lattnerf13721d2010-08-31 16:44:54 +00005576 switch (Triple.getOS()) {
5577 case llvm::Triple::Win32:
NAKAMURA Takumi0aa20572011-02-17 08:51:38 +00005578 case llvm::Triple::MinGW32:
Chris Lattnerf13721d2010-08-31 16:44:54 +00005579 case llvm::Triple::Cygwin:
5580 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Bendersky441d9f72012-12-04 18:38:10 +00005581 case llvm::Triple::NaCl:
John McCall64aa4b32013-04-16 22:48:15 +00005582 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5583 HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00005584 default:
Eli Friedmanee1ad992011-12-02 00:11:43 +00005585 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5586 HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00005587 }
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005588 }
Tony Linthicum96319392011-12-12 21:14:55 +00005589 case llvm::Triple::hexagon:
5590 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005591 case llvm::Triple::sparcv9:
5592 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Eli Friedmanee1ad992011-12-02 00:11:43 +00005593 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005594}