blob: c602b1f1db846358c87171c8ae405908438f21b7 [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"
Mark Lacey8b549992013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel34c1af82011-04-05 00:23:47 +000021#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar2c0843f2009-08-24 08:52:16 +000022#include "llvm/ADT/Triple.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Type.h"
Daniel Dunbar28df7a52009-12-03 09:13:49 +000025#include "llvm/Support/raw_ostream.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000026using namespace clang;
27using namespace CodeGen;
28
John McCallaeeb7012010-05-27 06:19:26 +000029static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
30 llvm::Value *Array,
31 llvm::Value *Value,
32 unsigned FirstIndex,
33 unsigned LastIndex) {
34 // Alternatively, we could emit this as a loop in the source.
35 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
36 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
37 Builder.CreateStore(Value, Cell);
38 }
39}
40
John McCalld608cdb2010-08-22 10:59:02 +000041static bool isAggregateTypeForABI(QualType T) {
John McCall9d232c82013-03-07 21:37:08 +000042 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalld608cdb2010-08-22 10:59:02 +000043 T->isMemberFunctionPointerType();
44}
45
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000046ABIInfo::~ABIInfo() {}
47
Mark Lacey23630722013-10-06 01:33:34 +000048static bool isRecordReturnIndirect(const RecordType *RT,
49 CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000050 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
51 if (!RD)
52 return false;
Mark Lacey23630722013-10-06 01:33:34 +000053 return CXXABI.isReturnTypeIndirect(RD);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000054}
55
56
Mark Lacey23630722013-10-06 01:33:34 +000057static bool isRecordReturnIndirect(QualType T, CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000058 const RecordType *RT = T->getAs<RecordType>();
59 if (!RT)
60 return false;
Mark Lacey23630722013-10-06 01:33:34 +000061 return isRecordReturnIndirect(RT, CXXABI);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000062}
63
64static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey23630722013-10-06 01:33:34 +000065 CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000066 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
67 if (!RD)
68 return CGCXXABI::RAA_Default;
Mark Lacey23630722013-10-06 01:33:34 +000069 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000070}
71
72static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey23630722013-10-06 01:33:34 +000073 CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000074 const RecordType *RT = T->getAs<RecordType>();
75 if (!RT)
76 return CGCXXABI::RAA_Default;
Mark Lacey23630722013-10-06 01:33:34 +000077 return getRecordArgABI(RT, CXXABI);
78}
79
80CGCXXABI &ABIInfo::getCXXABI() const {
81 return CGT.getCXXABI();
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000082}
83
Chris Lattnerea044322010-07-29 02:01:43 +000084ASTContext &ABIInfo::getContext() const {
85 return CGT.getContext();
86}
87
88llvm::LLVMContext &ABIInfo::getVMContext() const {
89 return CGT.getLLVMContext();
90}
91
Micah Villmow25a6a842012-10-08 16:25:52 +000092const llvm::DataLayout &ABIInfo::getDataLayout() const {
93 return CGT.getDataLayout();
Chris Lattnerea044322010-07-29 02:01:43 +000094}
95
John McCall64aa4b32013-04-16 22:48:15 +000096const TargetInfo &ABIInfo::getTarget() const {
97 return CGT.getTarget();
98}
Chris Lattnerea044322010-07-29 02:01:43 +000099
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000100void ABIArgInfo::dump() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000101 raw_ostream &OS = llvm::errs();
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000102 OS << "(ABIArgInfo Kind=";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000103 switch (TheKind) {
104 case Direct:
Chris Lattner800588f2010-07-29 06:26:06 +0000105 OS << "Direct Type=";
Chris Lattner2acc6e32011-07-18 04:24:23 +0000106 if (llvm::Type *Ty = getCoerceToType())
Chris Lattner800588f2010-07-29 06:26:06 +0000107 Ty->print(OS);
108 else
109 OS << "null";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000110 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000111 case Extend:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000112 OS << "Extend";
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000113 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000114 case Ignore:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000115 OS << "Ignore";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000116 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700117 case InAlloca:
118 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
119 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000120 case Indirect:
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000121 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenbergere9b5d772011-07-15 18:23:44 +0000122 << " ByVal=" << getIndirectByVal()
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000123 << " Realign=" << getIndirectRealign();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000124 break;
125 case Expand:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000126 OS << "Expand";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000127 break;
128 }
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000129 OS << ")\n";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000130}
131
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000132TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
133
John McCall49e34be2011-08-30 01:42:09 +0000134// If someone can figure out a general rule for this, that would be great.
135// It's probably just doomed to be platform-dependent, though.
136unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
137 // Verified for:
138 // x86-64 FreeBSD, Linux, Darwin
139 // x86-32 FreeBSD, Linux, Darwin
140 // PowerPC Linux, Darwin
141 // ARM Darwin (*not* EABI)
Tim Northoverc264e162013-01-31 12:13:10 +0000142 // AArch64 Linux
John McCall49e34be2011-08-30 01:42:09 +0000143 return 32;
144}
145
John McCallde5d3c72012-02-17 03:33:10 +0000146bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
147 const FunctionNoProtoType *fnType) const {
John McCall01f151e2011-09-21 08:08:30 +0000148 // The following conventions are known to require this to be false:
149 // x86_stdcall
150 // MIPS
151 // For everything else, we just prefer false unless we opt out.
152 return false;
153}
154
Reid Kleckner3190ca92013-05-08 13:44:39 +0000155void
156TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
157 llvm::SmallString<24> &Opt) const {
158 // This assumes the user is passing a library name like "rt" instead of a
159 // filename like "librt.a/so", and that they don't care whether it's static or
160 // dynamic.
161 Opt = "-l";
162 Opt += Lib;
163}
164
Daniel Dunbar98303b92009-09-13 08:03:58 +0000165static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000166
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000167/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000168/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar98303b92009-09-13 08:03:58 +0000169static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
170 bool AllowArrays) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000171 if (FD->isUnnamedBitfield())
172 return true;
173
174 QualType FT = FD->getType();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000175
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000176 // Constant arrays of empty records count as empty, strip them off.
177 // Constant arrays of zero length always count as empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000178 if (AllowArrays)
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000179 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
180 if (AT->getSize() == 0)
181 return true;
Daniel Dunbar98303b92009-09-13 08:03:58 +0000182 FT = AT->getElementType();
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000183 }
Daniel Dunbar98303b92009-09-13 08:03:58 +0000184
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000185 const RecordType *RT = FT->getAs<RecordType>();
186 if (!RT)
187 return false;
188
189 // C++ record fields are never empty, at least in the Itanium ABI.
190 //
191 // FIXME: We should use a predicate for whether this behavior is true in the
192 // current ABI.
193 if (isa<CXXRecordDecl>(RT->getDecl()))
194 return false;
195
Daniel Dunbar98303b92009-09-13 08:03:58 +0000196 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000197}
198
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000199/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000200/// fields. Note that a structure with a flexible array member is not
201/// considered empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000202static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000203 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000204 if (!RT)
205 return 0;
206 const RecordDecl *RD = RT->getDecl();
207 if (RD->hasFlexibleArrayMember())
208 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000209
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000210 // If this is a C++ record, check the bases first.
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000211 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Stephen Hines651f13c2014-04-23 16:59:28 -0700212 for (const auto &I : CXXRD->bases())
213 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000214 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000215
Stephen Hines651f13c2014-04-23 16:59:28 -0700216 for (const auto *I : RD->fields())
217 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000218 return false;
219 return true;
220}
221
222/// isSingleElementStruct - Determine if a structure is a "single
223/// element struct", i.e. it has exactly one non-empty field or
224/// exactly one field which is itself a single element
225/// struct. Structures with flexible array members are never
226/// considered single element structs.
227///
228/// \return The field declaration for the single non-empty field, if
229/// it exists.
230static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
231 const RecordType *RT = T->getAsStructureType();
232 if (!RT)
233 return 0;
234
235 const RecordDecl *RD = RT->getDecl();
236 if (RD->hasFlexibleArrayMember())
237 return 0;
238
239 const Type *Found = 0;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000240
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000241 // If this is a C++ record, check the bases first.
242 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700243 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000244 // Ignore empty records.
Stephen Hines651f13c2014-04-23 16:59:28 -0700245 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000246 continue;
247
248 // If we already found an element then this isn't a single-element struct.
249 if (Found)
250 return 0;
251
252 // If this is non-empty and not a single element struct, the composite
253 // cannot be a single element struct.
Stephen Hines651f13c2014-04-23 16:59:28 -0700254 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000255 if (!Found)
256 return 0;
257 }
258 }
259
260 // Check for single element.
Stephen Hines651f13c2014-04-23 16:59:28 -0700261 for (const auto *FD : RD->fields()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000262 QualType FT = FD->getType();
263
264 // Ignore empty fields.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000265 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000266 continue;
267
268 // If we already found an element then this isn't a single-element
269 // struct.
270 if (Found)
271 return 0;
272
273 // Treat single element arrays as the element.
274 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
275 if (AT->getSize().getZExtValue() != 1)
276 break;
277 FT = AT->getElementType();
278 }
279
John McCalld608cdb2010-08-22 10:59:02 +0000280 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000281 Found = FT.getTypePtr();
282 } else {
283 Found = isSingleElementStruct(FT, Context);
284 if (!Found)
285 return 0;
286 }
287 }
288
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000289 // We don't consider a struct a single-element struct if it has
290 // padding beyond the element type.
291 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
292 return 0;
293
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000294 return Found;
295}
296
297static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmandb748a32012-11-29 23:21:04 +0000298 // Treat complex types as the element type.
299 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
300 Ty = CTy->getElementType();
301
302 // Check for a type which we know has a simple scalar argument-passing
303 // convention without any padding. (We're specifically looking for 32
304 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbara1842d32010-05-14 03:40:53 +0000305 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmandb748a32012-11-29 23:21:04 +0000306 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000307 return false;
308
309 uint64_t Size = Context.getTypeSize(Ty);
310 return Size == 32 || Size == 64;
311}
312
Daniel Dunbar53012f42009-11-09 01:33:53 +0000313/// canExpandIndirectArgument - Test whether an argument type which is to be
314/// passed indirectly (on the stack) would have the equivalent layout if it was
315/// expanded into separate arguments. If so, we prefer to do the latter to avoid
316/// inhibiting optimizations.
317///
318// FIXME: This predicate is missing many cases, currently it just follows
319// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
320// should probably make this smarter, or better yet make the LLVM backend
321// capable of handling it.
322static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
323 // We can only expand structure types.
324 const RecordType *RT = Ty->getAs<RecordType>();
325 if (!RT)
326 return false;
327
328 // We can only expand (C) structures.
329 //
330 // FIXME: This needs to be generalized to handle classes as well.
331 const RecordDecl *RD = RT->getDecl();
332 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
333 return false;
334
Eli Friedman506d4e32011-11-18 01:32:26 +0000335 uint64_t Size = 0;
336
Stephen Hines651f13c2014-04-23 16:59:28 -0700337 for (const auto *FD : RD->fields()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000338 if (!is32Or64BitBasicType(FD->getType(), Context))
339 return false;
340
341 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
342 // how to expand them yet, and the predicate for telling if a bitfield still
343 // counts as "basic" is more complicated than what we were doing previously.
344 if (FD->isBitField())
345 return false;
Eli Friedman506d4e32011-11-18 01:32:26 +0000346
347 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000348 }
349
Eli Friedman506d4e32011-11-18 01:32:26 +0000350 // Make sure there are not any holes in the struct.
351 if (Size != Context.getTypeSize(Ty))
352 return false;
353
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000354 return true;
355}
356
357namespace {
358/// DefaultABIInfo - The default implementation for ABI specific
359/// details. This implementation provides information which results in
360/// self-consistent and sensible LLVM IR generation, but does not
361/// conform to any particular ABI.
362class DefaultABIInfo : public ABIInfo {
Chris Lattnerea044322010-07-29 02:01:43 +0000363public:
364 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000365
Chris Lattnera3c109b2010-07-29 02:16:43 +0000366 ABIArgInfo classifyReturnType(QualType RetTy) const;
367 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000368
Stephen Hines651f13c2014-04-23 16:59:28 -0700369 void computeInfo(CGFunctionInfo &FI) const override {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000370 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -0700371 for (auto &I : FI.arguments())
372 I.info = classifyArgumentType(I.type);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000373 }
374
Stephen Hines651f13c2014-04-23 16:59:28 -0700375 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
376 CodeGenFunction &CGF) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000377};
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)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700392 // Records with non-trivial destructors/constructors should not be passed
Jan Wen Voung90306932011-11-03 00:59:44 +0000393 // by value.
Mark Lacey23630722013-10-06 01:33:34 +0000394 if (isRecordReturnIndirect(Ty, getCXXABI()))
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
Stephen Hines651f13c2014-04-23 16:59:28 -0700437 void computeInfo(CGFunctionInfo &FI) const override;
438 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
439 CodeGenFunction &CGF) const override;
Derek Schuff9ed63f82012-09-06 17:37:28 +0000440};
441
442class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
443 public:
444 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
445 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
446};
447
448void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
449 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
450
Stephen Hines651f13c2014-04-23 16:59:28 -0700451 for (auto &I : FI.arguments())
452 I.info = classifyArgumentType(I.type);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000453 }
454
455llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
456 CodeGenFunction &CGF) const {
457 return 0;
458}
459
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000460/// \brief Classify argument of given type \p Ty.
461ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff9ed63f82012-09-06 17:37:28 +0000462 if (isAggregateTypeForABI(Ty)) {
Mark Lacey23630722013-10-06 01:33:34 +0000463 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000464 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000465 return ABIArgInfo::getIndirect(0);
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000466 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
467 // Treat an enum type as its underlying type.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000468 Ty = EnumTy->getDecl()->getIntegerType();
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000469 } else if (Ty->isFloatingType()) {
470 // Floating-point types don't go inreg.
471 return ABIArgInfo::getDirect();
Derek Schuff9ed63f82012-09-06 17:37:28 +0000472 }
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000473
474 return (Ty->isPromotableIntegerType() ?
475 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff9ed63f82012-09-06 17:37:28 +0000476}
477
478ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
479 if (RetTy->isVoidType())
480 return ABIArgInfo::getIgnore();
481
Eli Benderskye45dfd12013-04-04 22:49:35 +0000482 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000483 if (isAggregateTypeForABI(RetTy))
484 return ABIArgInfo::getIndirect(0);
485
486 // Treat an enum type as its underlying type.
487 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
488 RetTy = EnumTy->getDecl()->getIntegerType();
489
490 return (RetTy->isPromotableIntegerType() ?
491 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
492}
493
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000494/// IsX86_MMXType - Return true if this is an MMX type.
495bool IsX86_MMXType(llvm::Type *IRType) {
496 // 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 +0000497 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
498 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
499 IRType->getScalarSizeInBits() != 64;
500}
501
Jay Foadef6de3d2011-07-11 09:56:20 +0000502static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000503 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000504 llvm::Type* Ty) {
Tim Northover1bea6532013-06-07 00:04:50 +0000505 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
506 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
507 // Invalid MMX constraint
508 return 0;
509 }
510
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000511 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover1bea6532013-06-07 00:04:50 +0000512 }
513
514 // No operation needed
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000515 return Ty;
516}
517
Chris Lattnerdce5ad02010-06-28 20:05:43 +0000518//===----------------------------------------------------------------------===//
519// X86-32 ABI Implementation
520//===----------------------------------------------------------------------===//
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000521
Stephen Hines651f13c2014-04-23 16:59:28 -0700522/// \brief Similar to llvm::CCState, but for Clang.
523struct CCState {
524 CCState(unsigned CC) : CC(CC), FreeRegs(0) {}
525
526 unsigned CC;
527 unsigned FreeRegs;
528 unsigned StackOffset;
529 bool UseInAlloca;
530};
531
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000532/// X86_32ABIInfo - The X86-32 ABI information.
533class X86_32ABIInfo : public ABIInfo {
Rafael Espindolab48280b2012-07-31 02:44:24 +0000534 enum Class {
535 Integer,
536 Float
537 };
538
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000539 static const unsigned MinABIStackAlignInBytes = 4;
540
David Chisnall1e4249c2009-08-17 23:08:21 +0000541 bool IsDarwinVectorABI;
542 bool IsSmallStructInRegABI;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000543 bool IsWin32StructABI;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000544 unsigned DefaultNumRegisterParameters;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000545
546 static bool isRegisterSize(unsigned Size) {
547 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
548 }
549
Stephen Hines651f13c2014-04-23 16:59:28 -0700550 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
551 bool IsInstanceMethod) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000552
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000553 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
554 /// such that the argument will be passed in memory.
Stephen Hines651f13c2014-04-23 16:59:28 -0700555 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
556
557 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000558
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000559 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbare59d8582010-09-16 20:42:06 +0000560 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000561
Rafael Espindolab48280b2012-07-31 02:44:24 +0000562 Class classify(QualType Ty) const;
Stephen Hines651f13c2014-04-23 16:59:28 -0700563 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State,
564 bool IsInstanceMethod) const;
565 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
566 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
567
568 /// \brief Rewrite the function info so that all memory arguments use
569 /// inalloca.
570 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
571
572 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
573 unsigned &StackOffset, ABIArgInfo &Info,
574 QualType Type) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000575
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000576public:
577
Stephen Hines651f13c2014-04-23 16:59:28 -0700578 void computeInfo(CGFunctionInfo &FI) const override;
579 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
580 CodeGenFunction &CGF) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000581
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000582 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindolab48280b2012-07-31 02:44:24 +0000583 unsigned r)
Eli Friedmanc3e0fb42011-07-08 23:31:17 +0000584 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000585 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000586};
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000587
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000588class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
589public:
Eli Friedman55fc7e22012-01-25 22:46:34 +0000590 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000591 bool d, bool p, bool w, unsigned r)
592 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis74f72932010-02-13 15:54:06 +0000593
John McCallb8b52972013-06-18 02:46:29 +0000594 static bool isStructReturnInRegABI(
595 const llvm::Triple &Triple, const CodeGenOptions &Opts);
596
Charles Davis74f72932010-02-13 15:54:06 +0000597 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -0700598 CodeGen::CodeGenModule &CGM) const override;
John McCall6374c332010-03-06 00:35:14 +0000599
Stephen Hines651f13c2014-04-23 16:59:28 -0700600 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall6374c332010-03-06 00:35:14 +0000601 // Darwin uses different dwarf register numbers for EH.
John McCall64aa4b32013-04-16 22:48:15 +0000602 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCall6374c332010-03-06 00:35:14 +0000603 return 4;
604 }
605
606 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -0700607 llvm::Value *Address) const override;
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000608
Jay Foadef6de3d2011-07-11 09:56:20 +0000609 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000610 StringRef Constraint,
Stephen Hines651f13c2014-04-23 16:59:28 -0700611 llvm::Type* Ty) const override {
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000612 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
613 }
614
Stephen Hines651f13c2014-04-23 16:59:28 -0700615 llvm::Constant *
616 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb914e872013-10-20 21:29:19 +0000617 unsigned Sig = (0xeb << 0) | // jmp rel8
618 (0x06 << 8) | // .+0x08
619 ('F' << 16) |
620 ('T' << 24);
621 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
622 }
623
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000624};
625
626}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000627
628/// shouldReturnTypeInRegister - Determine if the given type should be
629/// passed in a register (for the Darwin ABI).
Stephen Hines651f13c2014-04-23 16:59:28 -0700630bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
631 bool IsInstanceMethod) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000632 uint64_t Size = Context.getTypeSize(Ty);
633
634 // Type must be register sized.
635 if (!isRegisterSize(Size))
636 return false;
637
638 if (Ty->isVectorType()) {
639 // 64- and 128- bit vectors inside structures are not returned in
640 // registers.
641 if (Size == 64 || Size == 128)
642 return false;
643
644 return true;
645 }
646
Daniel Dunbar77115232010-05-15 00:00:30 +0000647 // If this is a builtin, pointer, enum, complex type, member pointer, or
648 // member function pointer it is ok.
Daniel Dunbara1842d32010-05-14 03:40:53 +0000649 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbar55e59e12009-09-24 05:12:36 +0000650 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar77115232010-05-15 00:00:30 +0000651 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000652 return true;
653
654 // Arrays are treated like records.
655 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000656 return shouldReturnTypeInRegister(AT->getElementType(), Context,
Stephen Hines651f13c2014-04-23 16:59:28 -0700657 IsInstanceMethod);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000658
659 // Otherwise, it must be a record type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000660 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000661 if (!RT) return false;
662
Anders Carlssona8874232010-01-27 03:25:19 +0000663 // FIXME: Traverse bases here too.
664
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000665 // For thiscall conventions, structures will never be returned in
666 // a register. This is for compatibility with the MSVC ABI
Stephen Hines651f13c2014-04-23 16:59:28 -0700667 if (IsWin32StructABI && IsInstanceMethod && RT->isStructureType())
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000668 return false;
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000669
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000670 // Structure types are passed in register if all fields would be
671 // passed in a register.
Stephen Hines651f13c2014-04-23 16:59:28 -0700672 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000673 // Empty fields are ignored.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000674 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000675 continue;
676
677 // Check fields recursively.
Stephen Hines651f13c2014-04-23 16:59:28 -0700678 if (!shouldReturnTypeInRegister(FD->getType(), Context, IsInstanceMethod))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000679 return false;
680 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000681 return true;
682}
683
Stephen Hines651f13c2014-04-23 16:59:28 -0700684ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
685 // If the return value is indirect, then the hidden argument is consuming one
686 // integer register.
687 if (State.FreeRegs) {
688 --State.FreeRegs;
689 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
690 }
691 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
692}
693
694ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State,
695 bool IsInstanceMethod) const {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000696 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000697 return ABIArgInfo::getIgnore();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000698
Chris Lattnera3c109b2010-07-29 02:16:43 +0000699 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000700 // On Darwin, some vectors are returned in registers.
David Chisnall1e4249c2009-08-17 23:08:21 +0000701 if (IsDarwinVectorABI) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000702 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000703
704 // 128-bit vectors are a special case; they are returned in
705 // registers and we need to make sure to pick a type the LLVM
706 // backend will like.
707 if (Size == 128)
Chris Lattner800588f2010-07-29 06:26:06 +0000708 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattnera3c109b2010-07-29 02:16:43 +0000709 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000710
711 // Always return in register if it fits in a general purpose
712 // register, or if it is 64 bits and has a single element.
713 if ((Size == 8 || Size == 16 || Size == 32) ||
714 (Size == 64 && VT->getNumElements() == 1))
Chris Lattner800588f2010-07-29 06:26:06 +0000715 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +0000716 Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000717
Stephen Hines651f13c2014-04-23 16:59:28 -0700718 return getIndirectReturnResult(State);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000719 }
720
721 return ABIArgInfo::getDirect();
Chris Lattnera3c109b2010-07-29 02:16:43 +0000722 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000723
John McCalld608cdb2010-08-22 10:59:02 +0000724 if (isAggregateTypeForABI(RetTy)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000725 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Mark Lacey23630722013-10-06 01:33:34 +0000726 if (isRecordReturnIndirect(RT, getCXXABI()))
Stephen Hines651f13c2014-04-23 16:59:28 -0700727 return getIndirectReturnResult(State);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000728
Anders Carlsson40092972009-10-20 22:07:59 +0000729 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000730 if (RT->getDecl()->hasFlexibleArrayMember())
Stephen Hines651f13c2014-04-23 16:59:28 -0700731 return getIndirectReturnResult(State);
Anders Carlsson40092972009-10-20 22:07:59 +0000732 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000733
David Chisnall1e4249c2009-08-17 23:08:21 +0000734 // If specified, structs and unions are always indirect.
735 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Stephen Hines651f13c2014-04-23 16:59:28 -0700736 return getIndirectReturnResult(State);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000737
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000738 // Small structures which are register sized are generally returned
739 // in a register.
Stephen Hines651f13c2014-04-23 16:59:28 -0700740 if (shouldReturnTypeInRegister(RetTy, getContext(), IsInstanceMethod)) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000741 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000742
743 // As a special-case, if the struct is a "single-element" struct, and
744 // the field is of type "float" or "double", return it in a
Eli Friedman55fc7e22012-01-25 22:46:34 +0000745 // floating-point register. (MSVC does not apply this special case.)
746 // We apply a similar transformation for pointer types to improve the
747 // quality of the generated IR.
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000748 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000749 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedman55fc7e22012-01-25 22:46:34 +0000750 || SeltTy->hasPointerRepresentation())
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000751 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
752
753 // FIXME: We should be able to narrow this integer in cases with dead
754 // padding.
Chris Lattner800588f2010-07-29 06:26:06 +0000755 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000756 }
757
Stephen Hines651f13c2014-04-23 16:59:28 -0700758 return getIndirectReturnResult(State);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000759 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000760
Chris Lattnera3c109b2010-07-29 02:16:43 +0000761 // Treat an enum type as its underlying type.
762 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
763 RetTy = EnumTy->getDecl()->getIntegerType();
764
765 return (RetTy->isPromotableIntegerType() ?
766 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000767}
768
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000769static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
770 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
771}
772
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000773static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
774 const RecordType *RT = Ty->getAs<RecordType>();
775 if (!RT)
776 return 0;
777 const RecordDecl *RD = RT->getDecl();
778
779 // If this is a C++ record, check the bases first.
780 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Stephen Hines651f13c2014-04-23 16:59:28 -0700781 for (const auto &I : CXXRD->bases())
782 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000783 return false;
784
Stephen Hines651f13c2014-04-23 16:59:28 -0700785 for (const auto *i : RD->fields()) {
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000786 QualType FT = i->getType();
787
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000788 if (isSSEVectorType(Context, FT))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000789 return true;
790
791 if (isRecordWithSSEVectorType(Context, FT))
792 return true;
793 }
794
795 return false;
796}
797
Daniel Dunbare59d8582010-09-16 20:42:06 +0000798unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
799 unsigned Align) const {
800 // Otherwise, if the alignment is less than or equal to the minimum ABI
801 // alignment, just use the default; the backend will handle this.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000802 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbare59d8582010-09-16 20:42:06 +0000803 return 0; // Use default alignment.
804
805 // On non-Darwin, the stack type alignment is always 4.
806 if (!IsDarwinVectorABI) {
807 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000808 return MinABIStackAlignInBytes;
Daniel Dunbare59d8582010-09-16 20:42:06 +0000809 }
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000810
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000811 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000812 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
813 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000814 return 16;
815
816 return MinABIStackAlignInBytes;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000817}
818
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000819ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Stephen Hines651f13c2014-04-23 16:59:28 -0700820 CCState &State) const {
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000821 if (!ByVal) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700822 if (State.FreeRegs) {
823 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000824 return ABIArgInfo::getIndirectInReg(0, false);
825 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000826 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000827 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000828
Daniel Dunbare59d8582010-09-16 20:42:06 +0000829 // Compute the byval alignment.
830 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
831 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
832 if (StackAlign == 0)
Stephen Hines651f13c2014-04-23 16:59:28 -0700833 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbare59d8582010-09-16 20:42:06 +0000834
835 // If the stack alignment is less than the type alignment, realign the
836 // argument.
Stephen Hines651f13c2014-04-23 16:59:28 -0700837 bool Realign = TypeAlign > StackAlign;
838 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000839}
840
Rafael Espindolab48280b2012-07-31 02:44:24 +0000841X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
842 const Type *T = isSingleElementStruct(Ty, getContext());
843 if (!T)
844 T = Ty.getTypePtr();
845
846 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
847 BuiltinType::Kind K = BT->getKind();
848 if (K == BuiltinType::Float || K == BuiltinType::Double)
849 return Float;
850 }
851 return Integer;
852}
853
Stephen Hines651f13c2014-04-23 16:59:28 -0700854bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
855 bool &NeedsPadding) const {
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000856 NeedsPadding = false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000857 Class C = classify(Ty);
858 if (C == Float)
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000859 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000860
Rafael Espindolab6932692012-10-24 01:58:58 +0000861 unsigned Size = getContext().getTypeSize(Ty);
862 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindola5f14fcb2012-10-23 02:04:01 +0000863
864 if (SizeInRegs == 0)
865 return false;
866
Stephen Hines651f13c2014-04-23 16:59:28 -0700867 if (SizeInRegs > State.FreeRegs) {
868 State.FreeRegs = 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000869 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000870 }
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000871
Stephen Hines651f13c2014-04-23 16:59:28 -0700872 State.FreeRegs -= SizeInRegs;
Rafael Espindolab6932692012-10-24 01:58:58 +0000873
Stephen Hines651f13c2014-04-23 16:59:28 -0700874 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindolab6932692012-10-24 01:58:58 +0000875 if (Size > 32)
876 return false;
877
878 if (Ty->isIntegralOrEnumerationType())
879 return true;
880
881 if (Ty->isPointerType())
882 return true;
883
884 if (Ty->isReferenceType())
885 return true;
886
Stephen Hines651f13c2014-04-23 16:59:28 -0700887 if (State.FreeRegs)
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000888 NeedsPadding = true;
889
Rafael Espindolab6932692012-10-24 01:58:58 +0000890 return false;
891 }
892
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000893 return true;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000894}
895
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000896ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -0700897 CCState &State) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000898 // FIXME: Set alignment on indirect arguments.
John McCalld608cdb2010-08-22 10:59:02 +0000899 if (isAggregateTypeForABI(Ty)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000900 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700901 // Check with the C++ ABI first.
902 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
903 if (RAA == CGCXXABI::RAA_Indirect) {
904 return getIndirectResult(Ty, false, State);
905 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
906 // The field index doesn't matter, we'll fix it up later.
907 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
908 }
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000909
Stephen Hines651f13c2014-04-23 16:59:28 -0700910 // Structs are always byval on win32, regardless of what they contain.
911 if (IsWin32StructABI)
912 return getIndirectResult(Ty, true, State);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000913
914 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000915 if (RT->getDecl()->hasFlexibleArrayMember())
Stephen Hines651f13c2014-04-23 16:59:28 -0700916 return getIndirectResult(Ty, true, State);
Anders Carlssona8874232010-01-27 03:25:19 +0000917 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000918
Eli Friedman5a4d3522011-11-18 00:28:11 +0000919 // Ignore empty structs/unions.
Eli Friedman5a1ac892011-11-18 04:01:36 +0000920 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000921 return ABIArgInfo::getIgnore();
922
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000923 llvm::LLVMContext &LLVMContext = getVMContext();
924 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
925 bool NeedsPadding;
Stephen Hines651f13c2014-04-23 16:59:28 -0700926 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000927 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperb9bad792013-07-08 04:47:18 +0000928 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000929 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
930 return ABIArgInfo::getDirectInReg(Result);
931 }
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000932 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000933
Daniel Dunbar53012f42009-11-09 01:33:53 +0000934 // Expand small (<= 128-bit) record types when we know that the stack layout
935 // of those arguments will match the struct. This is important because the
936 // LLVM backend isn't smart enough to remove byval, which inhibits many
937 // optimizations.
Chris Lattnera3c109b2010-07-29 02:16:43 +0000938 if (getContext().getTypeSize(Ty) <= 4*32 &&
939 canExpandIndirectArgument(Ty, getContext()))
Stephen Hines651f13c2014-04-23 16:59:28 -0700940 return ABIArgInfo::getExpandWithPadding(
941 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000942
Stephen Hines651f13c2014-04-23 16:59:28 -0700943 return getIndirectResult(Ty, true, State);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000944 }
945
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000946 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner7b733502010-08-26 20:08:43 +0000947 // On Darwin, some vectors are passed in memory, we handle this by passing
948 // it as an i8/i16/i32/i64.
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000949 if (IsDarwinVectorABI) {
950 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000951 if ((Size == 8 || Size == 16 || Size == 32) ||
952 (Size == 64 && VT->getNumElements() == 1))
953 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
954 Size));
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000955 }
Bill Wendlingbb465d72010-10-18 03:41:31 +0000956
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000957 if (IsX86_MMXType(CGT.ConvertType(Ty)))
958 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000959
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000960 return ABIArgInfo::getDirect();
961 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000962
963
Chris Lattnera3c109b2010-07-29 02:16:43 +0000964 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
965 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000966
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000967 bool NeedsPadding;
Stephen Hines651f13c2014-04-23 16:59:28 -0700968 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000969
970 if (Ty->isPromotableIntegerType()) {
971 if (InReg)
972 return ABIArgInfo::getExtendInReg();
973 return ABIArgInfo::getExtend();
974 }
975 if (InReg)
976 return ABIArgInfo::getDirectInReg();
977 return ABIArgInfo::getDirect();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000978}
979
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000980void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines651f13c2014-04-23 16:59:28 -0700981 CCState State(FI.getCallingConvention());
982 if (State.CC == llvm::CallingConv::X86_FastCall)
983 State.FreeRegs = 2;
Rafael Espindolab6932692012-10-24 01:58:58 +0000984 else if (FI.getHasRegParm())
Stephen Hines651f13c2014-04-23 16:59:28 -0700985 State.FreeRegs = FI.getRegParm();
Rafael Espindolab6932692012-10-24 01:58:58 +0000986 else
Stephen Hines651f13c2014-04-23 16:59:28 -0700987 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000988
Stephen Hines651f13c2014-04-23 16:59:28 -0700989 FI.getReturnInfo() =
990 classifyReturnType(FI.getReturnType(), State, FI.isInstanceMethod());
991
992 // On win32, use the x86_cdeclmethodcc convention for cdecl methods that use
993 // sret. This convention swaps the order of the first two parameters behind
994 // the scenes to match MSVC.
995 if (IsWin32StructABI && FI.isInstanceMethod() &&
996 FI.getCallingConvention() == llvm::CallingConv::C &&
997 FI.getReturnInfo().isIndirect())
998 FI.setEffectiveCallingConvention(llvm::CallingConv::X86_CDeclMethod);
999
1000 bool UsedInAlloca = false;
1001 for (auto &I : FI.arguments()) {
1002 I.info = classifyArgumentType(I.type, State);
1003 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001004 }
1005
Stephen Hines651f13c2014-04-23 16:59:28 -07001006 // If we needed to use inalloca for any argument, do a second pass and rewrite
1007 // all the memory arguments to use inalloca.
1008 if (UsedInAlloca)
1009 rewriteWithInAlloca(FI);
1010}
1011
1012void
1013X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1014 unsigned &StackOffset,
1015 ABIArgInfo &Info, QualType Type) const {
1016 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1017 // byte aligned.
1018 unsigned Align = 4U;
1019 if (Info.getKind() == ABIArgInfo::Indirect && Info.getIndirectByVal())
1020 Align = std::max(Align, Info.getIndirectAlign());
1021 if (StackOffset & (Align - 1)) {
1022 unsigned OldOffset = StackOffset;
1023 StackOffset = llvm::RoundUpToAlignment(StackOffset, Align);
1024 unsigned NumBytes = StackOffset - OldOffset;
1025 assert(NumBytes);
1026 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1027 Ty = llvm::ArrayType::get(Ty, NumBytes);
1028 FrameFields.push_back(Ty);
1029 }
1030
1031 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1032 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1033 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1034}
1035
1036void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1037 assert(IsWin32StructABI && "inalloca only supported on win32");
1038
1039 // Build a packed struct type for all of the arguments in memory.
1040 SmallVector<llvm::Type *, 6> FrameFields;
1041
1042 unsigned StackOffset = 0;
1043
1044 // Put the sret parameter into the inalloca struct if it's in memory.
1045 ABIArgInfo &Ret = FI.getReturnInfo();
1046 if (Ret.isIndirect() && !Ret.getInReg()) {
1047 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1048 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1049 // On Windows, the hidden sret parameter is always returned in eax.
1050 Ret.setInAllocaSRet(IsWin32StructABI);
1051 }
1052
1053 // Skip the 'this' parameter in ecx.
1054 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1055 if (FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall)
1056 ++I;
1057
1058 // Put arguments passed in memory into the struct.
1059 for (; I != E; ++I) {
1060
1061 // Leave ignored and inreg arguments alone.
1062 switch (I->info.getKind()) {
1063 case ABIArgInfo::Indirect:
1064 assert(I->info.getIndirectByVal());
1065 break;
1066 case ABIArgInfo::Ignore:
1067 continue;
1068 case ABIArgInfo::Direct:
1069 case ABIArgInfo::Extend:
1070 if (I->info.getInReg())
1071 continue;
1072 break;
1073 default:
1074 break;
1075 }
1076
1077 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1078 }
1079
1080 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1081 /*isPacked=*/true));
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +00001082}
1083
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001084llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1085 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001086 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001087
1088 CGBuilderTy &Builder = CGF.Builder;
1089 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1090 "ap");
1091 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman7b1fb812011-11-18 02:12:09 +00001092
1093 // Compute if the address needs to be aligned
1094 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1095 Align = getTypeStackAlignInBytes(Ty, Align);
1096 Align = std::max(Align, 4U);
1097 if (Align > 4) {
1098 // addr = (addr + align - 1) & -align;
1099 llvm::Value *Offset =
1100 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1101 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1102 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1103 CGF.Int32Ty);
1104 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1105 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1106 Addr->getType(),
1107 "ap.cur.aligned");
1108 }
1109
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001110 llvm::Type *PTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001111 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001112 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1113
1114 uint64_t Offset =
Eli Friedman7b1fb812011-11-18 02:12:09 +00001115 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001116 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00001117 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001118 "ap.next");
1119 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1120
1121 return AddrTyped;
1122}
1123
Charles Davis74f72932010-02-13 15:54:06 +00001124void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1125 llvm::GlobalValue *GV,
1126 CodeGen::CodeGenModule &CGM) const {
1127 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1128 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1129 // Get the LLVM function.
1130 llvm::Function *Fn = cast<llvm::Function>(GV);
1131
1132 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendling0d583392012-10-15 20:36:26 +00001133 llvm::AttrBuilder B;
Bill Wendlinge91e9ec2012-10-14 03:28:14 +00001134 B.addStackAlignmentAttr(16);
Bill Wendling909b6de2013-01-23 00:21:06 +00001135 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1136 llvm::AttributeSet::get(CGM.getLLVMContext(),
1137 llvm::AttributeSet::FunctionIndex,
1138 B));
Charles Davis74f72932010-02-13 15:54:06 +00001139 }
1140 }
1141}
1142
John McCall6374c332010-03-06 00:35:14 +00001143bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1144 CodeGen::CodeGenFunction &CGF,
1145 llvm::Value *Address) const {
1146 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCall6374c332010-03-06 00:35:14 +00001147
Chris Lattner8b418682012-02-07 00:39:47 +00001148 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001149
John McCall6374c332010-03-06 00:35:14 +00001150 // 0-7 are the eight integer registers; the order is different
1151 // on Darwin (for EH), but the range is the same.
1152 // 8 is %eip.
John McCallaeeb7012010-05-27 06:19:26 +00001153 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCall6374c332010-03-06 00:35:14 +00001154
John McCall64aa4b32013-04-16 22:48:15 +00001155 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCall6374c332010-03-06 00:35:14 +00001156 // 12-16 are st(0..4). Not sure why we stop at 4.
1157 // These have size 16, which is sizeof(long double) on
1158 // platforms with 8-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001159 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCallaeeb7012010-05-27 06:19:26 +00001160 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001161
John McCall6374c332010-03-06 00:35:14 +00001162 } else {
1163 // 9 is %eflags, which doesn't get a size on Darwin for some
1164 // reason.
1165 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1166
1167 // 11-16 are st(0..5). Not sure why we stop at 5.
1168 // These have size 12, which is sizeof(long double) on
1169 // platforms with 4-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001170 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCallaeeb7012010-05-27 06:19:26 +00001171 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1172 }
John McCall6374c332010-03-06 00:35:14 +00001173
1174 return false;
1175}
1176
Chris Lattnerdce5ad02010-06-28 20:05:43 +00001177//===----------------------------------------------------------------------===//
1178// X86-64 ABI Implementation
1179//===----------------------------------------------------------------------===//
1180
1181
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001182namespace {
1183/// X86_64ABIInfo - The X86_64 ABI information.
1184class X86_64ABIInfo : public ABIInfo {
1185 enum Class {
1186 Integer = 0,
1187 SSE,
1188 SSEUp,
1189 X87,
1190 X87Up,
1191 ComplexX87,
1192 NoClass,
1193 Memory
1194 };
1195
1196 /// merge - Implement the X86_64 ABI merging algorithm.
1197 ///
1198 /// Merge an accumulating classification \arg Accum with a field
1199 /// classification \arg Field.
1200 ///
1201 /// \param Accum - The accumulating classification. This should
1202 /// always be either NoClass or the result of a previous merge
1203 /// call. In addition, this should never be Memory (the caller
1204 /// should just return Memory for the aggregate).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001205 static Class merge(Class Accum, Class Field);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001206
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001207 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1208 ///
1209 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1210 /// final MEMORY or SSE classes when necessary.
1211 ///
1212 /// \param AggregateSize - The size of the current aggregate in
1213 /// the classification process.
1214 ///
1215 /// \param Lo - The classification for the parts of the type
1216 /// residing in the low word of the containing object.
1217 ///
1218 /// \param Hi - The classification for the parts of the type
1219 /// residing in the higher words of the containing object.
1220 ///
1221 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1222
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001223 /// classify - Determine the x86_64 register classes in which the
1224 /// given type T should be passed.
1225 ///
1226 /// \param Lo - The classification for the parts of the type
1227 /// residing in the low word of the containing object.
1228 ///
1229 /// \param Hi - The classification for the parts of the type
1230 /// residing in the high word of the containing object.
1231 ///
1232 /// \param OffsetBase - The bit offset of this type in the
1233 /// containing object. Some parameters are classified different
1234 /// depending on whether they straddle an eightbyte boundary.
1235 ///
Eli Friedman7a1b5862013-06-12 00:13:45 +00001236 /// \param isNamedArg - Whether the argument in question is a "named"
1237 /// argument, as used in AMD64-ABI 3.5.7.
1238 ///
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001239 /// If a word is unused its result will be NoClass; if a type should
1240 /// be passed in Memory then at least the classification of \arg Lo
1241 /// will be Memory.
1242 ///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001243 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001244 ///
1245 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1246 /// also be ComplexX87.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001247 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1248 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001249
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001250 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001251 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1252 unsigned IROffset, QualType SourceTy,
1253 unsigned SourceOffset) const;
1254 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1255 unsigned IROffset, QualType SourceTy,
1256 unsigned SourceOffset) const;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001257
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001258 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001259 /// such that the argument will be returned in memory.
Chris Lattner9c254f02010-06-29 06:01:59 +00001260 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001261
1262 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001263 /// such that the argument will be passed in memory.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001264 ///
1265 /// \param freeIntRegs - The number of free integer registers remaining
1266 /// available.
1267 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001268
Chris Lattnera3c109b2010-07-29 02:16:43 +00001269 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001270
Bill Wendlingbb465d72010-10-18 03:41:31 +00001271 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbaredfac032012-03-10 01:03:58 +00001272 unsigned freeIntRegs,
Bill Wendlingbb465d72010-10-18 03:41:31 +00001273 unsigned &neededInt,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001274 unsigned &neededSSE,
1275 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001276
Eli Friedmanee1ad992011-12-02 00:11:43 +00001277 bool IsIllegalVectorType(QualType Ty) const;
1278
John McCall67a57732011-04-21 01:20:55 +00001279 /// The 0.98 ABI revision clarified a lot of ambiguities,
1280 /// unfortunately in ways that were not always consistent with
1281 /// certain previous compilers. In particular, platforms which
1282 /// required strict binary compatibility with older versions of GCC
1283 /// may need to exempt themselves.
1284 bool honorsRevision0_98() const {
John McCall64aa4b32013-04-16 22:48:15 +00001285 return !getTarget().getTriple().isOSDarwin();
John McCall67a57732011-04-21 01:20:55 +00001286 }
1287
Eli Friedmanee1ad992011-12-02 00:11:43 +00001288 bool HasAVX;
Derek Schuffbabaf312012-10-11 15:52:22 +00001289 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1290 // 64-bit hardware.
1291 bool Has64BitPointers;
Eli Friedmanee1ad992011-12-02 00:11:43 +00001292
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001293public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001294 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffbabaf312012-10-11 15:52:22 +00001295 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff90da80c2012-10-11 18:21:13 +00001296 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001297 }
Chris Lattner9c254f02010-06-29 06:01:59 +00001298
John McCallde5d3c72012-02-17 03:33:10 +00001299 bool isPassedUsingAVXType(QualType type) const {
1300 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00001301 // The freeIntRegs argument doesn't matter here.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001302 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1303 /*isNamedArg*/true);
John McCallde5d3c72012-02-17 03:33:10 +00001304 if (info.isDirect()) {
1305 llvm::Type *ty = info.getCoerceToType();
1306 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1307 return (vectorTy->getBitWidth() > 128);
1308 }
1309 return false;
1310 }
1311
Stephen Hines651f13c2014-04-23 16:59:28 -07001312 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001313
Stephen Hines651f13c2014-04-23 16:59:28 -07001314 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1315 CodeGenFunction &CGF) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001316};
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001317
Chris Lattnerf13721d2010-08-31 16:44:54 +00001318/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001319class WinX86_64ABIInfo : public ABIInfo {
1320
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001321 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001322
Chris Lattnerf13721d2010-08-31 16:44:54 +00001323public:
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001324 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1325
Stephen Hines651f13c2014-04-23 16:59:28 -07001326 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattnerf13721d2010-08-31 16:44:54 +00001327
Stephen Hines651f13c2014-04-23 16:59:28 -07001328 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1329 CodeGenFunction &CGF) const override;
Chris Lattnerf13721d2010-08-31 16:44:54 +00001330};
1331
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001332class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1333public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001334 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffbabaf312012-10-11 15:52:22 +00001335 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCall6374c332010-03-06 00:35:14 +00001336
John McCallde5d3c72012-02-17 03:33:10 +00001337 const X86_64ABIInfo &getABIInfo() const {
1338 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1339 }
1340
Stephen Hines651f13c2014-04-23 16:59:28 -07001341 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall6374c332010-03-06 00:35:14 +00001342 return 7;
1343 }
1344
1345 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07001346 llvm::Value *Address) const override {
Chris Lattner8b418682012-02-07 00:39:47 +00001347 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001348
John McCallaeeb7012010-05-27 06:19:26 +00001349 // 0-15 are the 16 integer registers.
1350 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001351 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCall6374c332010-03-06 00:35:14 +00001352 return false;
1353 }
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001354
Jay Foadef6de3d2011-07-11 09:56:20 +00001355 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001356 StringRef Constraint,
Stephen Hines651f13c2014-04-23 16:59:28 -07001357 llvm::Type* Ty) const override {
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001358 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1359 }
1360
John McCallde5d3c72012-02-17 03:33:10 +00001361 bool isNoProtoCallVariadic(const CallArgList &args,
Stephen Hines651f13c2014-04-23 16:59:28 -07001362 const FunctionNoProtoType *fnType) const override {
John McCall01f151e2011-09-21 08:08:30 +00001363 // The default CC on x86-64 sets %al to the number of SSA
1364 // registers used, and GCC sets this when calling an unprototyped
Eli Friedman3ed79032011-12-01 04:53:19 +00001365 // function, so we override the default behavior. However, don't do
Eli Friedman68805fe2011-12-06 03:08:26 +00001366 // that when AVX types are involved: the ABI explicitly states it is
1367 // undefined, and it doesn't work in practice because of how the ABI
1368 // defines varargs anyway.
Reid Kleckneref072032013-08-27 23:08:25 +00001369 if (fnType->getCallConv() == CC_C) {
Eli Friedman3ed79032011-12-01 04:53:19 +00001370 bool HasAVXType = false;
John McCallde5d3c72012-02-17 03:33:10 +00001371 for (CallArgList::const_iterator
1372 it = args.begin(), ie = args.end(); it != ie; ++it) {
1373 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1374 HasAVXType = true;
1375 break;
Eli Friedman3ed79032011-12-01 04:53:19 +00001376 }
1377 }
John McCallde5d3c72012-02-17 03:33:10 +00001378
Eli Friedman3ed79032011-12-01 04:53:19 +00001379 if (!HasAVXType)
1380 return true;
1381 }
John McCall01f151e2011-09-21 08:08:30 +00001382
John McCallde5d3c72012-02-17 03:33:10 +00001383 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCall01f151e2011-09-21 08:08:30 +00001384 }
1385
Stephen Hines651f13c2014-04-23 16:59:28 -07001386 llvm::Constant *
1387 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb914e872013-10-20 21:29:19 +00001388 unsigned Sig = (0xeb << 0) | // jmp rel8
1389 (0x0a << 8) | // .+0x0c
1390 ('F' << 16) |
1391 ('T' << 24);
1392 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1393 }
1394
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001395};
1396
Aaron Ballman89735b92013-05-24 15:06:56 +00001397static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1398 // If the argument does not end in .lib, automatically add the suffix. This
1399 // matches the behavior of MSVC.
1400 std::string ArgStr = Lib;
Rui Ueyama723cead2013-10-31 19:12:53 +00001401 if (!Lib.endswith_lower(".lib"))
Aaron Ballman89735b92013-05-24 15:06:56 +00001402 ArgStr += ".lib";
Aaron Ballman89735b92013-05-24 15:06:56 +00001403 return ArgStr;
1404}
1405
Reid Kleckner3190ca92013-05-08 13:44:39 +00001406class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1407public:
John McCallb8b52972013-06-18 02:46:29 +00001408 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1409 bool d, bool p, bool w, unsigned RegParms)
1410 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Kleckner3190ca92013-05-08 13:44:39 +00001411
1412 void getDependentLibraryOption(llvm::StringRef Lib,
Stephen Hines651f13c2014-04-23 16:59:28 -07001413 llvm::SmallString<24> &Opt) const override {
Reid Kleckner3190ca92013-05-08 13:44:39 +00001414 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001415 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001416 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001417
1418 void getDetectMismatchOption(llvm::StringRef Name,
1419 llvm::StringRef Value,
Stephen Hines651f13c2014-04-23 16:59:28 -07001420 llvm::SmallString<32> &Opt) const override {
Eli Friedman572ac322013-06-07 22:42:22 +00001421 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001422 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001423};
1424
Chris Lattnerf13721d2010-08-31 16:44:54 +00001425class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1426public:
1427 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1428 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1429
Stephen Hines651f13c2014-04-23 16:59:28 -07001430 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattnerf13721d2010-08-31 16:44:54 +00001431 return 7;
1432 }
1433
1434 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07001435 llvm::Value *Address) const override {
Chris Lattner8b418682012-02-07 00:39:47 +00001436 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001437
Chris Lattnerf13721d2010-08-31 16:44:54 +00001438 // 0-15 are the 16 integer registers.
1439 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001440 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattnerf13721d2010-08-31 16:44:54 +00001441 return false;
1442 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001443
1444 void getDependentLibraryOption(llvm::StringRef Lib,
Stephen Hines651f13c2014-04-23 16:59:28 -07001445 llvm::SmallString<24> &Opt) const override {
Reid Kleckner3190ca92013-05-08 13:44:39 +00001446 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001447 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001448 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001449
1450 void getDetectMismatchOption(llvm::StringRef Name,
1451 llvm::StringRef Value,
Stephen Hines651f13c2014-04-23 16:59:28 -07001452 llvm::SmallString<32> &Opt) const override {
Eli Friedman572ac322013-06-07 22:42:22 +00001453 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001454 }
Chris Lattnerf13721d2010-08-31 16:44:54 +00001455};
1456
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001457}
1458
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001459void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1460 Class &Hi) const {
1461 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1462 //
1463 // (a) If one of the classes is Memory, the whole argument is passed in
1464 // memory.
1465 //
1466 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1467 // memory.
1468 //
1469 // (c) If the size of the aggregate exceeds two eightbytes and the first
1470 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1471 // argument is passed in memory. NOTE: This is necessary to keep the
1472 // ABI working for processors that don't support the __m256 type.
1473 //
1474 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1475 //
1476 // Some of these are enforced by the merging logic. Others can arise
1477 // only with unions; for example:
1478 // union { _Complex double; unsigned; }
1479 //
1480 // Note that clauses (b) and (c) were added in 0.98.
1481 //
1482 if (Hi == Memory)
1483 Lo = Memory;
1484 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1485 Lo = Memory;
1486 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1487 Lo = Memory;
1488 if (Hi == SSEUp && Lo != SSE)
1489 Hi = SSE;
1490}
1491
Chris Lattner1090a9b2010-06-28 21:43:59 +00001492X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001493 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1494 // classified recursively so that always two fields are
1495 // considered. The resulting class is calculated according to
1496 // the classes of the fields in the eightbyte:
1497 //
1498 // (a) If both classes are equal, this is the resulting class.
1499 //
1500 // (b) If one of the classes is NO_CLASS, the resulting class is
1501 // the other class.
1502 //
1503 // (c) If one of the classes is MEMORY, the result is the MEMORY
1504 // class.
1505 //
1506 // (d) If one of the classes is INTEGER, the result is the
1507 // INTEGER.
1508 //
1509 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1510 // MEMORY is used as class.
1511 //
1512 // (f) Otherwise class SSE is used.
1513
1514 // Accum should never be memory (we should have returned) or
1515 // ComplexX87 (because this cannot be passed in a structure).
1516 assert((Accum != Memory && Accum != ComplexX87) &&
1517 "Invalid accumulated classification during merge.");
1518 if (Accum == Field || Field == NoClass)
1519 return Accum;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001520 if (Field == Memory)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001521 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001522 if (Accum == NoClass)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001523 return Field;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001524 if (Accum == Integer || Field == Integer)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001525 return Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001526 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1527 Accum == X87 || Accum == X87Up)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001528 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001529 return SSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001530}
1531
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001532void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001533 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001534 // FIXME: This code can be simplified by introducing a simple value class for
1535 // Class pairs with appropriate constructor methods for the various
1536 // situations.
1537
1538 // FIXME: Some of the split computations are wrong; unaligned vectors
1539 // shouldn't be passed in registers for example, so there is no chance they
1540 // can straddle an eightbyte. Verify & simplify.
1541
1542 Lo = Hi = NoClass;
1543
1544 Class &Current = OffsetBase < 64 ? Lo : Hi;
1545 Current = Memory;
1546
John McCall183700f2009-09-21 23:43:11 +00001547 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001548 BuiltinType::Kind k = BT->getKind();
1549
1550 if (k == BuiltinType::Void) {
1551 Current = NoClass;
1552 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1553 Lo = Integer;
1554 Hi = Integer;
1555 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1556 Current = Integer;
Derek Schuff7da46f92012-10-11 16:55:58 +00001557 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1558 (k == BuiltinType::LongDouble &&
Cameron Esfahani57b1da12013-09-14 01:09:11 +00001559 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001560 Current = SSE;
1561 } else if (k == BuiltinType::LongDouble) {
1562 Lo = X87;
1563 Hi = X87Up;
1564 }
1565 // FIXME: _Decimal32 and _Decimal64 are SSE.
1566 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001567 return;
1568 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001569
Chris Lattner1090a9b2010-06-28 21:43:59 +00001570 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001571 // Classify the underlying integer type.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001572 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattner1090a9b2010-06-28 21:43:59 +00001573 return;
1574 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001575
Chris Lattner1090a9b2010-06-28 21:43:59 +00001576 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001577 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001578 return;
1579 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001580
Chris Lattner1090a9b2010-06-28 21:43:59 +00001581 if (Ty->isMemberPointerType()) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001582 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar67d438d2010-05-15 00:00:37 +00001583 Lo = Hi = Integer;
1584 else
1585 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001586 return;
1587 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001588
Chris Lattner1090a9b2010-06-28 21:43:59 +00001589 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001590 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001591 if (Size == 32) {
1592 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1593 // float> as integer.
1594 Current = Integer;
1595
1596 // If this type crosses an eightbyte boundary, it should be
1597 // split.
1598 uint64_t EB_Real = (OffsetBase) / 64;
1599 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1600 if (EB_Real != EB_Imag)
1601 Hi = Lo;
1602 } else if (Size == 64) {
1603 // gcc passes <1 x double> in memory. :(
1604 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1605 return;
1606
1607 // gcc passes <1 x long long> as INTEGER.
Chris Lattner473f8e72010-08-26 18:03:20 +00001608 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner0fefa412010-08-26 18:13:50 +00001609 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1610 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1611 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001612 Current = Integer;
1613 else
1614 Current = SSE;
1615
1616 // If this type crosses an eightbyte boundary, it should be
1617 // split.
1618 if (OffsetBase && OffsetBase != 64)
1619 Hi = Lo;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001620 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001621 // Arguments of 256-bits are split into four eightbyte chunks. The
1622 // least significant one belongs to class SSE and all the others to class
1623 // SSEUP. The original Lo and Hi design considers that types can't be
1624 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1625 // This design isn't correct for 256-bits, but since there're no cases
1626 // where the upper parts would need to be inspected, avoid adding
1627 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001628 //
1629 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1630 // registers if they are "named", i.e. not part of the "..." of a
1631 // variadic function.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001632 Lo = SSE;
1633 Hi = SSEUp;
1634 }
Chris Lattner1090a9b2010-06-28 21:43:59 +00001635 return;
1636 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001637
Chris Lattner1090a9b2010-06-28 21:43:59 +00001638 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001639 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001640
Chris Lattnerea044322010-07-29 02:01:43 +00001641 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001642 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001643 if (Size <= 64)
1644 Current = Integer;
1645 else if (Size <= 128)
1646 Lo = Hi = Integer;
Chris Lattnerea044322010-07-29 02:01:43 +00001647 } else if (ET == getContext().FloatTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001648 Current = SSE;
Derek Schuff7da46f92012-10-11 16:55:58 +00001649 else if (ET == getContext().DoubleTy ||
1650 (ET == getContext().LongDoubleTy &&
Cameron Esfahani57b1da12013-09-14 01:09:11 +00001651 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001652 Lo = Hi = SSE;
Chris Lattnerea044322010-07-29 02:01:43 +00001653 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001654 Current = ComplexX87;
1655
1656 // If this complex type crosses an eightbyte boundary then it
1657 // should be split.
1658 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattnerea044322010-07-29 02:01:43 +00001659 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001660 if (Hi == NoClass && EB_Real != EB_Imag)
1661 Hi = Lo;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001662
Chris Lattner1090a9b2010-06-28 21:43:59 +00001663 return;
1664 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001665
Chris Lattnerea044322010-07-29 02:01:43 +00001666 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001667 // Arrays are treated like structures.
1668
Chris Lattnerea044322010-07-29 02:01:43 +00001669 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001670
1671 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001672 // than four eightbytes, ..., it has class MEMORY.
1673 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001674 return;
1675
1676 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1677 // fields, it has class MEMORY.
1678 //
1679 // Only need to check alignment of array base.
Chris Lattnerea044322010-07-29 02:01:43 +00001680 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001681 return;
1682
1683 // Otherwise implement simplified merge. We could be smarter about
1684 // this, but it isn't worth it and would be harder to verify.
1685 Current = NoClass;
Chris Lattnerea044322010-07-29 02:01:43 +00001686 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001687 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes089d8922011-07-12 01:27:38 +00001688
1689 // The only case a 256-bit wide vector could be used is when the array
1690 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1691 // to work for sizes wider than 128, early check and fallback to memory.
1692 if (Size > 128 && EltSize != 256)
1693 return;
1694
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001695 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1696 Class FieldLo, FieldHi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001697 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001698 Lo = merge(Lo, FieldLo);
1699 Hi = merge(Hi, FieldHi);
1700 if (Lo == Memory || Hi == Memory)
1701 break;
1702 }
1703
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001704 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001705 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattner1090a9b2010-06-28 21:43:59 +00001706 return;
1707 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001708
Chris Lattner1090a9b2010-06-28 21:43:59 +00001709 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001710 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001711
1712 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001713 // than four eightbytes, ..., it has class MEMORY.
1714 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001715 return;
1716
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001717 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1718 // copy constructor or a non-trivial destructor, it is passed by invisible
1719 // reference.
Mark Lacey23630722013-10-06 01:33:34 +00001720 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001721 return;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001722
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001723 const RecordDecl *RD = RT->getDecl();
1724
1725 // Assume variable sized types are passed in memory.
1726 if (RD->hasFlexibleArrayMember())
1727 return;
1728
Chris Lattnerea044322010-07-29 02:01:43 +00001729 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001730
1731 // Reset Lo class, this will be recomputed.
1732 Current = NoClass;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001733
1734 // If this is a C++ record, classify the bases first.
1735 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001736 for (const auto &I : CXXRD->bases()) {
1737 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001738 "Unexpected base class!");
1739 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -07001740 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001741
1742 // Classify this field.
1743 //
1744 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1745 // single eightbyte, each is classified separately. Each eightbyte gets
1746 // initialized to class NO_CLASS.
1747 Class FieldLo, FieldHi;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001748 uint64_t Offset =
1749 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Stephen Hines651f13c2014-04-23 16:59:28 -07001750 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001751 Lo = merge(Lo, FieldLo);
1752 Hi = merge(Hi, FieldHi);
1753 if (Lo == Memory || Hi == Memory)
1754 break;
1755 }
1756 }
1757
1758 // Classify the fields one at a time, merging the results.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001759 unsigned idx = 0;
Bruno Cardoso Lopes548e4782011-07-12 22:30:58 +00001760 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001761 i != e; ++i, ++idx) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001762 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1763 bool BitField = i->isBitField();
1764
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001765 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1766 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001767 //
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001768 // The only case a 256-bit wide vector could be used is when the struct
1769 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1770 // to work for sizes wider than 128, early check and fallback to memory.
1771 //
1772 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1773 Lo = Memory;
1774 return;
1775 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001776 // Note, skip this test for bit-fields, see below.
Chris Lattnerea044322010-07-29 02:01:43 +00001777 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001778 Lo = Memory;
1779 return;
1780 }
1781
1782 // Classify this field.
1783 //
1784 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1785 // exceeds a single eightbyte, each is classified
1786 // separately. Each eightbyte gets initialized to class
1787 // NO_CLASS.
1788 Class FieldLo, FieldHi;
1789
1790 // Bit-fields require special handling, they do not force the
1791 // structure to be passed in memory even if unaligned, and
1792 // therefore they can straddle an eightbyte.
1793 if (BitField) {
1794 // Ignore padding bit-fields.
1795 if (i->isUnnamedBitfield())
1796 continue;
1797
1798 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001799 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001800
1801 uint64_t EB_Lo = Offset / 64;
1802 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru9a6002a2013-10-06 09:54:18 +00001803
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001804 if (EB_Lo) {
1805 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1806 FieldLo = NoClass;
1807 FieldHi = Integer;
1808 } else {
1809 FieldLo = Integer;
1810 FieldHi = EB_Hi ? Integer : NoClass;
1811 }
1812 } else
Eli Friedman7a1b5862013-06-12 00:13:45 +00001813 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001814 Lo = merge(Lo, FieldLo);
1815 Hi = merge(Hi, FieldHi);
1816 if (Lo == Memory || Hi == Memory)
1817 break;
1818 }
1819
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001820 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001821 }
1822}
1823
Chris Lattner9c254f02010-06-29 06:01:59 +00001824ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001825 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1826 // place naturally.
John McCalld608cdb2010-08-22 10:59:02 +00001827 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001828 // Treat an enum type as its underlying type.
1829 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1830 Ty = EnumTy->getDecl()->getIntegerType();
1831
1832 return (Ty->isPromotableIntegerType() ?
1833 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1834 }
1835
1836 return ABIArgInfo::getIndirect(0);
1837}
1838
Eli Friedmanee1ad992011-12-02 00:11:43 +00001839bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1840 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1841 uint64_t Size = getContext().getTypeSize(VecTy);
1842 unsigned LargestVector = HasAVX ? 256 : 128;
1843 if (Size <= 64 || Size > LargestVector)
1844 return true;
1845 }
1846
1847 return false;
1848}
1849
Daniel Dunbaredfac032012-03-10 01:03:58 +00001850ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1851 unsigned freeIntRegs) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001852 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1853 // place naturally.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001854 //
1855 // This assumption is optimistic, as there could be free registers available
1856 // when we need to pass this argument in memory, and LLVM could try to pass
1857 // the argument in the free register. This does not seem to happen currently,
1858 // but this code would be much safer if we could mark the argument with
1859 // 'onstack'. See PR12193.
Eli Friedmanee1ad992011-12-02 00:11:43 +00001860 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001861 // Treat an enum type as its underlying type.
1862 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1863 Ty = EnumTy->getDecl()->getIntegerType();
1864
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001865 return (Ty->isPromotableIntegerType() ?
1866 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001867 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001868
Mark Lacey23630722013-10-06 01:33:34 +00001869 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001870 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001871
Chris Lattner855d2272011-05-22 23:21:23 +00001872 // Compute the byval alignment. We specify the alignment of the byval in all
1873 // cases so that the mid-level optimizer knows the alignment of the byval.
1874 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbaredfac032012-03-10 01:03:58 +00001875
1876 // Attempt to avoid passing indirect results using byval when possible. This
1877 // is important for good codegen.
1878 //
1879 // We do this by coercing the value into a scalar type which the backend can
1880 // handle naturally (i.e., without using byval).
1881 //
1882 // For simplicity, we currently only do this when we have exhausted all of the
1883 // free integer registers. Doing this when there are free integer registers
1884 // would require more care, as we would have to ensure that the coerced value
1885 // did not claim the unused register. That would require either reording the
1886 // arguments to the function (so that any subsequent inreg values came first),
1887 // or only doing this optimization when there were no following arguments that
1888 // might be inreg.
1889 //
1890 // We currently expect it to be rare (particularly in well written code) for
1891 // arguments to be passed on the stack when there are still free integer
1892 // registers available (this would typically imply large structs being passed
1893 // by value), so this seems like a fair tradeoff for now.
1894 //
1895 // We can revisit this if the backend grows support for 'onstack' parameter
1896 // attributes. See PR12193.
1897 if (freeIntRegs == 0) {
1898 uint64_t Size = getContext().getTypeSize(Ty);
1899
1900 // If this type fits in an eightbyte, coerce it into the matching integral
1901 // type, which will end up on the stack (with alignment 8).
1902 if (Align == 8 && Size <= 64)
1903 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1904 Size));
1905 }
1906
Chris Lattner855d2272011-05-22 23:21:23 +00001907 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001908}
1909
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001910/// GetByteVectorType - The ABI specifies that a value should be passed in an
1911/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner0f408f52010-07-29 04:56:46 +00001912/// vector register.
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001913llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001914 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001915
Chris Lattner15842bd2010-07-29 05:02:29 +00001916 // Wrapper structs that just contain vectors are passed just like vectors,
1917 // strip them off if present.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001918 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner15842bd2010-07-29 05:02:29 +00001919 while (STy && STy->getNumElements() == 1) {
1920 IRType = STy->getElementType(0);
1921 STy = dyn_cast<llvm::StructType>(IRType);
1922 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001923
Bruno Cardoso Lopes528a8c72011-07-08 22:57:35 +00001924 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001925 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1926 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001927 unsigned BitWidth = VT->getBitWidth();
Tanya Lattnerce275672011-11-28 23:18:11 +00001928 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner0f408f52010-07-29 04:56:46 +00001929 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1930 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1931 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1932 EltTy->isIntegerTy(128)))
1933 return VT;
1934 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001935
Chris Lattner0f408f52010-07-29 04:56:46 +00001936 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1937}
1938
Chris Lattnere2962be2010-07-29 07:30:00 +00001939/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1940/// is known to either be off the end of the specified type or being in
1941/// alignment padding. The user type specified is known to be at most 128 bits
1942/// in size, and have passed through X86_64ABIInfo::classify with a successful
1943/// classification that put one of the two halves in the INTEGER class.
1944///
1945/// It is conservatively correct to return false.
1946static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1947 unsigned EndBit, ASTContext &Context) {
1948 // If the bytes being queried are off the end of the type, there is no user
1949 // data hiding here. This handles analysis of builtins, vectors and other
1950 // types that don't contain interesting padding.
1951 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1952 if (TySize <= StartBit)
1953 return true;
1954
Chris Lattner021c3a32010-07-29 07:43:55 +00001955 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1956 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1957 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1958
1959 // Check each element to see if the element overlaps with the queried range.
1960 for (unsigned i = 0; i != NumElts; ++i) {
1961 // If the element is after the span we care about, then we're done..
1962 unsigned EltOffset = i*EltSize;
1963 if (EltOffset >= EndBit) break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001964
Chris Lattner021c3a32010-07-29 07:43:55 +00001965 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1966 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1967 EndBit-EltOffset, Context))
1968 return false;
1969 }
1970 // If it overlaps no elements, then it is safe to process as padding.
1971 return true;
1972 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001973
Chris Lattnere2962be2010-07-29 07:30:00 +00001974 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1975 const RecordDecl *RD = RT->getDecl();
1976 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001977
Chris Lattnere2962be2010-07-29 07:30:00 +00001978 // If this is a C++ record, check the bases first.
1979 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001980 for (const auto &I : CXXRD->bases()) {
1981 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnere2962be2010-07-29 07:30:00 +00001982 "Unexpected base class!");
1983 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -07001984 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001985
Chris Lattnere2962be2010-07-29 07:30:00 +00001986 // If the base is after the span we care about, ignore it.
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001987 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnere2962be2010-07-29 07:30:00 +00001988 if (BaseOffset >= EndBit) continue;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001989
Chris Lattnere2962be2010-07-29 07:30:00 +00001990 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Stephen Hines651f13c2014-04-23 16:59:28 -07001991 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnere2962be2010-07-29 07:30:00 +00001992 EndBit-BaseOffset, Context))
1993 return false;
1994 }
1995 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001996
Chris Lattnere2962be2010-07-29 07:30:00 +00001997 // Verify that no field has data that overlaps the region of interest. Yes
1998 // this could be sped up a lot by being smarter about queried fields,
1999 // however we're only looking at structs up to 16 bytes, so we don't care
2000 // much.
2001 unsigned idx = 0;
2002 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2003 i != e; ++i, ++idx) {
2004 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002005
Chris Lattnere2962be2010-07-29 07:30:00 +00002006 // If we found a field after the region we care about, then we're done.
2007 if (FieldOffset >= EndBit) break;
2008
2009 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2010 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2011 Context))
2012 return false;
2013 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002014
Chris Lattnere2962be2010-07-29 07:30:00 +00002015 // If nothing in this record overlapped the area of interest, then we're
2016 // clean.
2017 return true;
2018 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002019
Chris Lattnere2962be2010-07-29 07:30:00 +00002020 return false;
2021}
2022
Chris Lattner0b362002010-07-29 18:39:32 +00002023/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2024/// float member at the specified offset. For example, {int,{float}} has a
2025/// float at offset 4. It is conservatively correct for this routine to return
2026/// false.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002027static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmow25a6a842012-10-08 16:25:52 +00002028 const llvm::DataLayout &TD) {
Chris Lattner0b362002010-07-29 18:39:32 +00002029 // Base case if we find a float.
2030 if (IROffset == 0 && IRType->isFloatTy())
2031 return true;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002032
Chris Lattner0b362002010-07-29 18:39:32 +00002033 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002034 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner0b362002010-07-29 18:39:32 +00002035 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2036 unsigned Elt = SL->getElementContainingOffset(IROffset);
2037 IROffset -= SL->getElementOffset(Elt);
2038 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2039 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002040
Chris Lattner0b362002010-07-29 18:39:32 +00002041 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002042 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2043 llvm::Type *EltTy = ATy->getElementType();
Chris Lattner0b362002010-07-29 18:39:32 +00002044 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2045 IROffset -= IROffset/EltSize*EltSize;
2046 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2047 }
2048
2049 return false;
2050}
2051
Chris Lattnerf47c9442010-07-29 18:13:09 +00002052
2053/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2054/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002055llvm::Type *X86_64ABIInfo::
2056GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattnerf47c9442010-07-29 18:13:09 +00002057 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnercba8d312010-07-29 18:19:50 +00002058 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattnerf47c9442010-07-29 18:13:09 +00002059 // pass as float if the last 4 bytes is just padding. This happens for
2060 // structs that contain 3 floats.
2061 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2062 SourceOffset*8+64, getContext()))
2063 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002064
Chris Lattner0b362002010-07-29 18:39:32 +00002065 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2066 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2067 // case.
Micah Villmow25a6a842012-10-08 16:25:52 +00002068 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2069 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner22fd4ba2010-08-25 23:39:14 +00002070 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002071
Chris Lattnerf47c9442010-07-29 18:13:09 +00002072 return llvm::Type::getDoubleTy(getVMContext());
2073}
2074
2075
Chris Lattner0d2656d2010-07-29 17:40:35 +00002076/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2077/// an 8-byte GPR. This means that we either have a scalar or we are talking
2078/// about the high or low part of an up-to-16-byte struct. This routine picks
2079/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattner49382de2010-07-28 22:44:07 +00002080/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2081/// etc).
2082///
2083/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2084/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2085/// the 8-byte value references. PrefType may be null.
2086///
2087/// SourceTy is the source level type for the entire argument. SourceOffset is
2088/// an offset into this that we're processing (which is always either 0 or 8).
2089///
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002090llvm::Type *X86_64ABIInfo::
2091GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner0d2656d2010-07-29 17:40:35 +00002092 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnere2962be2010-07-29 07:30:00 +00002093 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2094 // returning an 8-byte unit starting with it. See if we can safely use it.
2095 if (IROffset == 0) {
2096 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffbabaf312012-10-11 15:52:22 +00002097 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2098 IRType->isIntegerTy(64))
Chris Lattnere2962be2010-07-29 07:30:00 +00002099 return IRType;
Chris Lattner49382de2010-07-28 22:44:07 +00002100
Chris Lattnere2962be2010-07-29 07:30:00 +00002101 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2102 // goodness in the source type is just tail padding. This is allowed to
2103 // kick in for struct {double,int} on the int, but not on
2104 // struct{double,int,int} because we wouldn't return the second int. We
2105 // have to do this analysis on the source type because we can't depend on
2106 // unions being lowered a specific way etc.
2107 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffbabaf312012-10-11 15:52:22 +00002108 IRType->isIntegerTy(32) ||
2109 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2110 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2111 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002112
Chris Lattnere2962be2010-07-29 07:30:00 +00002113 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2114 SourceOffset*8+64, getContext()))
2115 return IRType;
2116 }
2117 }
Chris Lattner49382de2010-07-28 22:44:07 +00002118
Chris Lattner2acc6e32011-07-18 04:24:23 +00002119 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner49382de2010-07-28 22:44:07 +00002120 // If this is a struct, recurse into the field at the specified offset.
Micah Villmow25a6a842012-10-08 16:25:52 +00002121 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattner49382de2010-07-28 22:44:07 +00002122 if (IROffset < SL->getSizeInBytes()) {
2123 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2124 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002125
Chris Lattner0d2656d2010-07-29 17:40:35 +00002126 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2127 SourceTy, SourceOffset);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002128 }
Chris Lattner49382de2010-07-28 22:44:07 +00002129 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002130
Chris Lattner2acc6e32011-07-18 04:24:23 +00002131 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002132 llvm::Type *EltTy = ATy->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00002133 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner021c3a32010-07-29 07:43:55 +00002134 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner0d2656d2010-07-29 17:40:35 +00002135 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2136 SourceOffset);
Chris Lattner021c3a32010-07-29 07:43:55 +00002137 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002138
Chris Lattner49382de2010-07-28 22:44:07 +00002139 // Okay, we don't have any better idea of what to pass, so we pass this in an
2140 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002141 unsigned TySizeInBytes =
2142 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattner49382de2010-07-28 22:44:07 +00002143
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002144 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002145
Chris Lattner49382de2010-07-28 22:44:07 +00002146 // It is always safe to classify this as an integer type up to i64 that
2147 // isn't larger than the structure.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002148 return llvm::IntegerType::get(getVMContext(),
2149 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner9c254f02010-06-29 06:01:59 +00002150}
2151
Chris Lattner66e7b682010-09-01 00:50:20 +00002152
2153/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2154/// be used as elements of a two register pair to pass or return, return a
2155/// first class aggregate to represent them. For example, if the low part of
2156/// a by-value argument should be passed as i32* and the high part as float,
2157/// return {i32*, float}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002158static llvm::Type *
Jay Foadef6de3d2011-07-11 09:56:20 +00002159GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmow25a6a842012-10-08 16:25:52 +00002160 const llvm::DataLayout &TD) {
Chris Lattner66e7b682010-09-01 00:50:20 +00002161 // In order to correctly satisfy the ABI, we need to the high part to start
2162 // at offset 8. If the high and low parts we inferred are both 4-byte types
2163 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2164 // the second element at offset 8. Check for this:
2165 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2166 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmow25a6a842012-10-08 16:25:52 +00002167 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattner66e7b682010-09-01 00:50:20 +00002168 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002169
Chris Lattner66e7b682010-09-01 00:50:20 +00002170 // To handle this, we have to increase the size of the low part so that the
2171 // second element will start at an 8 byte offset. We can't increase the size
2172 // of the second element because it might make us access off the end of the
2173 // struct.
2174 if (HiStart != 8) {
2175 // There are only two sorts of types the ABI generation code can produce for
2176 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2177 // Promote these to a larger type.
2178 if (Lo->isFloatTy())
2179 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2180 else {
2181 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2182 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2183 }
2184 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002185
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002186 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002187
2188
Chris Lattner66e7b682010-09-01 00:50:20 +00002189 // Verify that the second element is at an 8-byte offset.
2190 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2191 "Invalid x86-64 argument pair!");
2192 return Result;
2193}
2194
Chris Lattner519f68c2010-07-28 23:06:14 +00002195ABIArgInfo X86_64ABIInfo::
Chris Lattnera3c109b2010-07-29 02:16:43 +00002196classifyReturnType(QualType RetTy) const {
Chris Lattner519f68c2010-07-28 23:06:14 +00002197 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2198 // classification algorithm.
2199 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002200 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner519f68c2010-07-28 23:06:14 +00002201
2202 // Check some invariants.
2203 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002204 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2205
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002206 llvm::Type *ResType = 0;
Chris Lattner519f68c2010-07-28 23:06:14 +00002207 switch (Lo) {
2208 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002209 if (Hi == NoClass)
2210 return ABIArgInfo::getIgnore();
2211 // If the low part is just padding, it takes no register, leave ResType
2212 // null.
2213 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2214 "Unknown missing lo part");
2215 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002216
2217 case SSEUp:
2218 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002219 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002220
2221 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2222 // hidden argument.
2223 case Memory:
2224 return getIndirectReturnResult(RetTy);
2225
2226 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2227 // available register of the sequence %rax, %rdx is used.
2228 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002229 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002230
Chris Lattnereb518b42010-07-29 21:42:50 +00002231 // If we have a sign or zero extended integer, make sure to return Extend
2232 // so that the parameter gets the right LLVM IR attributes.
2233 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2234 // Treat an enum type as its underlying type.
2235 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2236 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002237
Chris Lattnereb518b42010-07-29 21:42:50 +00002238 if (RetTy->isIntegralOrEnumerationType() &&
2239 RetTy->isPromotableIntegerType())
2240 return ABIArgInfo::getExtend();
2241 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002242 break;
2243
2244 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2245 // available SSE register of the sequence %xmm0, %xmm1 is used.
2246 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002247 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattner0b30c672010-07-28 23:12:33 +00002248 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002249
2250 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2251 // returned on the X87 stack in %st0 as 80-bit x87 number.
2252 case X87:
Chris Lattnerea044322010-07-29 02:01:43 +00002253 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattner0b30c672010-07-28 23:12:33 +00002254 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002255
2256 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2257 // part of the value is returned in %st0 and the imaginary part in
2258 // %st1.
2259 case ComplexX87:
2260 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner7650d952011-06-18 22:49:11 +00002261 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattnerea044322010-07-29 02:01:43 +00002262 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner519f68c2010-07-28 23:06:14 +00002263 NULL);
2264 break;
2265 }
2266
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002267 llvm::Type *HighPart = 0;
Chris Lattner519f68c2010-07-28 23:06:14 +00002268 switch (Hi) {
2269 // Memory was handled previously and X87 should
2270 // never occur as a hi class.
2271 case Memory:
2272 case X87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002273 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002274
2275 case ComplexX87: // Previously handled.
Chris Lattner0b30c672010-07-28 23:12:33 +00002276 case NoClass:
2277 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002278
Chris Lattner3db4dde2010-09-01 00:20:33 +00002279 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002280 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002281 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2282 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002283 break;
Chris Lattner3db4dde2010-09-01 00:20:33 +00002284 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002285 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002286 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2287 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002288 break;
2289
2290 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002291 // is passed in the next available eightbyte chunk if the last used
2292 // vector register.
Chris Lattner519f68c2010-07-28 23:06:14 +00002293 //
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002294 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner519f68c2010-07-28 23:06:14 +00002295 case SSEUp:
2296 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002297 ResType = GetByteVectorType(RetTy);
Chris Lattner519f68c2010-07-28 23:06:14 +00002298 break;
2299
2300 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2301 // returned together with the previous X87 value in %st0.
2302 case X87Up:
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002303 // If X87Up is preceded by X87, we don't need to do
Chris Lattner519f68c2010-07-28 23:06:14 +00002304 // anything. However, in some cases with unions it may not be
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002305 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner519f68c2010-07-28 23:06:14 +00002306 // extra bits in an SSE reg.
Chris Lattner603519d2010-07-29 17:49:08 +00002307 if (Lo != X87) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002308 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002309 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2310 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner603519d2010-07-29 17:49:08 +00002311 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002312 break;
2313 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002314
Chris Lattner3db4dde2010-09-01 00:20:33 +00002315 // If a high part was specified, merge it together with the low part. It is
Chris Lattner645406a2010-09-01 00:24:35 +00002316 // known to pass in the high eightbyte of the result. We do this by forming a
2317 // first class struct aggregate with the high and low part: {low, high}
Chris Lattner66e7b682010-09-01 00:50:20 +00002318 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002319 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner519f68c2010-07-28 23:06:14 +00002320
Chris Lattnereb518b42010-07-29 21:42:50 +00002321 return ABIArgInfo::getDirect(ResType);
Chris Lattner519f68c2010-07-28 23:06:14 +00002322}
2323
Daniel Dunbaredfac032012-03-10 01:03:58 +00002324ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman7a1b5862013-06-12 00:13:45 +00002325 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2326 bool isNamedArg)
Daniel Dunbaredfac032012-03-10 01:03:58 +00002327 const
2328{
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002329 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002330 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002331
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002332 // Check some invariants.
2333 // FIXME: Enforce these by construction.
2334 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002335 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2336
2337 neededInt = 0;
2338 neededSSE = 0;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002339 llvm::Type *ResType = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002340 switch (Lo) {
2341 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002342 if (Hi == NoClass)
2343 return ABIArgInfo::getIgnore();
2344 // If the low part is just padding, it takes no register, leave ResType
2345 // null.
2346 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2347 "Unknown missing lo part");
2348 break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002349
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002350 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2351 // on the stack.
2352 case Memory:
2353
2354 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2355 // COMPLEX_X87, it is passed in memory.
2356 case X87:
2357 case ComplexX87:
Mark Lacey23630722013-10-06 01:33:34 +00002358 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedmanded137f2011-06-29 07:04:55 +00002359 ++neededInt;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002360 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002361
2362 case SSEUp:
2363 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002364 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002365
2366 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2367 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2368 // and %r9 is used.
2369 case Integer:
Chris Lattner9c254f02010-06-29 06:01:59 +00002370 ++neededInt;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002371
Chris Lattner49382de2010-07-28 22:44:07 +00002372 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002373 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattnereb518b42010-07-29 21:42:50 +00002374
2375 // If we have a sign or zero extended integer, make sure to return Extend
2376 // so that the parameter gets the right LLVM IR attributes.
2377 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2378 // Treat an enum type as its underlying type.
2379 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2380 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002381
Chris Lattnereb518b42010-07-29 21:42:50 +00002382 if (Ty->isIntegralOrEnumerationType() &&
2383 Ty->isPromotableIntegerType())
2384 return ABIArgInfo::getExtend();
2385 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002386
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002387 break;
2388
2389 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2390 // available SSE register is used, the registers are taken in the
2391 // order from %xmm0 to %xmm7.
Bill Wendlingbb465d72010-10-18 03:41:31 +00002392 case SSE: {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002393 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman14508ff2011-07-02 00:57:27 +00002394 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling99aaae82010-10-18 23:51:38 +00002395 ++neededSSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002396 break;
2397 }
Bill Wendlingbb465d72010-10-18 03:41:31 +00002398 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002399
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002400 llvm::Type *HighPart = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002401 switch (Hi) {
2402 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002403 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002404 // which is passed in memory.
2405 case Memory:
2406 case X87:
2407 case ComplexX87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002408 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002409
2410 case NoClass: break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002411
Chris Lattner645406a2010-09-01 00:24:35 +00002412 case Integer:
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002413 ++neededInt;
Chris Lattner49382de2010-07-28 22:44:07 +00002414 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002415 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002416
Chris Lattner645406a2010-09-01 00:24:35 +00002417 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2418 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002419 break;
2420
2421 // X87Up generally doesn't occur here (long double is passed in
2422 // memory), except in situations involving unions.
2423 case X87Up:
Chris Lattner645406a2010-09-01 00:24:35 +00002424 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002425 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002426
Chris Lattner645406a2010-09-01 00:24:35 +00002427 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2428 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner117e3f42010-07-30 04:02:24 +00002429
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002430 ++neededSSE;
2431 break;
2432
2433 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2434 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002435 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002436 case SSEUp:
Chris Lattnerab5722e2010-07-28 23:47:21 +00002437 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002438 ResType = GetByteVectorType(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002439 break;
2440 }
2441
Chris Lattner645406a2010-09-01 00:24:35 +00002442 // If a high part was specified, merge it together with the low part. It is
2443 // known to pass in the high eightbyte of the result. We do this by forming a
2444 // first class struct aggregate with the high and low part: {low, high}
2445 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002446 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002447
Chris Lattnereb518b42010-07-29 21:42:50 +00002448 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002449}
2450
Chris Lattneree5dcd02010-07-29 02:31:05 +00002451void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002452
Chris Lattnera3c109b2010-07-29 02:16:43 +00002453 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002454
2455 // Keep track of the number of assigned registers.
Bill Wendling99aaae82010-10-18 23:51:38 +00002456 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002457
2458 // If the return value is indirect, then the hidden argument is consuming one
2459 // integer register.
2460 if (FI.getReturnInfo().isIndirect())
2461 --freeIntRegs;
2462
Eli Friedman7a1b5862013-06-12 00:13:45 +00002463 bool isVariadic = FI.isVariadic();
2464 unsigned numRequiredArgs = 0;
2465 if (isVariadic)
2466 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2467
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002468 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2469 // get assigned (in left-to-right order) for passing as follows...
2470 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2471 it != ie; ++it) {
Eli Friedman7a1b5862013-06-12 00:13:45 +00002472 bool isNamedArg = true;
2473 if (isVariadic)
Aaron Ballmaneba7d2f2013-06-12 15:03:45 +00002474 isNamedArg = (it - FI.arg_begin()) <
2475 static_cast<signed>(numRequiredArgs);
Eli Friedman7a1b5862013-06-12 00:13:45 +00002476
Bill Wendling99aaae82010-10-18 23:51:38 +00002477 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002478 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman7a1b5862013-06-12 00:13:45 +00002479 neededSSE, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002480
2481 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2482 // eightbyte of an argument, the whole argument is passed on the
2483 // stack. If registers have already been assigned for some
2484 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling99aaae82010-10-18 23:51:38 +00002485 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002486 freeIntRegs -= neededInt;
2487 freeSSERegs -= neededSSE;
2488 } else {
Daniel Dunbaredfac032012-03-10 01:03:58 +00002489 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002490 }
2491 }
2492}
2493
2494static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2495 QualType Ty,
2496 CodeGenFunction &CGF) {
2497 llvm::Value *overflow_arg_area_p =
2498 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2499 llvm::Value *overflow_arg_area =
2500 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2501
2502 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2503 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedman8d2fe422011-11-18 02:44:19 +00002504 // It isn't stated explicitly in the standard, but in practice we use
2505 // alignment greater than 16 where necessary.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002506 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2507 if (Align > 8) {
Eli Friedman8d2fe422011-11-18 02:44:19 +00002508 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson0032b272009-08-13 21:57:51 +00002509 llvm::Value *Offset =
Eli Friedman8d2fe422011-11-18 02:44:19 +00002510 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002511 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2512 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner77b89b82010-06-27 07:15:29 +00002513 CGF.Int64Ty);
Eli Friedman8d2fe422011-11-18 02:44:19 +00002514 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002515 overflow_arg_area =
2516 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2517 overflow_arg_area->getType(),
2518 "overflow_arg_area.align");
2519 }
2520
2521 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002522 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002523 llvm::Value *Res =
2524 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002525 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002526
2527 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2528 // l->overflow_arg_area + sizeof(type).
2529 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2530 // an 8 byte boundary.
2531
2532 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson0032b272009-08-13 21:57:51 +00002533 llvm::Value *Offset =
Chris Lattner77b89b82010-06-27 07:15:29 +00002534 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002535 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2536 "overflow_arg_area.next");
2537 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2538
2539 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2540 return Res;
2541}
2542
2543llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2544 CodeGenFunction &CGF) const {
2545 // Assume that va_list type is correct; should be pointer to LLVM type:
2546 // struct {
2547 // i32 gp_offset;
2548 // i32 fp_offset;
2549 // i8* overflow_arg_area;
2550 // i8* reg_save_area;
2551 // };
Bill Wendling99aaae82010-10-18 23:51:38 +00002552 unsigned neededInt, neededSSE;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002553
Chris Lattnera14db752010-03-11 18:19:55 +00002554 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman7a1b5862013-06-12 00:13:45 +00002555 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2556 /*isNamedArg*/false);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002557
2558 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2559 // in the registers. If not go to step 7.
2560 if (!neededInt && !neededSSE)
2561 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2562
2563 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2564 // general purpose registers needed to pass type and num_fp to hold
2565 // the number of floating point registers needed.
2566
2567 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2568 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2569 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2570 //
2571 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2572 // register save space).
2573
2574 llvm::Value *InRegs = 0;
2575 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2576 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2577 if (neededInt) {
2578 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2579 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattner1090a9b2010-06-28 21:43:59 +00002580 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2581 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002582 }
2583
2584 if (neededSSE) {
2585 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2586 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2587 llvm::Value *FitsInFP =
Chris Lattner1090a9b2010-06-28 21:43:59 +00002588 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2589 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002590 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2591 }
2592
2593 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2594 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2595 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2596 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2597
2598 // Emit code to load the value if it was passed in registers.
2599
2600 CGF.EmitBlock(InRegBlock);
2601
2602 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2603 // an offset of l->gp_offset and/or l->fp_offset. This may require
2604 // copying to a temporary location in case the parameter is passed
2605 // in different register classes or requires an alignment greater
2606 // than 8 for general purpose registers and 16 for XMM registers.
2607 //
2608 // FIXME: This really results in shameful code when we end up needing to
2609 // collect arguments from different places; often what should result in a
2610 // simple assembling of a structure from scattered addresses has many more
2611 // loads than necessary. Can we clean this up?
Chris Lattner2acc6e32011-07-18 04:24:23 +00002612 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002613 llvm::Value *RegAddr =
2614 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2615 "reg_save_area");
2616 if (neededInt && neededSSE) {
2617 // FIXME: Cleanup.
Chris Lattner800588f2010-07-29 06:26:06 +00002618 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002619 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmaneeb00622013-06-07 23:20:55 +00002620 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2621 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002622 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002623 llvm::Type *TyLo = ST->getElementType(0);
2624 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattnera8b7a7d2010-08-26 06:28:35 +00002625 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002626 "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002627 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2628 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002629 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2630 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002631 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2632 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002633 llvm::Value *V =
2634 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2635 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2636 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2637 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2638
Owen Andersona1cf15f2009-07-14 23:10:40 +00002639 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002640 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002641 } else if (neededInt) {
2642 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2643 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002644 llvm::PointerType::getUnqual(LTy));
Eli Friedmaneeb00622013-06-07 23:20:55 +00002645
2646 // Copy to a temporary if necessary to ensure the appropriate alignment.
2647 std::pair<CharUnits, CharUnits> SizeAlign =
2648 CGF.getContext().getTypeInfoInChars(Ty);
2649 uint64_t TySize = SizeAlign.first.getQuantity();
2650 unsigned TyAlign = SizeAlign.second.getQuantity();
2651 if (TyAlign > 8) {
Eli Friedmaneeb00622013-06-07 23:20:55 +00002652 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2653 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2654 RegAddr = Tmp;
2655 }
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002656 } else if (neededSSE == 1) {
2657 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2658 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2659 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002660 } else {
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002661 assert(neededSSE == 2 && "Invalid number of needed registers!");
2662 // SSE registers are spaced 16 bytes apart in the register save
2663 // area, we need to collect the two eightbytes together.
2664 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattner1090a9b2010-06-28 21:43:59 +00002665 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattner8b418682012-02-07 00:39:47 +00002666 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002667 llvm::Type *DblPtrTy =
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002668 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmaneeb00622013-06-07 23:20:55 +00002669 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2670 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2671 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002672 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2673 DblPtrTy));
2674 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2675 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2676 DblPtrTy));
2677 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2678 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2679 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002680 }
2681
2682 // AMD64-ABI 3.5.7p5: Step 5. Set:
2683 // l->gp_offset = l->gp_offset + num_gp * 8
2684 // l->fp_offset = l->fp_offset + num_fp * 16.
2685 if (neededInt) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002686 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002687 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2688 gp_offset_p);
2689 }
2690 if (neededSSE) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002691 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002692 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2693 fp_offset_p);
2694 }
2695 CGF.EmitBranch(ContBlock);
2696
2697 // Emit code to load the value if it was passed in memory.
2698
2699 CGF.EmitBlock(InMemBlock);
2700 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2701
2702 // Return the appropriate result.
2703
2704 CGF.EmitBlock(ContBlock);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002705 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002706 "vaarg.addr");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002707 ResAddr->addIncoming(RegAddr, InRegBlock);
2708 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002709 return ResAddr;
2710}
2711
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002712ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002713
2714 if (Ty->isVoidType())
2715 return ABIArgInfo::getIgnore();
2716
2717 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2718 Ty = EnumTy->getDecl()->getIntegerType();
2719
2720 uint64_t Size = getContext().getTypeSize(Ty);
2721
2722 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002723 if (IsReturnType) {
Mark Lacey23630722013-10-06 01:33:34 +00002724 if (isRecordReturnIndirect(RT, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002725 return ABIArgInfo::getIndirect(0, false);
2726 } else {
Mark Lacey23630722013-10-06 01:33:34 +00002727 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002728 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2729 }
2730
2731 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002732 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2733
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002734 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Stephen Hines651f13c2014-04-23 16:59:28 -07002735 if (Size == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002736 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2737 Size));
2738
2739 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2740 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2741 if (Size <= 64 &&
NAKAMURA Takumiff8be0e2011-01-19 00:11:33 +00002742 (Size & (Size - 1)) == 0)
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002743 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2744 Size));
2745
2746 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2747 }
2748
2749 if (Ty->isPromotableIntegerType())
2750 return ABIArgInfo::getExtend();
2751
2752 return ABIArgInfo::getDirect();
2753}
2754
2755void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2756
2757 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002758 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002759
Stephen Hines651f13c2014-04-23 16:59:28 -07002760 for (auto &I : FI.arguments())
2761 I.info = classify(I.type, false);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002762}
2763
Chris Lattnerf13721d2010-08-31 16:44:54 +00002764llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2765 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00002766 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002767
Chris Lattnerf13721d2010-08-31 16:44:54 +00002768 CGBuilderTy &Builder = CGF.Builder;
2769 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2770 "ap");
2771 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2772 llvm::Type *PTy =
2773 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2774 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2775
2776 uint64_t Offset =
2777 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2778 llvm::Value *NextAddr =
2779 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2780 "ap.next");
2781 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2782
2783 return AddrTyped;
2784}
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002785
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00002786namespace {
2787
Derek Schuff263366f2012-10-16 22:30:41 +00002788class NaClX86_64ABIInfo : public ABIInfo {
2789 public:
2790 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2791 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07002792 void computeInfo(CGFunctionInfo &FI) const override;
2793 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2794 CodeGenFunction &CGF) const override;
Derek Schuff263366f2012-10-16 22:30:41 +00002795 private:
2796 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2797 X86_64ABIInfo NInfo; // Used for everything else.
2798};
2799
2800class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2801 public:
2802 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2803 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2804};
2805
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00002806}
2807
Derek Schuff263366f2012-10-16 22:30:41 +00002808void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2809 if (FI.getASTCallingConvention() == CC_PnaclCall)
2810 PInfo.computeInfo(FI);
2811 else
2812 NInfo.computeInfo(FI);
2813}
2814
2815llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2816 CodeGenFunction &CGF) const {
2817 // Always use the native convention; calling pnacl-style varargs functions
2818 // is unuspported.
2819 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2820}
2821
2822
John McCallec853ba2010-03-11 00:10:12 +00002823// PowerPC-32
2824
2825namespace {
2826class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2827public:
Chris Lattnerea044322010-07-29 02:01:43 +00002828 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002829
Stephen Hines651f13c2014-04-23 16:59:28 -07002830 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallec853ba2010-03-11 00:10:12 +00002831 // This is recovered from gcc output.
2832 return 1; // r1 is the dedicated stack pointer
2833 }
2834
2835 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07002836 llvm::Value *Address) const override;
John McCallec853ba2010-03-11 00:10:12 +00002837};
2838
2839}
2840
2841bool
2842PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2843 llvm::Value *Address) const {
2844 // This is calculated from the LLVM and GCC tables and verified
2845 // against gcc output. AFAIK all ABIs use the same encoding.
2846
2847 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallec853ba2010-03-11 00:10:12 +00002848
Chris Lattner8b418682012-02-07 00:39:47 +00002849 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallec853ba2010-03-11 00:10:12 +00002850 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2851 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2852 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2853
2854 // 0-31: r0-31, the 4-byte general-purpose registers
John McCallaeeb7012010-05-27 06:19:26 +00002855 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallec853ba2010-03-11 00:10:12 +00002856
2857 // 32-63: fp0-31, the 8-byte floating-point registers
John McCallaeeb7012010-05-27 06:19:26 +00002858 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallec853ba2010-03-11 00:10:12 +00002859
2860 // 64-76 are various 4-byte special-purpose registers:
2861 // 64: mq
2862 // 65: lr
2863 // 66: ctr
2864 // 67: ap
2865 // 68-75 cr0-7
2866 // 76: xer
John McCallaeeb7012010-05-27 06:19:26 +00002867 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallec853ba2010-03-11 00:10:12 +00002868
2869 // 77-108: v0-31, the 16-byte vector registers
John McCallaeeb7012010-05-27 06:19:26 +00002870 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallec853ba2010-03-11 00:10:12 +00002871
2872 // 109: vrsave
2873 // 110: vscr
2874 // 111: spe_acc
2875 // 112: spefscr
2876 // 113: sfp
John McCallaeeb7012010-05-27 06:19:26 +00002877 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallec853ba2010-03-11 00:10:12 +00002878
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002879 return false;
John McCallec853ba2010-03-11 00:10:12 +00002880}
2881
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002882// PowerPC-64
2883
2884namespace {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002885/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2886class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2887
2888public:
2889 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2890
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002891 bool isPromotableTypeForABI(QualType Ty) const;
2892
2893 ABIArgInfo classifyReturnType(QualType RetTy) const;
2894 ABIArgInfo classifyArgumentType(QualType Ty) const;
2895
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002896 // TODO: We can add more logic to computeInfo to improve performance.
2897 // Example: For aggregate arguments that fit in a register, we could
2898 // use getDirectInReg (as is done below for structs containing a single
2899 // floating-point value) to avoid pushing them to memory on function
2900 // entry. This would require changing the logic in PPCISelLowering
2901 // when lowering the parameters in the caller and args in the callee.
Stephen Hines651f13c2014-04-23 16:59:28 -07002902 void computeInfo(CGFunctionInfo &FI) const override {
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002903 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07002904 for (auto &I : FI.arguments()) {
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002905 // We rely on the default argument classification for the most part.
2906 // One exception: An aggregate containing a single floating-point
Bill Schmidtb1993102013-07-23 22:15:57 +00002907 // or vector item must be passed in a register if one is available.
Stephen Hines651f13c2014-04-23 16:59:28 -07002908 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002909 if (T) {
2910 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidtb1993102013-07-23 22:15:57 +00002911 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002912 QualType QT(T, 0);
Stephen Hines651f13c2014-04-23 16:59:28 -07002913 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002914 continue;
2915 }
2916 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002917 I.info = classifyArgumentType(I.type);
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002918 }
2919 }
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002920
Stephen Hines651f13c2014-04-23 16:59:28 -07002921 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2922 CodeGenFunction &CGF) const override;
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002923};
2924
2925class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2926public:
2927 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2928 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2929
Stephen Hines651f13c2014-04-23 16:59:28 -07002930 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002931 // This is recovered from gcc output.
2932 return 1; // r1 is the dedicated stack pointer
2933 }
2934
2935 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07002936 llvm::Value *Address) const override;
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002937};
2938
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002939class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2940public:
2941 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2942
Stephen Hines651f13c2014-04-23 16:59:28 -07002943 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002944 // This is recovered from gcc output.
2945 return 1; // r1 is the dedicated stack pointer
2946 }
2947
2948 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07002949 llvm::Value *Address) const override;
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002950};
2951
2952}
2953
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002954// Return true if the ABI requires Ty to be passed sign- or zero-
2955// extended to 64 bits.
2956bool
2957PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2958 // Treat an enum type as its underlying type.
2959 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2960 Ty = EnumTy->getDecl()->getIntegerType();
2961
2962 // Promotable integer types are required to be promoted by the ABI.
2963 if (Ty->isPromotableIntegerType())
2964 return true;
2965
2966 // In addition to the usual promotable integer types, we also need to
2967 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2968 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2969 switch (BT->getKind()) {
2970 case BuiltinType::Int:
2971 case BuiltinType::UInt:
2972 return true;
2973 default:
2974 break;
2975 }
2976
2977 return false;
2978}
2979
2980ABIArgInfo
2981PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidtc9715fc2012-11-27 02:46:43 +00002982 if (Ty->isAnyComplexType())
2983 return ABIArgInfo::getDirect();
2984
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002985 if (isAggregateTypeForABI(Ty)) {
Mark Lacey23630722013-10-06 01:33:34 +00002986 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002987 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002988
2989 return ABIArgInfo::getIndirect(0);
2990 }
2991
2992 return (isPromotableTypeForABI(Ty) ?
2993 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2994}
2995
2996ABIArgInfo
2997PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
2998 if (RetTy->isVoidType())
2999 return ABIArgInfo::getIgnore();
3000
Bill Schmidt9e6111a2012-12-17 04:20:17 +00003001 if (RetTy->isAnyComplexType())
3002 return ABIArgInfo::getDirect();
3003
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003004 if (isAggregateTypeForABI(RetTy))
3005 return ABIArgInfo::getIndirect(0);
3006
3007 return (isPromotableTypeForABI(RetTy) ?
3008 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3009}
3010
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003011// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3012llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3013 QualType Ty,
3014 CodeGenFunction &CGF) const {
3015 llvm::Type *BP = CGF.Int8PtrTy;
3016 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3017
3018 CGBuilderTy &Builder = CGF.Builder;
3019 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3020 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3021
Bill Schmidt19f8e852013-01-14 17:45:36 +00003022 // Update the va_list pointer. The pointer should be bumped by the
3023 // size of the object. We can trust getTypeSize() except for a complex
3024 // type whose base type is smaller than a doubleword. For these, the
3025 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003026 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt19f8e852013-01-14 17:45:36 +00003027 QualType BaseTy;
3028 unsigned CplxBaseSize = 0;
3029
3030 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3031 BaseTy = CTy->getElementType();
3032 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3033 if (CplxBaseSize < 8)
3034 SizeInBytes = 16;
3035 }
3036
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003037 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3038 llvm::Value *NextAddr =
3039 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3040 "ap.next");
3041 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3042
Bill Schmidt19f8e852013-01-14 17:45:36 +00003043 // If we have a complex type and the base type is smaller than 8 bytes,
3044 // the ABI calls for the real and imaginary parts to be right-adjusted
3045 // in separate doublewords. However, Clang expects us to produce a
3046 // pointer to a structure with the two parts packed tightly. So generate
3047 // loads of the real and imaginary parts relative to the va_list pointer,
3048 // and store them to a temporary structure.
3049 if (CplxBaseSize && CplxBaseSize < 8) {
3050 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3051 llvm::Value *ImagAddr = RealAddr;
3052 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3053 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3054 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3055 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3056 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3057 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3058 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3059 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3060 "vacplx");
3061 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3062 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3063 Builder.CreateStore(Real, RealPtr, false);
3064 Builder.CreateStore(Imag, ImagPtr, false);
3065 return Ptr;
3066 }
3067
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003068 // If the argument is smaller than 8 bytes, it is right-adjusted in
3069 // its doubleword slot. Adjust the pointer to pick it up from the
3070 // correct offset.
3071 if (SizeInBytes < 8) {
3072 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3073 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3074 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3075 }
3076
3077 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3078 return Builder.CreateBitCast(Addr, PTy);
3079}
3080
3081static bool
3082PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3083 llvm::Value *Address) {
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003084 // This is calculated from the LLVM and GCC tables and verified
3085 // against gcc output. AFAIK all ABIs use the same encoding.
3086
3087 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3088
3089 llvm::IntegerType *i8 = CGF.Int8Ty;
3090 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3091 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3092 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3093
3094 // 0-31: r0-31, the 8-byte general-purpose registers
3095 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3096
3097 // 32-63: fp0-31, the 8-byte floating-point registers
3098 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3099
3100 // 64-76 are various 4-byte special-purpose registers:
3101 // 64: mq
3102 // 65: lr
3103 // 66: ctr
3104 // 67: ap
3105 // 68-75 cr0-7
3106 // 76: xer
3107 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3108
3109 // 77-108: v0-31, the 16-byte vector registers
3110 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3111
3112 // 109: vrsave
3113 // 110: vscr
3114 // 111: spe_acc
3115 // 112: spefscr
3116 // 113: sfp
3117 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3118
3119 return false;
3120}
John McCallec853ba2010-03-11 00:10:12 +00003121
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003122bool
3123PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3124 CodeGen::CodeGenFunction &CGF,
3125 llvm::Value *Address) const {
3126
3127 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3128}
3129
3130bool
3131PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3132 llvm::Value *Address) const {
3133
3134 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3135}
3136
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003137//===----------------------------------------------------------------------===//
Stephen Hines651f13c2014-04-23 16:59:28 -07003138// ARM64 ABI Implementation
3139//===----------------------------------------------------------------------===//
3140
3141namespace {
3142
3143class ARM64ABIInfo : public ABIInfo {
3144public:
3145 enum ABIKind {
3146 AAPCS = 0,
3147 DarwinPCS
3148 };
3149
3150private:
3151 ABIKind Kind;
3152
3153public:
3154 ARM64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
3155
3156private:
3157 ABIKind getABIKind() const { return Kind; }
3158 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3159
3160 ABIArgInfo classifyReturnType(QualType RetTy) const;
3161 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3162 bool &IsHA, unsigned &AllocatedGPR,
3163 bool &IsSmallAggr) const;
3164 bool isIllegalVectorType(QualType Ty) const;
3165
3166 virtual void computeInfo(CGFunctionInfo &FI) const {
3167 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3168 // number of SIMD and Floating-point registers allocated so far.
3169 // If the argument is an HFA or an HVA and there are sufficient unallocated
3170 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3171 // and Floating-point Registers (with one register per member of the HFA or
3172 // HVA). Otherwise, the NSRN is set to 8.
3173 unsigned AllocatedVFP = 0;
3174 // To correctly handle small aggregates, we need to keep track of the number
3175 // of GPRs allocated so far. If the small aggregate can't all fit into
3176 // registers, it will be on stack. We don't allow the aggregate to be
3177 // partially in registers.
3178 unsigned AllocatedGPR = 0;
3179 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3180 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3181 it != ie; ++it) {
3182 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3183 bool IsHA = false, IsSmallAggr = false;
3184 const unsigned NumVFPs = 8;
3185 const unsigned NumGPRs = 8;
3186 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
3187 AllocatedGPR, IsSmallAggr);
3188 // If we do not have enough VFP registers for the HA, any VFP registers
3189 // that are unallocated are marked as unavailable. To achieve this, we add
3190 // padding of (NumVFPs - PreAllocation) floats.
3191 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3192 llvm::Type *PaddingTy = llvm::ArrayType::get(
3193 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3194 if (isDarwinPCS())
3195 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3196 else {
3197 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3198 // as sequences of floats since they'll get "holes" inserted as
3199 // padding by the back end.
3200 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3201 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
3202
3203 llvm::Type *CoerceTy = llvm::ArrayType::get(
3204 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3205 it->info = ABIArgInfo::getDirect(CoerceTy, 0, PaddingTy);
3206 }
3207 }
3208 // If we do not have enough GPRs for the small aggregate, any GPR regs
3209 // that are unallocated are marked as unavailable.
3210 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3211 llvm::Type *PaddingTy = llvm::ArrayType::get(
3212 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3213 it->info =
3214 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3215 }
3216 }
3217 }
3218
3219 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3220 CodeGenFunction &CGF) const;
3221
3222 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3223 CodeGenFunction &CGF) const;
3224
3225 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3226 CodeGenFunction &CGF) const {
3227 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3228 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3229 }
3230};
3231
3232class ARM64TargetCodeGenInfo : public TargetCodeGenInfo {
3233public:
3234 ARM64TargetCodeGenInfo(CodeGenTypes &CGT, ARM64ABIInfo::ABIKind Kind)
3235 : TargetCodeGenInfo(new ARM64ABIInfo(CGT, Kind)) {}
3236
3237 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3238 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3239 }
3240
3241 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3242
3243 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3244};
3245}
3246
3247static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3248 ASTContext &Context,
3249 uint64_t *HAMembers = 0);
3250
3251ABIArgInfo ARM64ABIInfo::classifyArgumentType(QualType Ty,
3252 unsigned &AllocatedVFP,
3253 bool &IsHA,
3254 unsigned &AllocatedGPR,
3255 bool &IsSmallAggr) const {
3256 // Handle illegal vector types here.
3257 if (isIllegalVectorType(Ty)) {
3258 uint64_t Size = getContext().getTypeSize(Ty);
3259 if (Size <= 32) {
3260 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3261 AllocatedGPR++;
3262 return ABIArgInfo::getDirect(ResType);
3263 }
3264 if (Size == 64) {
3265 llvm::Type *ResType =
3266 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3267 AllocatedVFP++;
3268 return ABIArgInfo::getDirect(ResType);
3269 }
3270 if (Size == 128) {
3271 llvm::Type *ResType =
3272 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3273 AllocatedVFP++;
3274 return ABIArgInfo::getDirect(ResType);
3275 }
3276 AllocatedGPR++;
3277 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3278 }
3279 if (Ty->isVectorType())
3280 // Size of a legal vector should be either 64 or 128.
3281 AllocatedVFP++;
3282 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3283 if (BT->getKind() == BuiltinType::Half ||
3284 BT->getKind() == BuiltinType::Float ||
3285 BT->getKind() == BuiltinType::Double ||
3286 BT->getKind() == BuiltinType::LongDouble)
3287 AllocatedVFP++;
3288 }
3289
3290 if (!isAggregateTypeForABI(Ty)) {
3291 // Treat an enum type as its underlying type.
3292 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3293 Ty = EnumTy->getDecl()->getIntegerType();
3294
3295 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
3296 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3297 AllocatedGPR += RegsNeeded;
3298 }
3299 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3300 ? ABIArgInfo::getExtend()
3301 : ABIArgInfo::getDirect());
3302 }
3303
3304 // Structures with either a non-trivial destructor or a non-trivial
3305 // copy constructor are always indirect.
3306 if (isRecordReturnIndirect(Ty, getCXXABI())) {
3307 AllocatedGPR++;
3308 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3309 }
3310
3311 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3312 // elsewhere for GNU compatibility.
3313 if (isEmptyRecord(getContext(), Ty, true)) {
3314 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3315 return ABIArgInfo::getIgnore();
3316
3317 ++AllocatedGPR;
3318 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3319 }
3320
3321 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
3322 const Type *Base = 0;
3323 uint64_t Members = 0;
3324 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
3325 AllocatedVFP += Members;
3326 IsHA = true;
3327 return ABIArgInfo::getExpand();
3328 }
3329
3330 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3331 uint64_t Size = getContext().getTypeSize(Ty);
3332 if (Size <= 128) {
3333 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3334 AllocatedGPR += Size / 64;
3335 IsSmallAggr = true;
3336 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3337 // For aggregates with 16-byte alignment, we use i128.
3338 if (getContext().getTypeAlign(Ty) < 128 && Size == 128) {
3339 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3340 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3341 }
3342 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3343 }
3344
3345 AllocatedGPR++;
3346 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3347}
3348
3349ABIArgInfo ARM64ABIInfo::classifyReturnType(QualType RetTy) const {
3350 if (RetTy->isVoidType())
3351 return ABIArgInfo::getIgnore();
3352
3353 // Large vector types should be returned via memory.
3354 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3355 return ABIArgInfo::getIndirect(0);
3356
3357 if (!isAggregateTypeForABI(RetTy)) {
3358 // Treat an enum type as its underlying type.
3359 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3360 RetTy = EnumTy->getDecl()->getIntegerType();
3361
3362 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
3363 : ABIArgInfo::getDirect());
3364 }
3365
3366 // Structures with either a non-trivial destructor or a non-trivial
3367 // copy constructor are always indirect.
3368 if (isRecordReturnIndirect(RetTy, getCXXABI()))
3369 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3370
3371 if (isEmptyRecord(getContext(), RetTy, true))
3372 return ABIArgInfo::getIgnore();
3373
3374 const Type *Base = 0;
3375 if (isHomogeneousAggregate(RetTy, Base, getContext()))
3376 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3377 return ABIArgInfo::getDirect();
3378
3379 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3380 uint64_t Size = getContext().getTypeSize(RetTy);
3381 if (Size <= 128) {
3382 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3383 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3384 }
3385
3386 return ABIArgInfo::getIndirect(0);
3387}
3388
3389/// isIllegalVectorType - check whether the vector type is legal for ARM64.
3390bool ARM64ABIInfo::isIllegalVectorType(QualType Ty) const {
3391 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3392 // Check whether VT is legal.
3393 unsigned NumElements = VT->getNumElements();
3394 uint64_t Size = getContext().getTypeSize(VT);
3395 // NumElements should be power of 2 between 1 and 16.
3396 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3397 return true;
3398 return Size != 64 && (Size != 128 || NumElements == 1);
3399 }
3400 return false;
3401}
3402
3403static llvm::Value *EmitAArch64VAArg(llvm::Value *VAListAddr, QualType Ty,
3404 int AllocatedGPR, int AllocatedVFP,
3405 bool IsIndirect, CodeGenFunction &CGF) {
3406 // The AArch64 va_list type and handling is specified in the Procedure Call
3407 // Standard, section B.4:
3408 //
3409 // struct {
3410 // void *__stack;
3411 // void *__gr_top;
3412 // void *__vr_top;
3413 // int __gr_offs;
3414 // int __vr_offs;
3415 // };
3416
3417 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3418 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3419 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3420 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3421 auto &Ctx = CGF.getContext();
3422
3423 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
3424 int reg_top_index;
3425 int RegSize;
3426 if (AllocatedGPR) {
3427 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
3428 // 3 is the field number of __gr_offs
3429 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3430 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3431 reg_top_index = 1; // field number for __gr_top
3432 RegSize = 8 * AllocatedGPR;
3433 } else {
3434 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
3435 // 4 is the field number of __vr_offs.
3436 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3437 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3438 reg_top_index = 2; // field number for __vr_top
3439 RegSize = 16 * AllocatedVFP;
3440 }
3441
3442 //=======================================
3443 // Find out where argument was passed
3444 //=======================================
3445
3446 // If reg_offs >= 0 we're already using the stack for this type of
3447 // argument. We don't want to keep updating reg_offs (in case it overflows,
3448 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3449 // whatever they get).
3450 llvm::Value *UsingStack = 0;
3451 UsingStack = CGF.Builder.CreateICmpSGE(
3452 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
3453
3454 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3455
3456 // Otherwise, at least some kind of argument could go in these registers, the
3457 // quesiton is whether this particular type is too big.
3458 CGF.EmitBlock(MaybeRegBlock);
3459
3460 // Integer arguments may need to correct register alignment (for example a
3461 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3462 // align __gr_offs to calculate the potential address.
3463 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3464 int Align = Ctx.getTypeAlign(Ty) / 8;
3465
3466 reg_offs = CGF.Builder.CreateAdd(
3467 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3468 "align_regoffs");
3469 reg_offs = CGF.Builder.CreateAnd(
3470 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3471 "aligned_regoffs");
3472 }
3473
3474 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
3475 llvm::Value *NewOffset = 0;
3476 NewOffset = CGF.Builder.CreateAdd(
3477 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
3478 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3479
3480 // Now we're in a position to decide whether this argument really was in
3481 // registers or not.
3482 llvm::Value *InRegs = 0;
3483 InRegs = CGF.Builder.CreateICmpSLE(
3484 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
3485
3486 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
3487
3488 //=======================================
3489 // Argument was in registers
3490 //=======================================
3491
3492 // Now we emit the code for if the argument was originally passed in
3493 // registers. First start the appropriate block:
3494 CGF.EmitBlock(InRegBlock);
3495
3496 llvm::Value *reg_top_p = 0, *reg_top = 0;
3497 reg_top_p =
3498 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
3499 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
3500 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
3501 llvm::Value *RegAddr = 0;
3502 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
3503
3504 if (IsIndirect) {
3505 // If it's been passed indirectly (actually a struct), whatever we find from
3506 // stored registers or on the stack will actually be a struct **.
3507 MemTy = llvm::PointerType::getUnqual(MemTy);
3508 }
3509
3510 const Type *Base = 0;
3511 uint64_t NumMembers;
3512 if (isHomogeneousAggregate(Ty, Base, Ctx, &NumMembers) && NumMembers > 1) {
3513 // Homogeneous aggregates passed in registers will have their elements split
3514 // and stored 16-bytes apart regardless of size (they're notionally in qN,
3515 // qN+1, ...). We reload and store into a temporary local variable
3516 // contiguously.
3517 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
3518 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
3519 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
3520 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
3521 int Offset = 0;
3522
3523 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
3524 Offset = 16 - Ctx.getTypeSize(Base) / 8;
3525 for (unsigned i = 0; i < NumMembers; ++i) {
3526 llvm::Value *BaseOffset =
3527 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
3528 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
3529 LoadAddr = CGF.Builder.CreateBitCast(
3530 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
3531 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
3532
3533 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
3534 CGF.Builder.CreateStore(Elem, StoreAddr);
3535 }
3536
3537 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
3538 } else {
3539 // Otherwise the object is contiguous in memory
3540 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
3541 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
3542 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
3543 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
3544 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
3545
3546 BaseAddr = CGF.Builder.CreateAdd(
3547 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3548
3549 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
3550 }
3551
3552 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
3553 }
3554
3555 CGF.EmitBranch(ContBlock);
3556
3557 //=======================================
3558 // Argument was on the stack
3559 //=======================================
3560 CGF.EmitBlock(OnStackBlock);
3561
3562 llvm::Value *stack_p = 0, *OnStackAddr = 0;
3563 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
3564 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
3565
3566 // Again, stack arguments may need realigmnent. In this case both integer and
3567 // floating-point ones might be affected.
3568 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3569 int Align = Ctx.getTypeAlign(Ty) / 8;
3570
3571 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3572
3573 OnStackAddr = CGF.Builder.CreateAdd(
3574 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
3575 "align_stack");
3576 OnStackAddr = CGF.Builder.CreateAnd(
3577 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
3578 "align_stack");
3579
3580 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3581 }
3582
3583 uint64_t StackSize;
3584 if (IsIndirect)
3585 StackSize = 8;
3586 else
3587 StackSize = Ctx.getTypeSize(Ty) / 8;
3588
3589 // All stack slots are 8 bytes
3590 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
3591
3592 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
3593 llvm::Value *NewStack =
3594 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
3595
3596 // Write the new value of __stack for the next call to va_arg
3597 CGF.Builder.CreateStore(NewStack, stack_p);
3598
3599 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
3600 Ctx.getTypeSize(Ty) < 64) {
3601 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
3602 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3603
3604 OnStackAddr = CGF.Builder.CreateAdd(
3605 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3606
3607 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3608 }
3609
3610 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
3611
3612 CGF.EmitBranch(ContBlock);
3613
3614 //=======================================
3615 // Tidy up
3616 //=======================================
3617 CGF.EmitBlock(ContBlock);
3618
3619 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
3620 ResAddr->addIncoming(RegAddr, InRegBlock);
3621 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
3622
3623 if (IsIndirect)
3624 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
3625
3626 return ResAddr;
3627}
3628
3629llvm::Value *ARM64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3630 CodeGenFunction &CGF) const {
3631
3632 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
3633 bool IsHA = false, IsSmallAggr = false;
3634 ABIArgInfo AI =
3635 classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR, IsSmallAggr);
3636
3637 return EmitAArch64VAArg(VAListAddr, Ty, AllocatedGPR, AllocatedVFP,
3638 AI.isIndirect(), CGF);
3639}
3640
3641llvm::Value *ARM64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3642 CodeGenFunction &CGF) const {
3643 // We do not support va_arg for aggregates or illegal vector types.
3644 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
3645 // other cases.
3646 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
3647 return 0;
3648
3649 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
3650 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
3651
3652 const Type *Base = 0;
3653 bool isHA = isHomogeneousAggregate(Ty, Base, getContext());
3654
3655 bool isIndirect = false;
3656 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
3657 // be passed indirectly.
3658 if (Size > 16 && !isHA) {
3659 isIndirect = true;
3660 Size = 8;
3661 Align = 8;
3662 }
3663
3664 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
3665 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
3666
3667 CGBuilderTy &Builder = CGF.Builder;
3668 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3669 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3670
3671 if (isEmptyRecord(getContext(), Ty, true)) {
3672 // These are ignored for parameter passing purposes.
3673 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3674 return Builder.CreateBitCast(Addr, PTy);
3675 }
3676
3677 const uint64_t MinABIAlign = 8;
3678 if (Align > MinABIAlign) {
3679 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
3680 Addr = Builder.CreateGEP(Addr, Offset);
3681 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3682 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
3683 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
3684 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
3685 }
3686
3687 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
3688 llvm::Value *NextAddr = Builder.CreateGEP(
3689 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
3690 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3691
3692 if (isIndirect)
3693 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
3694 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3695 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3696
3697 return AddrTyped;
3698}
3699
3700//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003701// ARM ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003702//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003703
3704namespace {
3705
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003706class ARMABIInfo : public ABIInfo {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003707public:
3708 enum ABIKind {
3709 APCS = 0,
3710 AAPCS = 1,
3711 AAPCS_VFP
3712 };
3713
3714private:
3715 ABIKind Kind;
Stephen Hines651f13c2014-04-23 16:59:28 -07003716 mutable int VFPRegs[16];
3717 const unsigned NumVFPs;
3718 const unsigned NumGPRs;
3719 mutable unsigned AllocatedGPRs;
3720 mutable unsigned AllocatedVFPs;
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003721
3722public:
Stephen Hines651f13c2014-04-23 16:59:28 -07003723 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
3724 NumVFPs(16), NumGPRs(4) {
John McCallbd7370a2013-02-28 19:01:20 +00003725 setRuntimeCC();
Stephen Hines651f13c2014-04-23 16:59:28 -07003726 resetAllocatedRegs();
John McCallbd7370a2013-02-28 19:01:20 +00003727 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003728
John McCall49e34be2011-08-30 01:42:09 +00003729 bool isEABI() const {
Stephen Hines651f13c2014-04-23 16:59:28 -07003730 switch (getTarget().getTriple().getEnvironment()) {
3731 case llvm::Triple::Android:
3732 case llvm::Triple::EABI:
3733 case llvm::Triple::EABIHF:
3734 case llvm::Triple::GNUEABI:
3735 case llvm::Triple::GNUEABIHF:
3736 return true;
3737 default:
3738 return false;
3739 }
3740 }
3741
3742 bool isEABIHF() const {
3743 switch (getTarget().getTriple().getEnvironment()) {
3744 case llvm::Triple::EABIHF:
3745 case llvm::Triple::GNUEABIHF:
3746 return true;
3747 default:
3748 return false;
3749 }
John McCall49e34be2011-08-30 01:42:09 +00003750 }
3751
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003752 ABIKind getABIKind() const { return Kind; }
3753
Tim Northover64eac852013-10-01 14:34:25 +00003754private:
Stephen Hines651f13c2014-04-23 16:59:28 -07003755 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
3756 ABIArgInfo classifyArgumentType(QualType RetTy, bool &IsHA, bool isVariadic,
3757 bool &IsCPRC) const;
Manman Ren97f81572012-10-16 19:18:39 +00003758 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003759
Stephen Hines651f13c2014-04-23 16:59:28 -07003760 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003761
Stephen Hines651f13c2014-04-23 16:59:28 -07003762 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3763 CodeGenFunction &CGF) const override;
John McCallbd7370a2013-02-28 19:01:20 +00003764
3765 llvm::CallingConv::ID getLLVMDefaultCC() const;
3766 llvm::CallingConv::ID getABIDefaultCC() const;
3767 void setRuntimeCC();
Stephen Hines651f13c2014-04-23 16:59:28 -07003768
3769 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
3770 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
3771 void resetAllocatedRegs(void) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003772};
3773
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00003774class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3775public:
Chris Lattnerea044322010-07-29 02:01:43 +00003776 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3777 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCall6374c332010-03-06 00:35:14 +00003778
John McCall49e34be2011-08-30 01:42:09 +00003779 const ARMABIInfo &getABIInfo() const {
3780 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3781 }
3782
Stephen Hines651f13c2014-04-23 16:59:28 -07003783 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCall6374c332010-03-06 00:35:14 +00003784 return 13;
3785 }
Roman Divacky09345d12011-05-18 19:36:54 +00003786
Stephen Hines651f13c2014-04-23 16:59:28 -07003787 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCallf85e1932011-06-15 23:02:42 +00003788 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3789 }
3790
Roman Divacky09345d12011-05-18 19:36:54 +00003791 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07003792 llvm::Value *Address) const override {
Chris Lattner8b418682012-02-07 00:39:47 +00003793 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divacky09345d12011-05-18 19:36:54 +00003794
3795 // 0-15 are the 16 integer registers.
Chris Lattner8b418682012-02-07 00:39:47 +00003796 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divacky09345d12011-05-18 19:36:54 +00003797 return false;
3798 }
John McCall49e34be2011-08-30 01:42:09 +00003799
Stephen Hines651f13c2014-04-23 16:59:28 -07003800 unsigned getSizeOfUnwindException() const override {
John McCall49e34be2011-08-30 01:42:09 +00003801 if (getABIInfo().isEABI()) return 88;
3802 return TargetCodeGenInfo::getSizeOfUnwindException();
3803 }
Tim Northover64eac852013-10-01 14:34:25 +00003804
3805 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -07003806 CodeGen::CodeGenModule &CGM) const override {
Tim Northover64eac852013-10-01 14:34:25 +00003807 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3808 if (!FD)
3809 return;
3810
3811 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3812 if (!Attr)
3813 return;
3814
3815 const char *Kind;
3816 switch (Attr->getInterrupt()) {
3817 case ARMInterruptAttr::Generic: Kind = ""; break;
3818 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3819 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3820 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3821 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3822 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3823 }
3824
3825 llvm::Function *Fn = cast<llvm::Function>(GV);
3826
3827 Fn->addFnAttr("interrupt", Kind);
3828
3829 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3830 return;
3831
3832 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3833 // however this is not necessarily true on taking any interrupt. Instruct
3834 // the backend to perform a realignment as part of the function prologue.
3835 llvm::AttrBuilder B;
3836 B.addStackAlignmentAttr(8);
3837 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3838 llvm::AttributeSet::get(CGM.getLLVMContext(),
3839 llvm::AttributeSet::FunctionIndex,
3840 B));
3841 }
3842
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00003843};
3844
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003845}
3846
Chris Lattneree5dcd02010-07-29 02:31:05 +00003847void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Renb3fa55f2012-10-30 23:21:41 +00003848 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Ren710c5172012-10-31 19:02:26 +00003849 // VFP registers allocated so far.
Manman Renb3fa55f2012-10-30 23:21:41 +00003850 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3851 // VFP registers of the appropriate type unallocated then the argument is
3852 // allocated to the lowest-numbered sequence of such registers.
3853 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3854 // unallocated are marked as unavailable.
Stephen Hines651f13c2014-04-23 16:59:28 -07003855 resetAllocatedRegs();
3856
3857 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
3858 for (auto &I : FI.arguments()) {
3859 unsigned PreAllocationVFPs = AllocatedVFPs;
3860 unsigned PreAllocationGPRs = AllocatedGPRs;
Manman Renb3fa55f2012-10-30 23:21:41 +00003861 bool IsHA = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07003862 bool IsCPRC = false;
Manman Renb3fa55f2012-10-30 23:21:41 +00003863 // 6.1.2.3 There is one VFP co-processor register class using registers
3864 // s0-s15 (d0-d7) for passing arguments.
Stephen Hines651f13c2014-04-23 16:59:28 -07003865 I.info = classifyArgumentType(I.type, IsHA, FI.isVariadic(), IsCPRC);
3866 assert((IsCPRC || !IsHA) && "Homogeneous aggregates must be CPRCs");
Manman Renb3fa55f2012-10-30 23:21:41 +00003867 // If we do not have enough VFP registers for the HA, any VFP registers
3868 // that are unallocated are marked as unavailable. To achieve this, we add
Stephen Hines651f13c2014-04-23 16:59:28 -07003869 // padding of (NumVFPs - PreAllocationVFP) floats.
3870 // Note that IsHA will only be set when using the AAPCS-VFP calling convention,
3871 // and the callee is not variadic.
3872 if (IsHA && AllocatedVFPs > NumVFPs && PreAllocationVFPs < NumVFPs) {
Manman Renb3fa55f2012-10-30 23:21:41 +00003873 llvm::Type *PaddingTy = llvm::ArrayType::get(
Stephen Hines651f13c2014-04-23 16:59:28 -07003874 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocationVFPs);
3875 I.info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3876 }
3877
3878 // If we have allocated some arguments onto the stack (due to running
3879 // out of VFP registers), we cannot split an argument between GPRs and
3880 // the stack. If this situation occurs, we add padding to prevent the
3881 // GPRs from being used. In this situiation, the current argument could
3882 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
3883 // unusable anyway.
3884 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
3885 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs && StackUsed) {
3886 llvm::Type *PaddingTy = llvm::ArrayType::get(
3887 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
3888 I.info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
Manman Renb3fa55f2012-10-30 23:21:41 +00003889 }
3890 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003891
Anton Korobeynikov414d8962011-04-14 20:06:49 +00003892 // Always honor user-specified calling convention.
3893 if (FI.getCallingConvention() != llvm::CallingConv::C)
3894 return;
3895
John McCallbd7370a2013-02-28 19:01:20 +00003896 llvm::CallingConv::ID cc = getRuntimeCC();
3897 if (cc != llvm::CallingConv::C)
3898 FI.setEffectiveCallingConvention(cc);
3899}
Rafael Espindola25117ab2010-06-16 16:13:39 +00003900
John McCallbd7370a2013-02-28 19:01:20 +00003901/// Return the default calling convention that LLVM will use.
3902llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3903 // The default calling convention that LLVM will infer.
Stephen Hines651f13c2014-04-23 16:59:28 -07003904 if (isEABIHF())
John McCallbd7370a2013-02-28 19:01:20 +00003905 return llvm::CallingConv::ARM_AAPCS_VFP;
3906 else if (isEABI())
3907 return llvm::CallingConv::ARM_AAPCS;
3908 else
3909 return llvm::CallingConv::ARM_APCS;
3910}
3911
3912/// Return the calling convention that our ABI would like us to use
3913/// as the C calling convention.
3914llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003915 switch (getABIKind()) {
John McCallbd7370a2013-02-28 19:01:20 +00003916 case APCS: return llvm::CallingConv::ARM_APCS;
3917 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3918 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003919 }
John McCallbd7370a2013-02-28 19:01:20 +00003920 llvm_unreachable("bad ABI kind");
3921}
3922
3923void ARMABIInfo::setRuntimeCC() {
3924 assert(getRuntimeCC() == llvm::CallingConv::C);
3925
3926 // Don't muddy up the IR with a ton of explicit annotations if
3927 // they'd just match what LLVM will infer from the triple.
3928 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3929 if (abiCC != getLLVMDefaultCC())
3930 RuntimeCC = abiCC;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003931}
3932
Bob Wilson194f06a2011-08-03 05:58:22 +00003933/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3934/// aggregate. If HAMembers is non-null, the number of base elements
3935/// contained in the type is returned through it; this is used for the
3936/// recursive calls that check aggregate component types.
3937static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
Stephen Hines651f13c2014-04-23 16:59:28 -07003938 ASTContext &Context, uint64_t *HAMembers) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003939 uint64_t Members = 0;
Bob Wilson194f06a2011-08-03 05:58:22 +00003940 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3941 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3942 return false;
3943 Members *= AT->getSize().getZExtValue();
3944 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3945 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003946 if (RD->hasFlexibleArrayMember())
Bob Wilson194f06a2011-08-03 05:58:22 +00003947 return false;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003948
Bob Wilson194f06a2011-08-03 05:58:22 +00003949 Members = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07003950 for (const auto *FD : RD->fields()) {
Bob Wilson194f06a2011-08-03 05:58:22 +00003951 uint64_t FldMembers;
3952 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3953 return false;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003954
3955 Members = (RD->isUnion() ?
3956 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilson194f06a2011-08-03 05:58:22 +00003957 }
3958 } else {
3959 Members = 1;
3960 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3961 Members = 2;
3962 Ty = CT->getElementType();
3963 }
3964
3965 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3966 // double, or 64-bit or 128-bit vectors.
3967 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3968 if (BT->getKind() != BuiltinType::Float &&
Tim Northoveradfa45f2012-07-20 22:29:29 +00003969 BT->getKind() != BuiltinType::Double &&
3970 BT->getKind() != BuiltinType::LongDouble)
Bob Wilson194f06a2011-08-03 05:58:22 +00003971 return false;
3972 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3973 unsigned VecSize = Context.getTypeSize(VT);
3974 if (VecSize != 64 && VecSize != 128)
3975 return false;
3976 } else {
3977 return false;
3978 }
3979
3980 // The base type must be the same for all members. Vector types of the
3981 // same total size are treated as being equivalent here.
3982 const Type *TyPtr = Ty.getTypePtr();
3983 if (!Base)
3984 Base = TyPtr;
Stephen Hines651f13c2014-04-23 16:59:28 -07003985
3986 if (Base != TyPtr) {
3987 // Homogeneous aggregates are defined as containing members with the
3988 // same machine type. There are two cases in which two members have
3989 // different TypePtrs but the same machine type:
3990
3991 // 1) Vectors of the same length, regardless of the type and number
3992 // of their members.
3993 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
3994 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
3995
3996 // 2) In the 32-bit AAPCS, `double' and `long double' have the same
3997 // machine type. This is not the case for the 64-bit AAPCS.
3998 const bool SameSizeDoubles =
3999 ( ( Base->isSpecificBuiltinType(BuiltinType::Double)
4000 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
4001 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble)
4002 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
4003 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4004
4005 if (!SameLengthVectors && !SameSizeDoubles)
4006 return false;
4007 }
Bob Wilson194f06a2011-08-03 05:58:22 +00004008 }
4009
4010 // Homogeneous Aggregates can have at most 4 members of the base type.
4011 if (HAMembers)
4012 *HAMembers = Members;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004013
4014 return (Members > 0 && Members <= 4);
Bob Wilson194f06a2011-08-03 05:58:22 +00004015}
4016
Manman Ren710c5172012-10-31 19:02:26 +00004017/// markAllocatedVFPs - update VFPRegs according to the alignment and
4018/// number of VFP registers (unit is S register) requested.
Stephen Hines651f13c2014-04-23 16:59:28 -07004019void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4020 unsigned NumRequired) const {
Manman Ren710c5172012-10-31 19:02:26 +00004021 // Early Exit.
Stephen Hines651f13c2014-04-23 16:59:28 -07004022 if (AllocatedVFPs >= 16) {
4023 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4024 // the stack.
4025 AllocatedVFPs = 17;
Manman Ren710c5172012-10-31 19:02:26 +00004026 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07004027 }
Manman Ren710c5172012-10-31 19:02:26 +00004028 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4029 // VFP registers of the appropriate type unallocated then the argument is
4030 // allocated to the lowest-numbered sequence of such registers.
4031 for (unsigned I = 0; I < 16; I += Alignment) {
4032 bool FoundSlot = true;
4033 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4034 if (J >= 16 || VFPRegs[J]) {
4035 FoundSlot = false;
4036 break;
4037 }
4038 if (FoundSlot) {
4039 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4040 VFPRegs[J] = 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07004041 AllocatedVFPs += NumRequired;
Manman Ren710c5172012-10-31 19:02:26 +00004042 return;
4043 }
4044 }
4045 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4046 // unallocated are marked as unavailable.
4047 for (unsigned I = 0; I < 16; I++)
4048 VFPRegs[I] = 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07004049 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Ren710c5172012-10-31 19:02:26 +00004050}
4051
Stephen Hines651f13c2014-04-23 16:59:28 -07004052/// Update AllocatedGPRs to record the number of general purpose registers
4053/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4054/// this represents arguments being stored on the stack.
4055void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
4056 unsigned NumRequired) const {
4057 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4058
4059 if (Alignment == 2 && AllocatedGPRs & 0x1)
4060 AllocatedGPRs += 1;
4061
4062 AllocatedGPRs += NumRequired;
4063}
4064
4065void ARMABIInfo::resetAllocatedRegs(void) const {
4066 AllocatedGPRs = 0;
4067 AllocatedVFPs = 0;
4068 for (unsigned i = 0; i < NumVFPs; ++i)
4069 VFPRegs[i] = 0;
4070}
4071
4072ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool &IsHA,
4073 bool isVariadic,
4074 bool &IsCPRC) const {
Manman Renb3fa55f2012-10-30 23:21:41 +00004075 // We update number of allocated VFPs according to
4076 // 6.1.2.1 The following argument types are VFP CPRCs:
4077 // A single-precision floating-point type (including promoted
4078 // half-precision types); A double-precision floating-point type;
4079 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4080 // with a Base Type of a single- or double-precision floating-point type,
4081 // 64-bit containerized vectors or 128-bit containerized vectors with one
4082 // to four Elements.
4083
Manman Ren97f81572012-10-16 19:18:39 +00004084 // Handle illegal vector types here.
4085 if (isIllegalVectorType(Ty)) {
4086 uint64_t Size = getContext().getTypeSize(Ty);
4087 if (Size <= 32) {
4088 llvm::Type *ResType =
4089 llvm::Type::getInt32Ty(getVMContext());
Stephen Hines651f13c2014-04-23 16:59:28 -07004090 markAllocatedGPRs(1, 1);
Manman Ren97f81572012-10-16 19:18:39 +00004091 return ABIArgInfo::getDirect(ResType);
4092 }
4093 if (Size == 64) {
4094 llvm::Type *ResType = llvm::VectorType::get(
4095 llvm::Type::getInt32Ty(getVMContext()), 2);
Stephen Hines651f13c2014-04-23 16:59:28 -07004096 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4097 markAllocatedGPRs(2, 2);
4098 } else {
4099 markAllocatedVFPs(2, 2);
4100 IsCPRC = true;
4101 }
Manman Ren97f81572012-10-16 19:18:39 +00004102 return ABIArgInfo::getDirect(ResType);
4103 }
4104 if (Size == 128) {
4105 llvm::Type *ResType = llvm::VectorType::get(
4106 llvm::Type::getInt32Ty(getVMContext()), 4);
Stephen Hines651f13c2014-04-23 16:59:28 -07004107 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4108 markAllocatedGPRs(2, 4);
4109 } else {
4110 markAllocatedVFPs(4, 4);
4111 IsCPRC = true;
4112 }
Manman Ren97f81572012-10-16 19:18:39 +00004113 return ABIArgInfo::getDirect(ResType);
4114 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004115 markAllocatedGPRs(1, 1);
Manman Ren97f81572012-10-16 19:18:39 +00004116 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4117 }
Manman Ren710c5172012-10-31 19:02:26 +00004118 // Update VFPRegs for legal vector types.
Stephen Hines651f13c2014-04-23 16:59:28 -07004119 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4120 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4121 uint64_t Size = getContext().getTypeSize(VT);
4122 // Size of a legal vector should be power of 2 and above 64.
4123 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4124 IsCPRC = true;
4125 }
Manman Renb3fa55f2012-10-30 23:21:41 +00004126 }
Manman Ren710c5172012-10-31 19:02:26 +00004127 // Update VFPRegs for floating point types.
Stephen Hines651f13c2014-04-23 16:59:28 -07004128 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4129 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4130 if (BT->getKind() == BuiltinType::Half ||
4131 BT->getKind() == BuiltinType::Float) {
4132 markAllocatedVFPs(1, 1);
4133 IsCPRC = true;
4134 }
4135 if (BT->getKind() == BuiltinType::Double ||
4136 BT->getKind() == BuiltinType::LongDouble) {
4137 markAllocatedVFPs(2, 2);
4138 IsCPRC = true;
4139 }
4140 }
Manman Renb3fa55f2012-10-30 23:21:41 +00004141 }
Manman Ren97f81572012-10-16 19:18:39 +00004142
John McCalld608cdb2010-08-22 10:59:02 +00004143 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004144 // Treat an enum type as its underlying type.
Stephen Hines651f13c2014-04-23 16:59:28 -07004145 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004146 Ty = EnumTy->getDecl()->getIntegerType();
Stephen Hines651f13c2014-04-23 16:59:28 -07004147 }
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004148
Stephen Hines651f13c2014-04-23 16:59:28 -07004149 unsigned Size = getContext().getTypeSize(Ty);
4150 if (!IsCPRC)
4151 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00004152 return (Ty->isPromotableIntegerType() ?
4153 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004154 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00004155
Stephen Hines651f13c2014-04-23 16:59:28 -07004156 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4157 markAllocatedGPRs(1, 1);
Tim Northoverf5c3a252013-06-21 22:49:34 +00004158 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Stephen Hines651f13c2014-04-23 16:59:28 -07004159 }
Tim Northoverf5c3a252013-06-21 22:49:34 +00004160
Daniel Dunbar42025572009-09-14 21:54:03 +00004161 // Ignore empty records.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004162 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar42025572009-09-14 21:54:03 +00004163 return ABIArgInfo::getIgnore();
4164
Stephen Hines651f13c2014-04-23 16:59:28 -07004165 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
Manman Renb3fa55f2012-10-30 23:21:41 +00004166 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4167 // into VFP registers.
Bob Wilson194f06a2011-08-03 05:58:22 +00004168 const Type *Base = 0;
Manman Renb3fa55f2012-10-30 23:21:41 +00004169 uint64_t Members = 0;
4170 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004171 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Renb3fa55f2012-10-30 23:21:41 +00004172 // Base can be a floating-point or a vector.
4173 if (Base->isVectorType()) {
4174 // ElementSize is in number of floats.
4175 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Stephen Hines651f13c2014-04-23 16:59:28 -07004176 markAllocatedVFPs(ElementSize,
Manman Rencb489dd2012-11-06 19:05:29 +00004177 Members * ElementSize);
Manman Renb3fa55f2012-10-30 23:21:41 +00004178 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Stephen Hines651f13c2014-04-23 16:59:28 -07004179 markAllocatedVFPs(1, Members);
Manman Renb3fa55f2012-10-30 23:21:41 +00004180 else {
4181 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4182 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Stephen Hines651f13c2014-04-23 16:59:28 -07004183 markAllocatedVFPs(2, Members * 2);
Manman Renb3fa55f2012-10-30 23:21:41 +00004184 }
4185 IsHA = true;
Stephen Hines651f13c2014-04-23 16:59:28 -07004186 IsCPRC = true;
Bob Wilson194f06a2011-08-03 05:58:22 +00004187 return ABIArgInfo::getExpand();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004188 }
Bob Wilson194f06a2011-08-03 05:58:22 +00004189 }
4190
Manman Ren634b3d22012-08-13 21:23:55 +00004191 // Support byval for ARM.
Manman Rencb489dd2012-11-06 19:05:29 +00004192 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4193 // most 8-byte. We realign the indirect argument if type alignment is bigger
4194 // than ABI alignment.
Manman Renfd1ba912012-11-05 22:42:46 +00004195 uint64_t ABIAlign = 4;
4196 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4197 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4198 getABIKind() == ARMABIInfo::AAPCS)
4199 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren885ad692012-11-06 04:58:01 +00004200 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004201 // Update Allocated GPRs
4202 markAllocatedGPRs(1, 1);
4203 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Rencb489dd2012-11-06 19:05:29 +00004204 /*Realign=*/TyAlign > ABIAlign);
Eli Friedman79f30982012-08-09 00:31:40 +00004205 }
4206
Daniel Dunbar8aa87c72010-09-23 01:54:28 +00004207 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2acc6e32011-07-18 04:24:23 +00004208 llvm::Type* ElemTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004209 unsigned SizeRegs;
Eli Friedman79f30982012-08-09 00:31:40 +00004210 // FIXME: Try to match the types of the arguments more accurately where
4211 // we can.
4212 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson53fc1a62011-08-01 23:39:04 +00004213 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4214 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Stephen Hines651f13c2014-04-23 16:59:28 -07004215 markAllocatedGPRs(1, SizeRegs);
Manman Ren78eb76e2012-06-25 22:04:00 +00004216 } else {
Manman Ren78eb76e2012-06-25 22:04:00 +00004217 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4218 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stephen Hines651f13c2014-04-23 16:59:28 -07004219 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastings67d097e2011-04-27 17:24:02 +00004220 }
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00004221
Chris Lattner9cbe4f02011-07-09 17:41:47 +00004222 llvm::Type *STy =
Chris Lattner7650d952011-06-18 22:49:11 +00004223 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00004224 return ABIArgInfo::getDirect(STy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004225}
4226
Chris Lattnera3c109b2010-07-29 02:16:43 +00004227static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar98303b92009-09-13 08:03:58 +00004228 llvm::LLVMContext &VMContext) {
4229 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4230 // is called integer-like if its size is less than or equal to one word, and
4231 // the offset of each of its addressable sub-fields is zero.
4232
4233 uint64_t Size = Context.getTypeSize(Ty);
4234
4235 // Check that the type fits in a word.
4236 if (Size > 32)
4237 return false;
4238
4239 // FIXME: Handle vector types!
4240 if (Ty->isVectorType())
4241 return false;
4242
Daniel Dunbarb0d58192009-09-14 02:20:34 +00004243 // Float types are never treated as "integer like".
4244 if (Ty->isRealFloatingType())
4245 return false;
4246
Daniel Dunbar98303b92009-09-13 08:03:58 +00004247 // If this is a builtin or pointer type then it is ok.
John McCall183700f2009-09-21 23:43:11 +00004248 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar98303b92009-09-13 08:03:58 +00004249 return true;
4250
Daniel Dunbar45815812010-02-01 23:31:26 +00004251 // Small complex integer types are "integer like".
4252 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4253 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar98303b92009-09-13 08:03:58 +00004254
4255 // Single element and zero sized arrays should be allowed, by the definition
4256 // above, but they are not.
4257
4258 // Otherwise, it must be a record type.
4259 const RecordType *RT = Ty->getAs<RecordType>();
4260 if (!RT) return false;
4261
4262 // Ignore records with flexible arrays.
4263 const RecordDecl *RD = RT->getDecl();
4264 if (RD->hasFlexibleArrayMember())
4265 return false;
4266
4267 // Check that all sub-fields are at offset 0, and are themselves "integer
4268 // like".
4269 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4270
4271 bool HadField = false;
4272 unsigned idx = 0;
4273 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4274 i != e; ++i, ++idx) {
David Blaikie581deb32012-06-06 20:45:41 +00004275 const FieldDecl *FD = *i;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004276
Daniel Dunbar679855a2010-01-29 03:22:29 +00004277 // Bit-fields are not addressable, we only need to verify they are "integer
4278 // like". We still have to disallow a subsequent non-bitfield, for example:
4279 // struct { int : 0; int x }
4280 // is non-integer like according to gcc.
4281 if (FD->isBitField()) {
4282 if (!RD->isUnion())
4283 HadField = true;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004284
Daniel Dunbar679855a2010-01-29 03:22:29 +00004285 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4286 return false;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004287
Daniel Dunbar679855a2010-01-29 03:22:29 +00004288 continue;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004289 }
4290
Daniel Dunbar679855a2010-01-29 03:22:29 +00004291 // Check if this field is at offset 0.
4292 if (Layout.getFieldOffset(idx) != 0)
4293 return false;
4294
Daniel Dunbar98303b92009-09-13 08:03:58 +00004295 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4296 return false;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00004297
Daniel Dunbar679855a2010-01-29 03:22:29 +00004298 // Only allow at most one field in a structure. This doesn't match the
4299 // wording above, but follows gcc in situations with a field following an
4300 // empty structure.
Daniel Dunbar98303b92009-09-13 08:03:58 +00004301 if (!RD->isUnion()) {
4302 if (HadField)
4303 return false;
4304
4305 HadField = true;
4306 }
4307 }
4308
4309 return true;
4310}
4311
Stephen Hines651f13c2014-04-23 16:59:28 -07004312ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4313 bool isVariadic) const {
Daniel Dunbar98303b92009-09-13 08:03:58 +00004314 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004315 return ABIArgInfo::getIgnore();
Daniel Dunbar98303b92009-09-13 08:03:58 +00004316
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00004317 // Large vector types should be returned via memory.
Stephen Hines651f13c2014-04-23 16:59:28 -07004318 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4319 markAllocatedGPRs(1, 1);
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00004320 return ABIArgInfo::getIndirect(0);
Stephen Hines651f13c2014-04-23 16:59:28 -07004321 }
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00004322
John McCalld608cdb2010-08-22 10:59:02 +00004323 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004324 // Treat an enum type as its underlying type.
4325 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4326 RetTy = EnumTy->getDecl()->getIntegerType();
4327
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00004328 return (RetTy->isPromotableIntegerType() ?
4329 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004330 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00004331
Rafael Espindola0eb1d972010-06-08 02:42:08 +00004332 // Structures with either a non-trivial destructor or a non-trivial
4333 // copy constructor are always indirect.
Stephen Hines651f13c2014-04-23 16:59:28 -07004334 if (isRecordReturnIndirect(RetTy, getCXXABI())) {
4335 markAllocatedGPRs(1, 1);
Rafael Espindola0eb1d972010-06-08 02:42:08 +00004336 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Stephen Hines651f13c2014-04-23 16:59:28 -07004337 }
Rafael Espindola0eb1d972010-06-08 02:42:08 +00004338
Daniel Dunbar98303b92009-09-13 08:03:58 +00004339 // Are we following APCS?
4340 if (getABIKind() == APCS) {
Chris Lattnera3c109b2010-07-29 02:16:43 +00004341 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar98303b92009-09-13 08:03:58 +00004342 return ABIArgInfo::getIgnore();
4343
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00004344 // Complex types are all returned as packed integers.
4345 //
4346 // FIXME: Consider using 2 x vector types if the back end handles them
4347 // correctly.
4348 if (RetTy->isAnyComplexType())
Chris Lattner800588f2010-07-29 06:26:06 +00004349 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +00004350 getContext().getTypeSize(RetTy)));
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00004351
Daniel Dunbar98303b92009-09-13 08:03:58 +00004352 // Integer like structures are returned in r0.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004353 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar98303b92009-09-13 08:03:58 +00004354 // Return in the smallest viable integer type.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004355 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar98303b92009-09-13 08:03:58 +00004356 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00004357 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00004358 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00004359 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4360 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00004361 }
4362
4363 // Otherwise return in memory.
Stephen Hines651f13c2014-04-23 16:59:28 -07004364 markAllocatedGPRs(1, 1);
Daniel Dunbar98303b92009-09-13 08:03:58 +00004365 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004366 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00004367
4368 // Otherwise this is an AAPCS variant.
4369
Chris Lattnera3c109b2010-07-29 02:16:43 +00004370 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar16a08082009-09-14 00:56:55 +00004371 return ABIArgInfo::getIgnore();
4372
Bob Wilson3b694fa2011-11-02 04:51:36 +00004373 // Check for homogeneous aggregates with AAPCS-VFP.
Stephen Hines651f13c2014-04-23 16:59:28 -07004374 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Bob Wilson3b694fa2011-11-02 04:51:36 +00004375 const Type *Base = 0;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004376 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
4377 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson3b694fa2011-11-02 04:51:36 +00004378 // Homogeneous Aggregates are returned directly.
4379 return ABIArgInfo::getDirect();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004380 }
Bob Wilson3b694fa2011-11-02 04:51:36 +00004381 }
4382
Daniel Dunbar98303b92009-09-13 08:03:58 +00004383 // Aggregates <= 4 bytes are returned in r0; other aggregates
4384 // are returned indirectly.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004385 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar16a08082009-09-14 00:56:55 +00004386 if (Size <= 32) {
4387 // Return in the smallest viable integer type.
4388 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00004389 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00004390 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00004391 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4392 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00004393 }
4394
Stephen Hines651f13c2014-04-23 16:59:28 -07004395 markAllocatedGPRs(1, 1);
Daniel Dunbar98303b92009-09-13 08:03:58 +00004396 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004397}
4398
Manman Ren97f81572012-10-16 19:18:39 +00004399/// isIllegalVector - check whether Ty is an illegal vector type.
4400bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4401 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4402 // Check whether VT is legal.
4403 unsigned NumElements = VT->getNumElements();
Manman Ren97f81572012-10-16 19:18:39 +00004404 // NumElements should be power of 2.
Stephen Hinesc3c9d172013-01-15 23:50:35 -08004405 if (((NumElements & (NumElements - 1)) != 0) && NumElements != 3)
Manman Ren97f81572012-10-16 19:18:39 +00004406 return true;
Manman Ren97f81572012-10-16 19:18:39 +00004407 }
4408 return false;
4409}
4410
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004411llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner77b89b82010-06-27 07:15:29 +00004412 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00004413 llvm::Type *BP = CGF.Int8PtrTy;
4414 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004415
4416 CGBuilderTy &Builder = CGF.Builder;
Chris Lattner8b418682012-02-07 00:39:47 +00004417 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004418 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rend105e732012-10-16 19:01:37 +00004419
Tim Northover373ac0a2013-06-21 23:05:33 +00004420 if (isEmptyRecord(getContext(), Ty, true)) {
4421 // These are ignored for parameter passing purposes.
4422 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4423 return Builder.CreateBitCast(Addr, PTy);
4424 }
4425
Manman Rend105e732012-10-16 19:01:37 +00004426 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindolae164c182011-08-02 22:33:37 +00004427 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Ren97f81572012-10-16 19:18:39 +00004428 bool IsIndirect = false;
Manman Rend105e732012-10-16 19:01:37 +00004429
4430 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4431 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren93371022012-10-16 19:51:48 +00004432 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4433 getABIKind() == ARMABIInfo::AAPCS)
4434 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4435 else
4436 TyAlign = 4;
Stephen Hinesc3c9d172013-01-15 23:50:35 -08004437 // Use indirect if size of the illegal vector is bigger than 32 bytes.
4438 if (isIllegalVectorType(Ty) && Size > 32) {
Manman Ren97f81572012-10-16 19:18:39 +00004439 IsIndirect = true;
4440 Size = 4;
4441 TyAlign = 4;
4442 }
Manman Rend105e732012-10-16 19:01:37 +00004443
4444 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindolae164c182011-08-02 22:33:37 +00004445 if (TyAlign > 4) {
4446 assert((TyAlign & (TyAlign - 1)) == 0 &&
4447 "Alignment is not power of 2!");
4448 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4449 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4450 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rend105e732012-10-16 19:01:37 +00004451 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindolae164c182011-08-02 22:33:37 +00004452 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004453
4454 uint64_t Offset =
Manman Rend105e732012-10-16 19:01:37 +00004455 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004456 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00004457 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004458 "ap.next");
4459 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4460
Manman Ren97f81572012-10-16 19:18:39 +00004461 if (IsIndirect)
4462 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren93371022012-10-16 19:51:48 +00004463 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rend105e732012-10-16 19:01:37 +00004464 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4465 // may not be correctly aligned for the vector type. We create an aligned
4466 // temporary space and copy the content over from ap.cur to the temporary
4467 // space. This is necessary if the natural alignment of the type is greater
4468 // than the ABI alignment.
4469 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4470 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4471 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4472 "var.align");
4473 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4474 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4475 Builder.CreateMemCpy(Dst, Src,
4476 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4477 TyAlign, false);
4478 Addr = AlignedTemp; //The content is in aligned location.
4479 }
4480 llvm::Type *PTy =
4481 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4482 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4483
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004484 return AddrTyped;
4485}
4486
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00004487namespace {
4488
Derek Schuff263366f2012-10-16 22:30:41 +00004489class NaClARMABIInfo : public ABIInfo {
4490 public:
4491 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4492 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07004493 void computeInfo(CGFunctionInfo &FI) const override;
4494 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4495 CodeGenFunction &CGF) const override;
Derek Schuff263366f2012-10-16 22:30:41 +00004496 private:
4497 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
4498 ARMABIInfo NInfo; // Used for everything else.
4499};
4500
4501class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
4502 public:
4503 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4504 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
4505};
4506
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00004507}
4508
Derek Schuff263366f2012-10-16 22:30:41 +00004509void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4510 if (FI.getASTCallingConvention() == CC_PnaclCall)
4511 PInfo.computeInfo(FI);
4512 else
4513 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
4514}
4515
4516llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4517 CodeGenFunction &CGF) const {
4518 // Always use the native convention; calling pnacl-style varargs functions
4519 // is unsupported.
4520 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
4521}
4522
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004523//===----------------------------------------------------------------------===//
Tim Northoverc264e162013-01-31 12:13:10 +00004524// AArch64 ABI Implementation
4525//===----------------------------------------------------------------------===//
4526
4527namespace {
4528
4529class AArch64ABIInfo : public ABIInfo {
4530public:
4531 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4532
4533private:
4534 // The AArch64 PCS is explicit about return types and argument types being
4535 // handled identically, so we don't need to draw a distinction between
4536 // Argument and Return classification.
4537 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
4538 int &FreeVFPRegs) const;
4539
4540 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
4541 llvm::Type *DirectTy = 0) const;
4542
Stephen Hines651f13c2014-04-23 16:59:28 -07004543 void computeInfo(CGFunctionInfo &FI) const override;
Tim Northoverc264e162013-01-31 12:13:10 +00004544
Stephen Hines651f13c2014-04-23 16:59:28 -07004545 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4546 CodeGenFunction &CGF) const override;
Tim Northoverc264e162013-01-31 12:13:10 +00004547};
4548
4549class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
4550public:
4551 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
4552 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
4553
4554 const AArch64ABIInfo &getABIInfo() const {
4555 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
4556 }
4557
Stephen Hines651f13c2014-04-23 16:59:28 -07004558 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tim Northoverc264e162013-01-31 12:13:10 +00004559 return 31;
4560 }
4561
4562 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07004563 llvm::Value *Address) const override {
Tim Northoverc264e162013-01-31 12:13:10 +00004564 // 0-31 are x0-x30 and sp: 8 bytes each
4565 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
4566 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
4567
4568 // 64-95 are v0-v31: 16 bytes each
4569 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
4570 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
4571
4572 return false;
4573 }
4574
4575};
4576
4577}
4578
4579void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4580 int FreeIntRegs = 8, FreeVFPRegs = 8;
4581
4582 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
4583 FreeIntRegs, FreeVFPRegs);
4584
4585 FreeIntRegs = FreeVFPRegs = 8;
Stephen Hines651f13c2014-04-23 16:59:28 -07004586 for (auto &I : FI.arguments()) {
4587 I.info = classifyGenericType(I.type, FreeIntRegs, FreeVFPRegs);
Tim Northoverc264e162013-01-31 12:13:10 +00004588
4589 }
4590}
4591
4592ABIArgInfo
4593AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
4594 bool IsInt, llvm::Type *DirectTy) const {
4595 if (FreeRegs >= RegsNeeded) {
4596 FreeRegs -= RegsNeeded;
4597 return ABIArgInfo::getDirect(DirectTy);
4598 }
4599
4600 llvm::Type *Padding = 0;
4601
4602 // We need padding so that later arguments don't get filled in anyway. That
4603 // wouldn't happen if only ByVal arguments followed in the same category, but
4604 // a large structure will simply seem to be a pointer as far as LLVM is
4605 // concerned.
4606 if (FreeRegs > 0) {
4607 if (IsInt)
4608 Padding = llvm::Type::getInt64Ty(getVMContext());
4609 else
4610 Padding = llvm::Type::getFloatTy(getVMContext());
4611
4612 // Either [N x i64] or [N x float].
4613 Padding = llvm::ArrayType::get(Padding, FreeRegs);
4614 FreeRegs = 0;
4615 }
4616
4617 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
4618 /*IsByVal=*/ true, /*Realign=*/ false,
4619 Padding);
4620}
4621
4622
4623ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
4624 int &FreeIntRegs,
4625 int &FreeVFPRegs) const {
4626 // Can only occurs for return, but harmless otherwise.
4627 if (Ty->isVoidType())
4628 return ABIArgInfo::getIgnore();
4629
4630 // Large vector types should be returned via memory. There's no such concept
4631 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
4632 // classified they'd go into memory (see B.3).
4633 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
4634 if (FreeIntRegs > 0)
4635 --FreeIntRegs;
4636 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4637 }
4638
4639 // All non-aggregate LLVM types have a concrete ABI representation so they can
4640 // be passed directly. After this block we're guaranteed to be in a
4641 // complicated case.
4642 if (!isAggregateTypeForABI(Ty)) {
4643 // Treat an enum type as its underlying type.
4644 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4645 Ty = EnumTy->getDecl()->getIntegerType();
4646
4647 if (Ty->isFloatingType() || Ty->isVectorType())
4648 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
4649
4650 assert(getContext().getTypeSize(Ty) <= 128 &&
4651 "unexpectedly large scalar type");
4652
4653 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
4654
4655 // If the type may need padding registers to ensure "alignment", we must be
4656 // careful when this is accounted for. Increasing the effective size covers
4657 // all cases.
4658 if (getContext().getTypeAlign(Ty) == 128)
4659 RegsNeeded += FreeIntRegs % 2 != 0;
4660
4661 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
4662 }
4663
Mark Lacey23630722013-10-06 01:33:34 +00004664 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004665 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northoverc264e162013-01-31 12:13:10 +00004666 --FreeIntRegs;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004667 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northoverc264e162013-01-31 12:13:10 +00004668 }
4669
4670 if (isEmptyRecord(getContext(), Ty, true)) {
4671 if (!getContext().getLangOpts().CPlusPlus) {
4672 // Empty structs outside C++ mode are a GNU extension, so no ABI can
4673 // possibly tell us what to do. It turns out (I believe) that GCC ignores
4674 // the object for parameter-passsing purposes.
4675 return ABIArgInfo::getIgnore();
4676 }
4677
4678 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
4679 // description of va_arg in the PCS require that an empty struct does
4680 // actually occupy space for parameter-passing. I'm hoping for a
4681 // clarification giving an explicit paragraph to point to in future.
4682 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
4683 llvm::Type::getInt8Ty(getVMContext()));
4684 }
4685
4686 // Homogeneous vector aggregates get passed in registers or on the stack.
4687 const Type *Base = 0;
4688 uint64_t NumMembers = 0;
4689 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
4690 assert(Base && "Base class should be set for homogeneous aggregate");
4691 // Homogeneous aggregates are passed and returned directly.
4692 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
4693 /*IsInt=*/ false);
4694 }
4695
4696 uint64_t Size = getContext().getTypeSize(Ty);
4697 if (Size <= 128) {
4698 // Small structs can use the same direct type whether they're in registers
4699 // or on the stack.
4700 llvm::Type *BaseTy;
4701 unsigned NumBases;
4702 int SizeInRegs = (Size + 63) / 64;
4703
4704 if (getContext().getTypeAlign(Ty) == 128) {
4705 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
4706 NumBases = 1;
4707
4708 // If the type may need padding registers to ensure "alignment", we must
4709 // be careful when this is accounted for. Increasing the effective size
4710 // covers all cases.
4711 SizeInRegs += FreeIntRegs % 2 != 0;
4712 } else {
4713 BaseTy = llvm::Type::getInt64Ty(getVMContext());
4714 NumBases = SizeInRegs;
4715 }
4716 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
4717
4718 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
4719 /*IsInt=*/ true, DirectTy);
4720 }
4721
4722 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
4723 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
4724 --FreeIntRegs;
4725 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
4726}
4727
4728llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4729 CodeGenFunction &CGF) const {
Tim Northoverc264e162013-01-31 12:13:10 +00004730 int FreeIntRegs = 8, FreeVFPRegs = 8;
4731 Ty = CGF.getContext().getCanonicalType(Ty);
4732 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
4733
Stephen Hines651f13c2014-04-23 16:59:28 -07004734 return EmitAArch64VAArg(VAListAddr, Ty, 8 - FreeIntRegs, 8 - FreeVFPRegs,
4735 AI.isIndirect(), CGF);
Tim Northoverc264e162013-01-31 12:13:10 +00004736}
4737
4738//===----------------------------------------------------------------------===//
Justin Holewinski2c585b92012-05-24 17:43:12 +00004739// NVPTX ABI Implementation
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004740//===----------------------------------------------------------------------===//
4741
4742namespace {
4743
Justin Holewinski2c585b92012-05-24 17:43:12 +00004744class NVPTXABIInfo : public ABIInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004745public:
Justin Holewinskidca8f332013-03-30 14:38:24 +00004746 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004747
4748 ABIArgInfo classifyReturnType(QualType RetTy) const;
4749 ABIArgInfo classifyArgumentType(QualType Ty) const;
4750
Stephen Hines651f13c2014-04-23 16:59:28 -07004751 void computeInfo(CGFunctionInfo &FI) const override;
4752 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4753 CodeGenFunction &CFG) const override;
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004754};
4755
Justin Holewinski2c585b92012-05-24 17:43:12 +00004756class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004757public:
Justin Holewinski2c585b92012-05-24 17:43:12 +00004758 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4759 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07004760
4761 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4762 CodeGen::CodeGenModule &M) const override;
Justin Holewinskidca8f332013-03-30 14:38:24 +00004763private:
4764 static void addKernelMetadata(llvm::Function *F);
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004765};
4766
Justin Holewinski2c585b92012-05-24 17:43:12 +00004767ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004768 if (RetTy->isVoidType())
4769 return ABIArgInfo::getIgnore();
Bill Wendling846ff9f2013-11-21 23:31:45 +00004770
4771 // note: this is different from default ABI
4772 if (!RetTy->isScalarType())
4773 return ABIArgInfo::getDirect();
4774
4775 // Treat an enum type as its underlying type.
4776 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4777 RetTy = EnumTy->getDecl()->getIntegerType();
4778
4779 return (RetTy->isPromotableIntegerType() ?
4780 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004781}
4782
Justin Holewinski2c585b92012-05-24 17:43:12 +00004783ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Bill Wendling846ff9f2013-11-21 23:31:45 +00004784 // Treat an enum type as its underlying type.
4785 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4786 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004787
Bill Wendling846ff9f2013-11-21 23:31:45 +00004788 return (Ty->isPromotableIntegerType() ?
4789 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004790}
4791
Justin Holewinski2c585b92012-05-24 17:43:12 +00004792void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004793 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07004794 for (auto &I : FI.arguments())
4795 I.info = classifyArgumentType(I.type);
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004796
4797 // Always honor user-specified calling convention.
4798 if (FI.getCallingConvention() != llvm::CallingConv::C)
4799 return;
4800
John McCallbd7370a2013-02-28 19:01:20 +00004801 FI.setEffectiveCallingConvention(getRuntimeCC());
4802}
4803
Justin Holewinski2c585b92012-05-24 17:43:12 +00004804llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4805 CodeGenFunction &CFG) const {
4806 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004807}
4808
Justin Holewinski2c585b92012-05-24 17:43:12 +00004809void NVPTXTargetCodeGenInfo::
4810SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4811 CodeGen::CodeGenModule &M) const{
Justin Holewinski818eafb2011-10-05 17:58:44 +00004812 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4813 if (!FD) return;
4814
4815 llvm::Function *F = cast<llvm::Function>(GV);
4816
4817 // Perform special handling in OpenCL mode
David Blaikie4e4d0842012-03-11 07:00:24 +00004818 if (M.getLangOpts().OpenCL) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004819 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00004820 // By default, all functions are device functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00004821 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004822 // OpenCL __kernel functions get kernel metadata
4823 addKernelMetadata(F);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004824 // And kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00004825 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004826 }
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004827 }
Justin Holewinski818eafb2011-10-05 17:58:44 +00004828
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004829 // Perform special handling in CUDA mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00004830 if (M.getLangOpts().CUDA) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004831 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004832 // __global__ functions cannot be called from the device, we do not
4833 // need to set the noinline attribute.
Stephen Hines651f13c2014-04-23 16:59:28 -07004834 if (FD->hasAttr<CUDAGlobalAttr>())
Justin Holewinskidca8f332013-03-30 14:38:24 +00004835 addKernelMetadata(F);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004836 }
4837}
4838
Justin Holewinskidca8f332013-03-30 14:38:24 +00004839void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4840 llvm::Module *M = F->getParent();
4841 llvm::LLVMContext &Ctx = M->getContext();
4842
4843 // Get "nvvm.annotations" metadata node
4844 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4845
4846 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4847 llvm::SmallVector<llvm::Value *, 3> MDVals;
4848 MDVals.push_back(F);
4849 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4850 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4851
4852 // Append metadata to nvvm.annotations
4853 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4854}
4855
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004856}
4857
4858//===----------------------------------------------------------------------===//
Ulrich Weigandb8409212013-05-06 16:26:41 +00004859// SystemZ ABI Implementation
4860//===----------------------------------------------------------------------===//
4861
4862namespace {
4863
4864class SystemZABIInfo : public ABIInfo {
4865public:
4866 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4867
4868 bool isPromotableIntegerType(QualType Ty) const;
4869 bool isCompoundType(QualType Ty) const;
4870 bool isFPArgumentType(QualType Ty) const;
4871
4872 ABIArgInfo classifyReturnType(QualType RetTy) const;
4873 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4874
Stephen Hines651f13c2014-04-23 16:59:28 -07004875 void computeInfo(CGFunctionInfo &FI) const override {
Ulrich Weigandb8409212013-05-06 16:26:41 +00004876 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07004877 for (auto &I : FI.arguments())
4878 I.info = classifyArgumentType(I.type);
Ulrich Weigandb8409212013-05-06 16:26:41 +00004879 }
4880
Stephen Hines651f13c2014-04-23 16:59:28 -07004881 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4882 CodeGenFunction &CGF) const override;
Ulrich Weigandb8409212013-05-06 16:26:41 +00004883};
4884
4885class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4886public:
4887 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4888 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4889};
4890
4891}
4892
4893bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4894 // Treat an enum type as its underlying type.
4895 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4896 Ty = EnumTy->getDecl()->getIntegerType();
4897
4898 // Promotable integer types are required to be promoted by the ABI.
4899 if (Ty->isPromotableIntegerType())
4900 return true;
4901
4902 // 32-bit values must also be promoted.
4903 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4904 switch (BT->getKind()) {
4905 case BuiltinType::Int:
4906 case BuiltinType::UInt:
4907 return true;
4908 default:
4909 return false;
4910 }
4911 return false;
4912}
4913
4914bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4915 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4916}
4917
4918bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4919 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4920 switch (BT->getKind()) {
4921 case BuiltinType::Float:
4922 case BuiltinType::Double:
4923 return true;
4924 default:
4925 return false;
4926 }
4927
4928 if (const RecordType *RT = Ty->getAsStructureType()) {
4929 const RecordDecl *RD = RT->getDecl();
4930 bool Found = false;
4931
4932 // If this is a C++ record, check the bases first.
4933 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Stephen Hines651f13c2014-04-23 16:59:28 -07004934 for (const auto &I : CXXRD->bases()) {
4935 QualType Base = I.getType();
Ulrich Weigandb8409212013-05-06 16:26:41 +00004936
4937 // Empty bases don't affect things either way.
4938 if (isEmptyRecord(getContext(), Base, true))
4939 continue;
4940
4941 if (Found)
4942 return false;
4943 Found = isFPArgumentType(Base);
4944 if (!Found)
4945 return false;
4946 }
4947
4948 // Check the fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07004949 for (const auto *FD : RD->fields()) {
Ulrich Weigandb8409212013-05-06 16:26:41 +00004950 // Empty bitfields don't affect things either way.
4951 // Unlike isSingleElementStruct(), empty structure and array fields
4952 // do count. So do anonymous bitfields that aren't zero-sized.
4953 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4954 return true;
4955
4956 // Unlike isSingleElementStruct(), arrays do not count.
4957 // Nested isFPArgumentType structures still do though.
4958 if (Found)
4959 return false;
4960 Found = isFPArgumentType(FD->getType());
4961 if (!Found)
4962 return false;
4963 }
4964
4965 // Unlike isSingleElementStruct(), trailing padding is allowed.
4966 // An 8-byte aligned struct s { float f; } is passed as a double.
4967 return Found;
4968 }
4969
4970 return false;
4971}
4972
4973llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4974 CodeGenFunction &CGF) const {
4975 // Assume that va_list type is correct; should be pointer to LLVM type:
4976 // struct {
4977 // i64 __gpr;
4978 // i64 __fpr;
4979 // i8 *__overflow_arg_area;
4980 // i8 *__reg_save_area;
4981 // };
4982
4983 // Every argument occupies 8 bytes and is passed by preference in either
4984 // GPRs or FPRs.
4985 Ty = CGF.getContext().getCanonicalType(Ty);
4986 ABIArgInfo AI = classifyArgumentType(Ty);
4987 bool InFPRs = isFPArgumentType(Ty);
4988
4989 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4990 bool IsIndirect = AI.isIndirect();
4991 unsigned UnpaddedBitSize;
4992 if (IsIndirect) {
4993 APTy = llvm::PointerType::getUnqual(APTy);
4994 UnpaddedBitSize = 64;
4995 } else
4996 UnpaddedBitSize = getContext().getTypeSize(Ty);
4997 unsigned PaddedBitSize = 64;
4998 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4999
5000 unsigned PaddedSize = PaddedBitSize / 8;
5001 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5002
5003 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5004 if (InFPRs) {
5005 MaxRegs = 4; // Maximum of 4 FPR arguments
5006 RegCountField = 1; // __fpr
5007 RegSaveIndex = 16; // save offset for f0
5008 RegPadding = 0; // floats are passed in the high bits of an FPR
5009 } else {
5010 MaxRegs = 5; // Maximum of 5 GPR arguments
5011 RegCountField = 0; // __gpr
5012 RegSaveIndex = 2; // save offset for r2
5013 RegPadding = Padding; // values are passed in the low bits of a GPR
5014 }
5015
5016 llvm::Value *RegCountPtr =
5017 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5018 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5019 llvm::Type *IndexTy = RegCount->getType();
5020 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5021 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Stephen Hines651f13c2014-04-23 16:59:28 -07005022 "fits_in_regs");
Ulrich Weigandb8409212013-05-06 16:26:41 +00005023
5024 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5025 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5026 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5027 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5028
5029 // Emit code to load the value if it was passed in registers.
5030 CGF.EmitBlock(InRegBlock);
5031
5032 // Work out the address of an argument register.
5033 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5034 llvm::Value *ScaledRegCount =
5035 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5036 llvm::Value *RegBase =
5037 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5038 llvm::Value *RegOffset =
5039 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5040 llvm::Value *RegSaveAreaPtr =
5041 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5042 llvm::Value *RegSaveArea =
5043 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5044 llvm::Value *RawRegAddr =
5045 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5046 llvm::Value *RegAddr =
5047 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5048
5049 // Update the register count
5050 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5051 llvm::Value *NewRegCount =
5052 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5053 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5054 CGF.EmitBranch(ContBlock);
5055
5056 // Emit code to load the value if it was passed in memory.
5057 CGF.EmitBlock(InMemBlock);
5058
5059 // Work out the address of a stack argument.
5060 llvm::Value *OverflowArgAreaPtr =
5061 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5062 llvm::Value *OverflowArgArea =
5063 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5064 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5065 llvm::Value *RawMemAddr =
5066 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5067 llvm::Value *MemAddr =
5068 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5069
5070 // Update overflow_arg_area_ptr pointer
5071 llvm::Value *NewOverflowArgArea =
5072 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5073 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5074 CGF.EmitBranch(ContBlock);
5075
5076 // Return the appropriate result.
5077 CGF.EmitBlock(ContBlock);
5078 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5079 ResAddr->addIncoming(RegAddr, InRegBlock);
5080 ResAddr->addIncoming(MemAddr, InMemBlock);
5081
5082 if (IsIndirect)
5083 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5084
5085 return ResAddr;
5086}
5087
John McCallb8b52972013-06-18 02:46:29 +00005088bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
5089 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
5090 assert(Triple.getArch() == llvm::Triple::x86);
5091
5092 switch (Opts.getStructReturnConvention()) {
5093 case CodeGenOptions::SRCK_Default:
5094 break;
5095 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
5096 return false;
5097 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
5098 return true;
5099 }
5100
5101 if (Triple.isOSDarwin())
5102 return true;
5103
5104 switch (Triple.getOS()) {
John McCallb8b52972013-06-18 02:46:29 +00005105 case llvm::Triple::AuroraUX:
5106 case llvm::Triple::DragonFly:
5107 case llvm::Triple::FreeBSD:
5108 case llvm::Triple::OpenBSD:
5109 case llvm::Triple::Bitrig:
John McCallb8b52972013-06-18 02:46:29 +00005110 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07005111 case llvm::Triple::Win32:
5112 switch (Triple.getEnvironment()) {
5113 case llvm::Triple::UnknownEnvironment:
5114 case llvm::Triple::Cygnus:
5115 case llvm::Triple::GNU:
5116 case llvm::Triple::MSVC:
5117 return true;
5118 default:
5119 return false;
5120 }
John McCallb8b52972013-06-18 02:46:29 +00005121 default:
5122 return false;
5123 }
5124}
Ulrich Weigandb8409212013-05-06 16:26:41 +00005125
5126ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5127 if (RetTy->isVoidType())
5128 return ABIArgInfo::getIgnore();
5129 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5130 return ABIArgInfo::getIndirect(0);
5131 return (isPromotableIntegerType(RetTy) ?
5132 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5133}
5134
5135ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5136 // Handle the generic C++ ABI.
Mark Lacey23630722013-10-06 01:33:34 +00005137 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigandb8409212013-05-06 16:26:41 +00005138 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5139
5140 // Integers and enums are extended to full register width.
5141 if (isPromotableIntegerType(Ty))
5142 return ABIArgInfo::getExtend();
5143
5144 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5145 uint64_t Size = getContext().getTypeSize(Ty);
5146 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandiford148a3522013-12-04 10:02:36 +00005147 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005148
5149 // Handle small structures.
5150 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5151 // Structures with flexible arrays have variable length, so really
5152 // fail the size test above.
5153 const RecordDecl *RD = RT->getDecl();
5154 if (RD->hasFlexibleArrayMember())
Richard Sandiford148a3522013-12-04 10:02:36 +00005155 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005156
5157 // The structure is passed as an unextended integer, a float, or a double.
5158 llvm::Type *PassTy;
5159 if (isFPArgumentType(Ty)) {
5160 assert(Size == 32 || Size == 64);
5161 if (Size == 32)
5162 PassTy = llvm::Type::getFloatTy(getVMContext());
5163 else
5164 PassTy = llvm::Type::getDoubleTy(getVMContext());
5165 } else
5166 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5167 return ABIArgInfo::getDirect(PassTy);
5168 }
5169
5170 // Non-structure compounds are passed indirectly.
5171 if (isCompoundType(Ty))
Richard Sandiford148a3522013-12-04 10:02:36 +00005172 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005173
5174 return ABIArgInfo::getDirect(0);
5175}
5176
5177//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005178// MSP430 ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00005179//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005180
5181namespace {
5182
5183class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5184public:
Chris Lattnerea044322010-07-29 02:01:43 +00005185 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5186 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005187 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -07005188 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005189};
5190
5191}
5192
5193void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5194 llvm::GlobalValue *GV,
5195 CodeGen::CodeGenModule &M) const {
5196 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5197 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5198 // Handle 'interrupt' attribute:
5199 llvm::Function *F = cast<llvm::Function>(GV);
5200
5201 // Step 1: Set ISR calling convention.
5202 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5203
5204 // Step 2: Add attributes goodness.
Bill Wendling72390b32012-12-20 19:27:06 +00005205 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005206
5207 // Step 3: Emit ISR vector alias.
Anton Korobeynikovf419a852012-11-26 18:59:10 +00005208 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005209 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovf419a852012-11-26 18:59:10 +00005210 "__isr_" + Twine(Num),
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005211 GV, &M.getModule());
5212 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005213 }
5214}
5215
Chris Lattnerdce5ad02010-06-28 20:05:43 +00005216//===----------------------------------------------------------------------===//
John McCallaeeb7012010-05-27 06:19:26 +00005217// MIPS ABI Implementation. This works for both little-endian and
5218// big-endian variants.
Chris Lattnerdce5ad02010-06-28 20:05:43 +00005219//===----------------------------------------------------------------------===//
5220
John McCallaeeb7012010-05-27 06:19:26 +00005221namespace {
Akira Hatanaka619e8872011-06-02 00:09:17 +00005222class MipsABIInfo : public ABIInfo {
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005223 bool IsO32;
Akira Hatanakac359f202012-07-03 19:24:06 +00005224 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5225 void CoerceToIntArgs(uint64_t TySize,
Craig Topper6b9240e2013-07-05 19:34:19 +00005226 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005227 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005228 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005229 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005230public:
Akira Hatanakab551dd32011-11-03 00:05:50 +00005231 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakac359f202012-07-03 19:24:06 +00005232 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
5233 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanaka619e8872011-06-02 00:09:17 +00005234
5235 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005236 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Stephen Hines651f13c2014-04-23 16:59:28 -07005237 void computeInfo(CGFunctionInfo &FI) const override;
5238 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5239 CodeGenFunction &CGF) const override;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005240};
5241
John McCallaeeb7012010-05-27 06:19:26 +00005242class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanakae624fa02011-09-20 18:23:28 +00005243 unsigned SizeOfUnwindException;
John McCallaeeb7012010-05-27 06:19:26 +00005244public:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005245 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5246 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
5247 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCallaeeb7012010-05-27 06:19:26 +00005248
Stephen Hines651f13c2014-04-23 16:59:28 -07005249 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallaeeb7012010-05-27 06:19:26 +00005250 return 29;
5251 }
5252
Reed Kotler7dfd1822013-01-16 17:10:28 +00005253 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -07005254 CodeGen::CodeGenModule &CGM) const override {
Reed Kotlerad4b8b42013-03-13 20:40:30 +00005255 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5256 if (!FD) return;
Rafael Espindolad8e6d6d2013-03-19 14:32:23 +00005257 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotlerad4b8b42013-03-13 20:40:30 +00005258 if (FD->hasAttr<Mips16Attr>()) {
5259 Fn->addFnAttr("mips16");
5260 }
5261 else if (FD->hasAttr<NoMips16Attr>()) {
5262 Fn->addFnAttr("nomips16");
5263 }
Reed Kotler7dfd1822013-01-16 17:10:28 +00005264 }
Reed Kotlerad4b8b42013-03-13 20:40:30 +00005265
John McCallaeeb7012010-05-27 06:19:26 +00005266 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07005267 llvm::Value *Address) const override;
John McCall49e34be2011-08-30 01:42:09 +00005268
Stephen Hines651f13c2014-04-23 16:59:28 -07005269 unsigned getSizeOfUnwindException() const override {
Akira Hatanakae624fa02011-09-20 18:23:28 +00005270 return SizeOfUnwindException;
John McCall49e34be2011-08-30 01:42:09 +00005271 }
John McCallaeeb7012010-05-27 06:19:26 +00005272};
5273}
5274
Akira Hatanakac359f202012-07-03 19:24:06 +00005275void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper6b9240e2013-07-05 19:34:19 +00005276 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00005277 llvm::IntegerType *IntTy =
5278 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005279
5280 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5281 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5282 ArgList.push_back(IntTy);
5283
5284 // If necessary, add one more integer type to ArgList.
5285 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5286
5287 if (R)
5288 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005289}
5290
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005291// In N32/64, an aligned double precision floating point field is passed in
5292// a register.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005293llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00005294 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5295
5296 if (IsO32) {
5297 CoerceToIntArgs(TySize, ArgList);
5298 return llvm::StructType::get(getVMContext(), ArgList);
5299 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005300
Akira Hatanaka2afd23d2012-01-12 00:52:17 +00005301 if (Ty->isComplexType())
5302 return CGT.ConvertType(Ty);
Akira Hatanaka6d1080f2012-01-10 23:12:19 +00005303
Akira Hatanakaa34e9212012-02-09 19:54:16 +00005304 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005305
Akira Hatanakac359f202012-07-03 19:24:06 +00005306 // Unions/vectors are passed in integer registers.
5307 if (!RT || !RT->isStructureOrClassType()) {
5308 CoerceToIntArgs(TySize, ArgList);
5309 return llvm::StructType::get(getVMContext(), ArgList);
5310 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005311
5312 const RecordDecl *RD = RT->getDecl();
5313 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005314 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005315
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005316 uint64_t LastOffset = 0;
5317 unsigned idx = 0;
5318 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5319
Akira Hatanakaa34e9212012-02-09 19:54:16 +00005320 // Iterate over fields in the struct/class and check if there are any aligned
5321 // double fields.
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005322 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5323 i != e; ++i, ++idx) {
David Blaikie262bc182012-04-30 02:36:29 +00005324 const QualType Ty = i->getType();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005325 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5326
5327 if (!BT || BT->getKind() != BuiltinType::Double)
5328 continue;
5329
5330 uint64_t Offset = Layout.getFieldOffset(idx);
5331 if (Offset % 64) // Ignore doubles that are not aligned.
5332 continue;
5333
5334 // Add ((Offset - LastOffset) / 64) args of type i64.
5335 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5336 ArgList.push_back(I64);
5337
5338 // Add double type.
5339 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5340 LastOffset = Offset + 64;
5341 }
5342
Akira Hatanakac359f202012-07-03 19:24:06 +00005343 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5344 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005345
5346 return llvm::StructType::get(getVMContext(), ArgList);
5347}
5348
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005349llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5350 uint64_t Offset) const {
5351 if (OrigOffset + MinABIStackAlignInBytes > Offset)
5352 return 0;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005353
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005354 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005355}
Akira Hatanaka9659d592012-01-10 22:44:52 +00005356
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005357ABIArgInfo
5358MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005359 uint64_t OrigOffset = Offset;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005360 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005361 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005362
Akira Hatanakac359f202012-07-03 19:24:06 +00005363 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5364 (uint64_t)StackAlignInBytes);
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005365 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5366 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005367
Akira Hatanakac359f202012-07-03 19:24:06 +00005368 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanaka619e8872011-06-02 00:09:17 +00005369 // Ignore empty aggregates.
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005370 if (TySize == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00005371 return ABIArgInfo::getIgnore();
5372
Mark Lacey23630722013-10-06 01:33:34 +00005373 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005374 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005375 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005376 }
Akira Hatanaka511949b2011-08-01 18:09:58 +00005377
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005378 // If we have reached here, aggregates are passed directly by coercing to
5379 // another structure type. Padding is inserted if the offset of the
5380 // aggregate is unaligned.
5381 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005382 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00005383 }
5384
5385 // Treat an enum type as its underlying type.
5386 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5387 Ty = EnumTy->getDecl()->getIntegerType();
5388
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005389 if (Ty->isPromotableIntegerType())
5390 return ABIArgInfo::getExtend();
5391
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005392 return ABIArgInfo::getDirect(
5393 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00005394}
5395
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005396llvm::Type*
5397MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakada54ff32012-02-09 18:49:26 +00005398 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakac359f202012-07-03 19:24:06 +00005399 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005400
Akira Hatanakada54ff32012-02-09 18:49:26 +00005401 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005402 const RecordDecl *RD = RT->getDecl();
Akira Hatanakada54ff32012-02-09 18:49:26 +00005403 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5404 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005405
Akira Hatanakada54ff32012-02-09 18:49:26 +00005406 // N32/64 returns struct/classes in floating point registers if the
5407 // following conditions are met:
5408 // 1. The size of the struct/class is no larger than 128-bit.
5409 // 2. The struct/class has one or two fields all of which are floating
5410 // point types.
5411 // 3. The offset of the first field is zero (this follows what gcc does).
5412 //
5413 // Any other composite results are returned in integer registers.
5414 //
5415 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5416 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5417 for (; b != e; ++b) {
David Blaikie262bc182012-04-30 02:36:29 +00005418 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005419
Akira Hatanakada54ff32012-02-09 18:49:26 +00005420 if (!BT || !BT->isFloatingPoint())
5421 break;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005422
David Blaikie262bc182012-04-30 02:36:29 +00005423 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakada54ff32012-02-09 18:49:26 +00005424 }
5425
5426 if (b == e)
5427 return llvm::StructType::get(getVMContext(), RTList,
5428 RD->hasAttr<PackedAttr>());
5429
5430 RTList.clear();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005431 }
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005432 }
5433
Akira Hatanakac359f202012-07-03 19:24:06 +00005434 CoerceToIntArgs(Size, RTList);
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005435 return llvm::StructType::get(getVMContext(), RTList);
5436}
5437
Akira Hatanaka619e8872011-06-02 00:09:17 +00005438ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanakaa8536c02012-01-23 23:18:57 +00005439 uint64_t Size = getContext().getTypeSize(RetTy);
5440
5441 if (RetTy->isVoidType() || Size == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00005442 return ABIArgInfo::getIgnore();
5443
Akira Hatanaka8aeb1472012-05-11 21:01:17 +00005444 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey23630722013-10-06 01:33:34 +00005445 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005446 return ABIArgInfo::getIndirect(0);
5447
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005448 if (Size <= 128) {
5449 if (RetTy->isAnyComplexType())
5450 return ABIArgInfo::getDirect();
5451
Akira Hatanakac359f202012-07-03 19:24:06 +00005452 // O32 returns integer vectors in registers.
5453 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
5454 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5455
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005456 if (!IsO32)
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005457 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5458 }
Akira Hatanaka619e8872011-06-02 00:09:17 +00005459
5460 return ABIArgInfo::getIndirect(0);
5461 }
5462
5463 // Treat an enum type as its underlying type.
5464 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5465 RetTy = EnumTy->getDecl()->getIntegerType();
5466
5467 return (RetTy->isPromotableIntegerType() ?
5468 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5469}
5470
5471void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakacc662542012-01-12 01:10:09 +00005472 ABIArgInfo &RetInfo = FI.getReturnInfo();
5473 RetInfo = classifyReturnType(FI.getReturnType());
5474
5475 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005476 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanakacc662542012-01-12 01:10:09 +00005477
Stephen Hines651f13c2014-04-23 16:59:28 -07005478 for (auto &I : FI.arguments())
5479 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanaka619e8872011-06-02 00:09:17 +00005480}
5481
5482llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5483 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00005484 llvm::Type *BP = CGF.Int8PtrTy;
5485 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005486
5487 CGBuilderTy &Builder = CGF.Builder;
5488 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5489 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005490 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005491 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5492 llvm::Value *AddrTyped;
John McCall64aa4b32013-04-16 22:48:15 +00005493 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005494 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005495
5496 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005497 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5498 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5499 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5500 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005501 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5502 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5503 }
5504 else
5505 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5506
5507 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005508 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005509 uint64_t Offset =
5510 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5511 llvm::Value *NextAddr =
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005512 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005513 "ap.next");
5514 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5515
5516 return AddrTyped;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005517}
5518
John McCallaeeb7012010-05-27 06:19:26 +00005519bool
5520MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5521 llvm::Value *Address) const {
5522 // This information comes from gcc's implementation, which seems to
5523 // as canonical as it gets.
5524
John McCallaeeb7012010-05-27 06:19:26 +00005525 // Everything on MIPS is 4 bytes. Double-precision FP registers
5526 // are aliased to pairs of single-precision FP registers.
Chris Lattner8b418682012-02-07 00:39:47 +00005527 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCallaeeb7012010-05-27 06:19:26 +00005528
5529 // 0-31 are the general purpose registers, $0 - $31.
5530 // 32-63 are the floating-point registers, $f0 - $f31.
5531 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5532 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattner8b418682012-02-07 00:39:47 +00005533 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCallaeeb7012010-05-27 06:19:26 +00005534
5535 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5536 // They are one bit wide and ignored here.
5537
5538 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5539 // (coprocessor 1 is the FP unit)
5540 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5541 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5542 // 176-181 are the DSP accumulator registers.
Chris Lattner8b418682012-02-07 00:39:47 +00005543 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCallaeeb7012010-05-27 06:19:26 +00005544 return false;
5545}
5546
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005547//===----------------------------------------------------------------------===//
5548// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5549// Currently subclassed only to implement custom OpenCL C function attribute
5550// handling.
5551//===----------------------------------------------------------------------===//
5552
5553namespace {
5554
5555class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5556public:
5557 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5558 : DefaultTargetCodeGenInfo(CGT) {}
5559
Stephen Hines651f13c2014-04-23 16:59:28 -07005560 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5561 CodeGen::CodeGenModule &M) const override;
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005562};
5563
5564void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5565 llvm::GlobalValue *GV,
5566 CodeGen::CodeGenModule &M) const {
5567 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5568 if (!FD) return;
5569
5570 llvm::Function *F = cast<llvm::Function>(GV);
5571
David Blaikie4e4d0842012-03-11 07:00:24 +00005572 if (M.getLangOpts().OpenCL) {
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005573 if (FD->hasAttr<OpenCLKernelAttr>()) {
5574 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00005575 F->addFnAttr(llvm::Attribute::NoInline);
Stephen Hines651f13c2014-04-23 16:59:28 -07005576 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5577 if (Attr) {
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005578 // Convert the reqd_work_group_size() attributes to metadata.
5579 llvm::LLVMContext &Context = F->getContext();
5580 llvm::NamedMDNode *OpenCLMetadata =
5581 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5582
5583 SmallVector<llvm::Value*, 5> Operands;
5584 Operands.push_back(F);
5585
Chris Lattner8b418682012-02-07 00:39:47 +00005586 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07005587 llvm::APInt(32, Attr->getXDim())));
Chris Lattner8b418682012-02-07 00:39:47 +00005588 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07005589 llvm::APInt(32, Attr->getYDim())));
Chris Lattner8b418682012-02-07 00:39:47 +00005590 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07005591 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005592
5593 // Add a boolean constant operand for "required" (true) or "hint" (false)
5594 // for implementing the work_group_size_hint attr later. Currently
5595 // always true as the hint is not yet implemented.
Chris Lattner8b418682012-02-07 00:39:47 +00005596 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005597 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5598 }
5599 }
5600 }
5601}
5602
5603}
John McCallaeeb7012010-05-27 06:19:26 +00005604
Tony Linthicum96319392011-12-12 21:14:55 +00005605//===----------------------------------------------------------------------===//
5606// Hexagon ABI Implementation
5607//===----------------------------------------------------------------------===//
5608
5609namespace {
5610
5611class HexagonABIInfo : public ABIInfo {
5612
5613
5614public:
5615 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5616
5617private:
5618
5619 ABIArgInfo classifyReturnType(QualType RetTy) const;
5620 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5621
Stephen Hines651f13c2014-04-23 16:59:28 -07005622 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum96319392011-12-12 21:14:55 +00005623
Stephen Hines651f13c2014-04-23 16:59:28 -07005624 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5625 CodeGenFunction &CGF) const override;
Tony Linthicum96319392011-12-12 21:14:55 +00005626};
5627
5628class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5629public:
5630 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5631 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5632
Stephen Hines651f13c2014-04-23 16:59:28 -07005633 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum96319392011-12-12 21:14:55 +00005634 return 29;
5635 }
5636};
5637
5638}
5639
5640void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5641 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07005642 for (auto &I : FI.arguments())
5643 I.info = classifyArgumentType(I.type);
Tony Linthicum96319392011-12-12 21:14:55 +00005644}
5645
5646ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5647 if (!isAggregateTypeForABI(Ty)) {
5648 // Treat an enum type as its underlying type.
5649 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5650 Ty = EnumTy->getDecl()->getIntegerType();
5651
5652 return (Ty->isPromotableIntegerType() ?
5653 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5654 }
5655
5656 // Ignore empty records.
5657 if (isEmptyRecord(getContext(), Ty, true))
5658 return ABIArgInfo::getIgnore();
5659
Mark Lacey23630722013-10-06 01:33:34 +00005660 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005661 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum96319392011-12-12 21:14:55 +00005662
5663 uint64_t Size = getContext().getTypeSize(Ty);
5664 if (Size > 64)
5665 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5666 // Pass in the smallest viable integer type.
5667 else if (Size > 32)
5668 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5669 else if (Size > 16)
5670 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5671 else if (Size > 8)
5672 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5673 else
5674 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5675}
5676
5677ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5678 if (RetTy->isVoidType())
5679 return ABIArgInfo::getIgnore();
5680
5681 // Large vector types should be returned via memory.
5682 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5683 return ABIArgInfo::getIndirect(0);
5684
5685 if (!isAggregateTypeForABI(RetTy)) {
5686 // Treat an enum type as its underlying type.
5687 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5688 RetTy = EnumTy->getDecl()->getIntegerType();
5689
5690 return (RetTy->isPromotableIntegerType() ?
5691 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5692 }
5693
5694 // Structures with either a non-trivial destructor or a non-trivial
5695 // copy constructor are always indirect.
Mark Lacey23630722013-10-06 01:33:34 +00005696 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum96319392011-12-12 21:14:55 +00005697 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5698
5699 if (isEmptyRecord(getContext(), RetTy, true))
5700 return ABIArgInfo::getIgnore();
5701
5702 // Aggregates <= 8 bytes are returned in r0; other aggregates
5703 // are returned indirectly.
5704 uint64_t Size = getContext().getTypeSize(RetTy);
5705 if (Size <= 64) {
5706 // Return in the smallest viable integer type.
5707 if (Size <= 8)
5708 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5709 if (Size <= 16)
5710 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5711 if (Size <= 32)
5712 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5713 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5714 }
5715
5716 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5717}
5718
5719llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner8b418682012-02-07 00:39:47 +00005720 CodeGenFunction &CGF) const {
Tony Linthicum96319392011-12-12 21:14:55 +00005721 // FIXME: Need to handle alignment
Chris Lattner8b418682012-02-07 00:39:47 +00005722 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum96319392011-12-12 21:14:55 +00005723
5724 CGBuilderTy &Builder = CGF.Builder;
5725 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5726 "ap");
5727 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5728 llvm::Type *PTy =
5729 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5730 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5731
5732 uint64_t Offset =
5733 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5734 llvm::Value *NextAddr =
5735 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5736 "ap.next");
5737 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5738
5739 return AddrTyped;
5740}
5741
5742
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005743//===----------------------------------------------------------------------===//
5744// SPARC v9 ABI Implementation.
5745// Based on the SPARC Compliance Definition version 2.4.1.
5746//
5747// Function arguments a mapped to a nominal "parameter array" and promoted to
5748// registers depending on their type. Each argument occupies 8 or 16 bytes in
5749// the array, structs larger than 16 bytes are passed indirectly.
5750//
5751// One case requires special care:
5752//
5753// struct mixed {
5754// int i;
5755// float f;
5756// };
5757//
5758// When a struct mixed is passed by value, it only occupies 8 bytes in the
5759// parameter array, but the int is passed in an integer register, and the float
5760// is passed in a floating point register. This is represented as two arguments
5761// with the LLVM IR inreg attribute:
5762//
5763// declare void f(i32 inreg %i, float inreg %f)
5764//
5765// The code generator will only allocate 4 bytes from the parameter array for
5766// the inreg arguments. All other arguments are allocated a multiple of 8
5767// bytes.
5768//
5769namespace {
5770class SparcV9ABIInfo : public ABIInfo {
5771public:
5772 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5773
5774private:
5775 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Stephen Hines651f13c2014-04-23 16:59:28 -07005776 void computeInfo(CGFunctionInfo &FI) const override;
5777 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5778 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00005779
5780 // Coercion type builder for structs passed in registers. The coercion type
5781 // serves two purposes:
5782 //
5783 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5784 // in registers.
5785 // 2. Expose aligned floating point elements as first-level elements, so the
5786 // code generator knows to pass them in floating point registers.
5787 //
5788 // We also compute the InReg flag which indicates that the struct contains
5789 // aligned 32-bit floats.
5790 //
5791 struct CoerceBuilder {
5792 llvm::LLVMContext &Context;
5793 const llvm::DataLayout &DL;
5794 SmallVector<llvm::Type*, 8> Elems;
5795 uint64_t Size;
5796 bool InReg;
5797
5798 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5799 : Context(c), DL(dl), Size(0), InReg(false) {}
5800
5801 // Pad Elems with integers until Size is ToSize.
5802 void pad(uint64_t ToSize) {
5803 assert(ToSize >= Size && "Cannot remove elements");
5804 if (ToSize == Size)
5805 return;
5806
5807 // Finish the current 64-bit word.
5808 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5809 if (Aligned > Size && Aligned <= ToSize) {
5810 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5811 Size = Aligned;
5812 }
5813
5814 // Add whole 64-bit words.
5815 while (Size + 64 <= ToSize) {
5816 Elems.push_back(llvm::Type::getInt64Ty(Context));
5817 Size += 64;
5818 }
5819
5820 // Final in-word padding.
5821 if (Size < ToSize) {
5822 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5823 Size = ToSize;
5824 }
5825 }
5826
5827 // Add a floating point element at Offset.
5828 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5829 // Unaligned floats are treated as integers.
5830 if (Offset % Bits)
5831 return;
5832 // The InReg flag is only required if there are any floats < 64 bits.
5833 if (Bits < 64)
5834 InReg = true;
5835 pad(Offset);
5836 Elems.push_back(Ty);
5837 Size = Offset + Bits;
5838 }
5839
5840 // Add a struct type to the coercion type, starting at Offset (in bits).
5841 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5842 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5843 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5844 llvm::Type *ElemTy = StrTy->getElementType(i);
5845 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5846 switch (ElemTy->getTypeID()) {
5847 case llvm::Type::StructTyID:
5848 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5849 break;
5850 case llvm::Type::FloatTyID:
5851 addFloat(ElemOffset, ElemTy, 32);
5852 break;
5853 case llvm::Type::DoubleTyID:
5854 addFloat(ElemOffset, ElemTy, 64);
5855 break;
5856 case llvm::Type::FP128TyID:
5857 addFloat(ElemOffset, ElemTy, 128);
5858 break;
5859 case llvm::Type::PointerTyID:
5860 if (ElemOffset % 64 == 0) {
5861 pad(ElemOffset);
5862 Elems.push_back(ElemTy);
5863 Size += 64;
5864 }
5865 break;
5866 default:
5867 break;
5868 }
5869 }
5870 }
5871
5872 // Check if Ty is a usable substitute for the coercion type.
5873 bool isUsableType(llvm::StructType *Ty) const {
5874 if (Ty->getNumElements() != Elems.size())
5875 return false;
5876 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5877 if (Elems[i] != Ty->getElementType(i))
5878 return false;
5879 return true;
5880 }
5881
5882 // Get the coercion type as a literal struct type.
5883 llvm::Type *getType() const {
5884 if (Elems.size() == 1)
5885 return Elems.front();
5886 else
5887 return llvm::StructType::get(Context, Elems);
5888 }
5889 };
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005890};
5891} // end anonymous namespace
5892
5893ABIArgInfo
5894SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5895 if (Ty->isVoidType())
5896 return ABIArgInfo::getIgnore();
5897
5898 uint64_t Size = getContext().getTypeSize(Ty);
5899
5900 // Anything too big to fit in registers is passed with an explicit indirect
5901 // pointer / sret pointer.
5902 if (Size > SizeLimit)
5903 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5904
5905 // Treat an enum type as its underlying type.
5906 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5907 Ty = EnumTy->getDecl()->getIntegerType();
5908
5909 // Integer types smaller than a register are extended.
5910 if (Size < 64 && Ty->isIntegerType())
5911 return ABIArgInfo::getExtend();
5912
5913 // Other non-aggregates go in registers.
5914 if (!isAggregateTypeForABI(Ty))
5915 return ABIArgInfo::getDirect();
5916
Stephen Hines651f13c2014-04-23 16:59:28 -07005917 // If a C++ object has either a non-trivial copy constructor or a non-trivial
5918 // destructor, it is passed with an explicit indirect pointer / sret pointer.
5919 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5920 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5921
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005922 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00005923 // Build a coercion type from the LLVM struct type.
5924 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5925 if (!StrTy)
5926 return ABIArgInfo::getDirect();
5927
5928 CoerceBuilder CB(getVMContext(), getDataLayout());
5929 CB.addStruct(0, StrTy);
5930 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5931
5932 // Try to use the original type for coercion.
5933 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5934
5935 if (CB.InReg)
5936 return ABIArgInfo::getDirectInReg(CoerceTy);
5937 else
5938 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005939}
5940
5941llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5942 CodeGenFunction &CGF) const {
Jakob Stoklund Olesena4b56d32013-06-05 03:00:18 +00005943 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5944 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5945 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5946 AI.setCoerceToType(ArgTy);
5947
5948 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5949 CGBuilderTy &Builder = CGF.Builder;
5950 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5951 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5952 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5953 llvm::Value *ArgAddr;
5954 unsigned Stride;
5955
5956 switch (AI.getKind()) {
5957 case ABIArgInfo::Expand:
Stephen Hines651f13c2014-04-23 16:59:28 -07005958 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesena4b56d32013-06-05 03:00:18 +00005959 llvm_unreachable("Unsupported ABI kind for va_arg");
5960
5961 case ABIArgInfo::Extend:
5962 Stride = 8;
5963 ArgAddr = Builder
5964 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5965 "extend");
5966 break;
5967
5968 case ABIArgInfo::Direct:
5969 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5970 ArgAddr = Addr;
5971 break;
5972
5973 case ABIArgInfo::Indirect:
5974 Stride = 8;
5975 ArgAddr = Builder.CreateBitCast(Addr,
5976 llvm::PointerType::getUnqual(ArgPtrTy),
5977 "indirect");
5978 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5979 break;
5980
5981 case ABIArgInfo::Ignore:
5982 return llvm::UndefValue::get(ArgPtrTy);
5983 }
5984
5985 // Update VAList.
5986 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5987 Builder.CreateStore(Addr, VAListAddrAsBPP);
5988
5989 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005990}
5991
5992void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5993 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Stephen Hines651f13c2014-04-23 16:59:28 -07005994 for (auto &I : FI.arguments())
5995 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005996}
5997
5998namespace {
5999class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6000public:
6001 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6002 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07006003
6004 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6005 return 14;
6006 }
6007
6008 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6009 llvm::Value *Address) const override;
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006010};
6011} // end anonymous namespace
6012
Stephen Hines651f13c2014-04-23 16:59:28 -07006013bool
6014SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6015 llvm::Value *Address) const {
6016 // This is calculated from the LLVM and GCC tables and verified
6017 // against gcc output. AFAIK all ABIs use the same encoding.
6018
6019 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6020
6021 llvm::IntegerType *i8 = CGF.Int8Ty;
6022 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6023 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6024
6025 // 0-31: the 8-byte general-purpose registers
6026 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6027
6028 // 32-63: f0-31, the 4-byte floating-point registers
6029 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6030
6031 // Y = 64
6032 // PSR = 65
6033 // WIM = 66
6034 // TBR = 67
6035 // PC = 68
6036 // NPC = 69
6037 // FSR = 70
6038 // CSR = 71
6039 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6040
6041 // 72-87: d0-15, the 8-byte floating-point registers
6042 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6043
6044 return false;
6045}
6046
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006047
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006048//===----------------------------------------------------------------------===//
Stephen Hines651f13c2014-04-23 16:59:28 -07006049// XCore ABI Implementation
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006050//===----------------------------------------------------------------------===//
6051namespace {
Robert Lytton276c2892013-08-19 09:46:39 +00006052class XCoreABIInfo : public DefaultABIInfo {
6053public:
6054 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07006055 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6056 CodeGenFunction &CGF) const override;
Robert Lytton276c2892013-08-19 09:46:39 +00006057};
6058
Stephen Hines651f13c2014-04-23 16:59:28 -07006059class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006060public:
Stephen Hines651f13c2014-04-23 16:59:28 -07006061 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton276c2892013-08-19 09:46:39 +00006062 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006063};
Robert Lytton645e6fd2013-10-11 10:29:34 +00006064} // End anonymous namespace.
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006065
Robert Lytton276c2892013-08-19 09:46:39 +00006066llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6067 CodeGenFunction &CGF) const {
Robert Lytton276c2892013-08-19 09:46:39 +00006068 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton276c2892013-08-19 09:46:39 +00006069
Robert Lytton645e6fd2013-10-11 10:29:34 +00006070 // Get the VAList.
Robert Lytton276c2892013-08-19 09:46:39 +00006071 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6072 CGF.Int8PtrPtrTy);
6073 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton276c2892013-08-19 09:46:39 +00006074
Robert Lytton645e6fd2013-10-11 10:29:34 +00006075 // Handle the argument.
6076 ABIArgInfo AI = classifyArgumentType(Ty);
6077 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6078 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6079 AI.setCoerceToType(ArgTy);
Robert Lytton276c2892013-08-19 09:46:39 +00006080 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton645e6fd2013-10-11 10:29:34 +00006081 llvm::Value *Val;
Andy Gibbsed9967e2013-10-14 07:02:04 +00006082 uint64_t ArgSize = 0;
Robert Lytton276c2892013-08-19 09:46:39 +00006083 switch (AI.getKind()) {
Robert Lytton276c2892013-08-19 09:46:39 +00006084 case ABIArgInfo::Expand:
Stephen Hines651f13c2014-04-23 16:59:28 -07006085 case ABIArgInfo::InAlloca:
Robert Lytton276c2892013-08-19 09:46:39 +00006086 llvm_unreachable("Unsupported ABI kind for va_arg");
6087 case ABIArgInfo::Ignore:
Robert Lytton645e6fd2013-10-11 10:29:34 +00006088 Val = llvm::UndefValue::get(ArgPtrTy);
6089 ArgSize = 0;
6090 break;
Robert Lytton276c2892013-08-19 09:46:39 +00006091 case ABIArgInfo::Extend:
6092 case ABIArgInfo::Direct:
Robert Lytton645e6fd2013-10-11 10:29:34 +00006093 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6094 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6095 if (ArgSize < 4)
6096 ArgSize = 4;
6097 break;
Robert Lytton276c2892013-08-19 09:46:39 +00006098 case ABIArgInfo::Indirect:
6099 llvm::Value *ArgAddr;
6100 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6101 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton645e6fd2013-10-11 10:29:34 +00006102 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6103 ArgSize = 4;
6104 break;
Robert Lytton276c2892013-08-19 09:46:39 +00006105 }
Robert Lytton645e6fd2013-10-11 10:29:34 +00006106
6107 // Increment the VAList.
6108 if (ArgSize) {
6109 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6110 Builder.CreateStore(APN, VAListAddrAsBPP);
6111 }
6112 return Val;
Robert Lytton276c2892013-08-19 09:46:39 +00006113}
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006114
6115//===----------------------------------------------------------------------===//
6116// Driver code
6117//===----------------------------------------------------------------------===//
6118
Chris Lattnerea044322010-07-29 02:01:43 +00006119const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00006120 if (TheTargetCodeGenInfo)
6121 return *TheTargetCodeGenInfo;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00006122
John McCall64aa4b32013-04-16 22:48:15 +00006123 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar1752ee42009-08-24 09:10:05 +00006124 switch (Triple.getArch()) {
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00006125 default:
Chris Lattnerea044322010-07-29 02:01:43 +00006126 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00006127
Derek Schuff9ed63f82012-09-06 17:37:28 +00006128 case llvm::Triple::le32:
6129 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCallaeeb7012010-05-27 06:19:26 +00006130 case llvm::Triple::mips:
6131 case llvm::Triple::mipsel:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00006132 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
John McCallaeeb7012010-05-27 06:19:26 +00006133
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00006134 case llvm::Triple::mips64:
6135 case llvm::Triple::mips64el:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00006136 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00006137
Stephen Hines651f13c2014-04-23 16:59:28 -07006138 case llvm::Triple::arm64: {
6139 ARM64ABIInfo::ABIKind Kind = ARM64ABIInfo::AAPCS;
6140 if (strcmp(getTarget().getABI(), "darwinpcs") == 0)
6141 Kind = ARM64ABIInfo::DarwinPCS;
6142
6143 return *(TheTargetCodeGenInfo = new ARM64TargetCodeGenInfo(Types, Kind));
6144 }
6145
Tim Northoverc264e162013-01-31 12:13:10 +00006146 case llvm::Triple::aarch64:
Stephen Hines651f13c2014-04-23 16:59:28 -07006147 case llvm::Triple::aarch64_be:
Tim Northoverc264e162013-01-31 12:13:10 +00006148 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
6149
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00006150 case llvm::Triple::arm:
Stephen Hines651f13c2014-04-23 16:59:28 -07006151 case llvm::Triple::armeb:
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00006152 case llvm::Triple::thumb:
Stephen Hines651f13c2014-04-23 16:59:28 -07006153 case llvm::Triple::thumbeb:
Sandeep Patel34c1af82011-04-05 00:23:47 +00006154 {
6155 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCall64aa4b32013-04-16 22:48:15 +00006156 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel34c1af82011-04-05 00:23:47 +00006157 Kind = ARMABIInfo::APCS;
David Tweedb16abb12012-10-25 13:33:01 +00006158 else if (CodeGenOpts.FloatABI == "hard" ||
John McCall64aa4b32013-04-16 22:48:15 +00006159 (CodeGenOpts.FloatABI != "soft" &&
6160 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel34c1af82011-04-05 00:23:47 +00006161 Kind = ARMABIInfo::AAPCS_VFP;
6162
Derek Schuff263366f2012-10-16 22:30:41 +00006163 switch (Triple.getOS()) {
Eli Bendersky441d9f72012-12-04 18:38:10 +00006164 case llvm::Triple::NaCl:
Derek Schuff263366f2012-10-16 22:30:41 +00006165 return *(TheTargetCodeGenInfo =
6166 new NaClARMTargetCodeGenInfo(Types, Kind));
6167 default:
6168 return *(TheTargetCodeGenInfo =
6169 new ARMTargetCodeGenInfo(Types, Kind));
6170 }
Sandeep Patel34c1af82011-04-05 00:23:47 +00006171 }
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00006172
John McCallec853ba2010-03-11 00:10:12 +00006173 case llvm::Triple::ppc:
Chris Lattnerea044322010-07-29 02:01:43 +00006174 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divacky0fbc4b92012-05-09 18:22:46 +00006175 case llvm::Triple::ppc64:
Bill Schmidt2fc107f2012-10-03 19:18:57 +00006176 if (Triple.isOSBinFormatELF())
6177 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
6178 else
6179 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidtea7fb0c2013-07-26 01:36:11 +00006180 case llvm::Triple::ppc64le:
6181 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
6182 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallec853ba2010-03-11 00:10:12 +00006183
Peter Collingbourneedb66f32012-05-20 23:28:41 +00006184 case llvm::Triple::nvptx:
6185 case llvm::Triple::nvptx64:
Justin Holewinski2c585b92012-05-24 17:43:12 +00006186 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinski0259c3a2011-04-22 11:10:38 +00006187
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00006188 case llvm::Triple::msp430:
Chris Lattnerea044322010-07-29 02:01:43 +00006189 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00006190
Ulrich Weigandb8409212013-05-06 16:26:41 +00006191 case llvm::Triple::systemz:
6192 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
6193
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00006194 case llvm::Triple::tce:
6195 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
6196
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00006197 case llvm::Triple::x86: {
John McCallb8b52972013-06-18 02:46:29 +00006198 bool IsDarwinVectorABI = Triple.isOSDarwin();
6199 bool IsSmallStructInRegABI =
6200 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Stephen Hines651f13c2014-04-23 16:59:28 -07006201 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
Daniel Dunbardb57a4c2011-04-19 21:43:27 +00006202
John McCallb8b52972013-06-18 02:46:29 +00006203 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedman55fc7e22012-01-25 22:46:34 +00006204 return *(TheTargetCodeGenInfo =
Reid Kleckner3190ca92013-05-08 13:44:39 +00006205 new WinX86_32TargetCodeGenInfo(Types,
John McCallb8b52972013-06-18 02:46:29 +00006206 IsDarwinVectorABI, IsSmallStructInRegABI,
6207 IsWin32FloatStructABI,
Reid Kleckner3190ca92013-05-08 13:44:39 +00006208 CodeGenOpts.NumRegisterParameters));
John McCallb8b52972013-06-18 02:46:29 +00006209 } else {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00006210 return *(TheTargetCodeGenInfo =
John McCallb8b52972013-06-18 02:46:29 +00006211 new X86_32TargetCodeGenInfo(Types,
6212 IsDarwinVectorABI, IsSmallStructInRegABI,
6213 IsWin32FloatStructABI,
Rafael Espindolab48280b2012-07-31 02:44:24 +00006214 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00006215 }
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00006216 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00006217
Eli Friedmanee1ad992011-12-02 00:11:43 +00006218 case llvm::Triple::x86_64: {
John McCall64aa4b32013-04-16 22:48:15 +00006219 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanee1ad992011-12-02 00:11:43 +00006220
Chris Lattnerf13721d2010-08-31 16:44:54 +00006221 switch (Triple.getOS()) {
6222 case llvm::Triple::Win32:
NAKAMURA Takumi0aa20572011-02-17 08:51:38 +00006223 case llvm::Triple::MinGW32:
Chris Lattnerf13721d2010-08-31 16:44:54 +00006224 case llvm::Triple::Cygwin:
6225 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Bendersky441d9f72012-12-04 18:38:10 +00006226 case llvm::Triple::NaCl:
John McCall64aa4b32013-04-16 22:48:15 +00006227 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
6228 HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00006229 default:
Eli Friedmanee1ad992011-12-02 00:11:43 +00006230 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
6231 HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00006232 }
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00006233 }
Tony Linthicum96319392011-12-12 21:14:55 +00006234 case llvm::Triple::hexagon:
6235 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006236 case llvm::Triple::sparcv9:
6237 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006238 case llvm::Triple::xcore:
Stephen Hines651f13c2014-04-23 16:59:28 -07006239 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanee1ad992011-12-02 00:11:43 +00006240 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00006241}